gemot 0.1.1

Community domain and assembly layer for Moot lifecycle, governance, replication, and Tessera.
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
//! Aggregate domain service for one Moot.
//!
//! This is the application boundary above constitutional governance and the
//! replicated Moot object store. Commands take seeds and domain values, persist
//! through the shared processor, and return plain receipts and snapshots.

use std::io::{Read, Write};
use std::path::Path;

use muniment::{Backend, MemoryBackend, RedbBackend};
use p2panda_core::cbor::{decode_cbor, encode_cbor};
use proofs::Digest;
use serde::{Deserialize, Serialize};
use stickleback::{
    DropExportBudget, DropExportDecision, DropExportProfile, DropExportSelector, DropId,
    DropImportReport, DropLimits, DropProtector, DropRecord, DropWriteReceipt, EvidenceKind,
    MunimentStore, NativeDropError, decode_operation_record, export_topic_operations,
    read_plain_drop, read_protected_drop, write_plain_drop, write_protected_drop,
};

use super::constitution::{
    ConstitutionExt, ConstitutionRules, MootGovernance, MootGovernanceError, MootGovernanceSnapshot,
};
use super::delegation::{
    MootDelegationProjection, MootDelegationStore, MootDelegationStoreError, MootDelegations,
    MootScopeKeyEpoch,
};
use super::group::store::{MootGroupStore, MootGroupStoreError};
use super::group::wire::MootGroupExt;
use super::group::{MootGroup, MootGroupSnapshot, MootMembershipAction};

use super::MootId;
use super::records::{
    AvailabilityPolicy, ErasurePolicy, FaunaEntry, MootEvent, MootRetentionPolicy, MootRoster,
    MootStore, MootStoreError, PolicyRevision,
};
use super::tessera::{
    GateDecision, TesseraEvent, TesseraExt, TesseraFacts, TesseraFileStore, TesseraStore,
    TesseraStoreError, authorize,
};
use super::typed_authorization::MootAuthority;

const CONSTITUTION_EVIDENCE_VERSION: u16 = 1;
const DELEGATION_EVIDENCE_VERSION: u16 = 1;
const DOMAIN_EVIDENCE_VERSION: u16 = 1;

/// Stable privacy and radio-budget priorities for an importable Moot drop.
/// Every selected record remains full-bodied because a signed log with a
/// missing body cannot safely reconstruct governance or roster state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MootDropSelector {
    pub checkpoint_priority: u32,
    pub roster_priority: u32,
    pub fauna_priority: u32,
}

impl Default for MootDropSelector {
    fn default() -> Self {
        Self {
            checkpoint_priority: 100,
            roster_priority: 80,
            fauna_priority: 40,
        }
    }
}

impl DropExportSelector<super::MootExt> for MootDropSelector {
    fn select(&self, operation: &p2panda_core::Operation<super::MootExt>) -> DropExportDecision {
        let priority = match super::from_operation(operation) {
            Ok((_, MootEvent::RetentionCheckpoint { .. })) => self.checkpoint_priority,
            Ok((_, MootEvent::Declared { .. } | MootEvent::Joined { .. })) => self.roster_priority,
            Ok((_, MootEvent::Shared { .. } | MootEvent::HistoryPruned { .. })) => {
                self.fauna_priority
            }
            Err(_) => return DropExportDecision::Omit,
        };
        DropExportDecision::Full { priority }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct ConstitutionEvidence {
    version: u16,
    operations: Vec<DropRecord>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct DelegationEvidence {
    version: u16,
    operations: Vec<DropRecord>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct DomainEvidence {
    version: u16,
    membership_operations: Vec<DropRecord>,
    tessera_operations: Vec<DropRecord>,
}

/// Retention settings supplied by the Moot's governed configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootRetentionSettings {
    pub revision: PolicyRevision,
    pub availability: AvailabilityPolicy,
    pub erasure: ErasurePolicy,
}

impl MootRetentionSettings {
    fn resolve(
        &self,
        checkpoint_authority: super::GovernedCheckpointAuthority,
        checkpoint_authority_history: Vec<super::GovernedCheckpointAuthority>,
    ) -> MootRetentionPolicy {
        MootRetentionPolicy {
            revision: self.revision.clone(),
            checkpoint_authority,
            checkpoint_authority_history,
            availability: self.availability,
            erasure: self.erasure,
        }
    }
}

/// Latest accepted checkpoint, presented without wire-operation types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCheckpointSnapshot {
    pub operation: [u8; 32],
    pub policy_revision: PolicyRevision,
    pub authority_revision: Digest,
    pub previous_checkpoint: Option<[u8; 32]>,
    pub frontier_count: usize,
    pub at_ms: u64,
}

/// Readable current state of one Moot.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootSnapshot {
    pub moot_id: MootId,
    pub governance: MootGovernanceSnapshot,
    /// Signed, converged membership and its retained-operation health.
    pub membership: MootGroupSnapshot,
    pub roster: MootRoster,
    pub checkpoint: Option<MootCheckpointSnapshot>,
    /// Signed delegated certificates retained in the current authority fold.
    pub delegated_certificates: usize,
    /// Signed Tessera operations retained for the Moot's trust projection.
    pub tessera_operations: usize,
}

/// A request to evaluate one capability-scoped community action.
///
/// `subject` is the stable persona-chain root, not the signing key of a single
/// device or session. The capability path remains opaque to Gemot: Meadowcap,
/// a p2panda group-state adapter, or a local policy provider may each give it
/// its own structural meaning.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootAuthorizationRequest {
    pub subject: [u8; 32],
    pub capability_path: String,
    pub at_ms: u64,
}

/// Inputs supplied by the Moot's membership and capability authority.
///
/// The provider answers structural access and supplies the current Tessera
/// facts. Its `facts.is_member` field is the single membership input for a
/// members-only constitution; `capability_covers` is the corresponding scoped
/// live decision. [`Moot::authorize_constitution_grant`] intersects it with the
/// signed constitutional grant state. Key material never crosses this API: a
/// group-key engine may back the provider later without putting decryption
/// authority in Gemot.
#[derive(Clone, Debug, Default)]
pub struct MootAuthorizationInputs {
    pub capability_covers: bool,
    pub facts: TesseraFacts,
}

/// Supplies membership, scoped-capability, and reputation facts at the Moot
/// authorization seam.
///
/// This is deliberately an injected read boundary. The signed constitution
/// chooses the admission policy; the provider is the replaceable source of
/// current group membership and grants. A future p2panda group-state/key
/// adapter belongs here, rather than in the constitution fold or Tessera log.
pub trait MootAuthorizationProvider {
    fn inputs(&self, request: &MootAuthorizationRequest) -> MootAuthorizationInputs;
}

/// Result of an object command. The operation id is enough for citations and
/// outbox tracking while the p2panda operation remains inside the store.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootCommandReceipt {
    pub operation: [u8; 32],
    pub lane: MootLane,
    pub snapshot: MootSnapshot,
}

/// The replicated lane an authored command must be published on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MootLane {
    Membership,
    Objects,
    Tessera,
}

/// A signed operation recovered from a command receipt for host-side live
/// publication. Gemot stays transport-neutral; the host owns the typed handle.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MootOutboundOperation {
    Membership(p2panda_core::Operation<MootGroupExt>),
    Object(p2panda_core::Operation<super::MootExt>),
    Tessera(p2panda_core::Operation<TesseraExt>),
}

/// Native-drop import result plus the refreshed materialized view.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MootDropImportReceipt {
    pub import: DropImportReport,
    pub constitution_operations: u64,
    pub delegation_operations: u64,
    pub membership_operations: u64,
    pub tessera_operations: u64,
    pub snapshot: MootSnapshot,
}

/// Aggregate Moot service failure.
#[derive(Debug, thiserror::Error)]
pub enum MootError {
    #[error(transparent)]
    Governance(#[from] MootGovernanceError),
    #[error(transparent)]
    Store(#[from] MootStoreError),
    #[error(transparent)]
    Tessera(#[from] TesseraStoreError),
    #[error(transparent)]
    Delegation(#[from] MootDelegationStoreError),
    #[error(transparent)]
    Membership(#[from] MootGroupStoreError),
    #[error("moot has no accepted retention checkpoint")]
    CheckpointMissing,
    #[error("moot storage directory: {0}")]
    Io(#[from] std::io::Error),
    #[error(transparent)]
    Drop(#[from] NativeDropError),
    #[error("Moot drop needs full operation bodies")]
    HeaderOnlyDrop,
    #[error("Moot drop selection omitted {0} retained records; increase its byte budget")]
    IncompleteDropBudget(u64),
    #[error("Moot drop is missing critical constitution authority evidence")]
    ConstitutionEvidenceMissing,
    #[error("Moot drop carries malformed constitution authority evidence")]
    ConstitutionEvidenceMalformed,
    #[error("Moot drop carries malformed delegation authority evidence")]
    DelegationEvidenceMalformed,
    #[error("Moot drop carries malformed auxiliary domain evidence")]
    DomainEvidenceMalformed,
    #[error("authored operation is absent from its retained lane")]
    OutboundMissing,
}

/// One Moot's constitutional and replicated object services.
#[derive(Clone)]
pub struct Moot<B> {
    moot_id: MootId,
    governance: MootGovernance<B>,
    objects: MootStore<B>,
    tessera: TesseraStore<B>,
    delegations: MootDelegationStore<B>,
    membership: MootGroupStore<B>,
    retention: MootRetentionSettings,
}

/// Durable redb-backed aggregate Moot service.
pub type MootFile = Moot<RedbBackend>;

impl Moot<MemoryBackend> {
    pub fn in_memory(moot_id: MootId, founder: [u8; 32], retention: MootRetentionSettings) -> Self {
        Self {
            moot_id,
            governance: MootGovernance::in_memory(moot_id.0, founder),
            objects: MootStore::in_memory(),
            tessera: TesseraStore::in_memory(),
            delegations: MootDelegationStore::in_memory(moot_id.0),
            membership: MootGroupStore::in_memory(moot_id.0),
            retention,
        }
    }
}

impl Moot<RedbBackend> {
    /// Open one Moot beneath `directory`. Governance and object data use
    /// separate redb files while presenting one domain service.
    pub async fn open(
        directory: impl AsRef<Path>,
        moot_id: MootId,
        founder: [u8; 32],
        retention: MootRetentionSettings,
    ) -> Result<Self, MootError> {
        std::fs::create_dir_all(directory.as_ref())?;
        let service = Self {
            moot_id,
            governance: MootGovernance::open(
                directory.as_ref().join("constitution.redb"),
                moot_id.0,
                founder,
            )?,
            objects: MootStore::at_path(directory.as_ref().join("objects.redb"))?,
            tessera: TesseraFileStore::open(directory.as_ref().join("tessera.redb"))?,
            delegations: super::delegation::MootDelegationFileStore::open(
                directory.as_ref().join("delegations.redb"),
                moot_id.0,
            )?,
            membership: super::group::store::MootGroupFileStore::open(
                directory.as_ref().join("membership.redb"),
                moot_id.0,
            )?,
            retention,
        };
        match service.governance.snapshot().await {
            Ok(_) => service.refresh_retention_authority().await?,
            Err(MootGovernanceError::NotFounded) => {}
            Err(error) => return Err(error.into()),
        }
        Ok(service)
    }

    /// Reopen one already-founded Moot beneath `directory`.
    ///
    /// The governance founder is recovered from the retained signed genesis,
    /// keeping product bindings free of an independently asserted root key.
    pub async fn open_existing(
        directory: impl AsRef<Path>,
        moot_id: MootId,
        retention: MootRetentionSettings,
    ) -> Result<Self, MootError> {
        let service = Self {
            moot_id,
            governance: MootGovernance::open_existing(
                directory.as_ref().join("constitution.redb"),
                moot_id.0,
            )
            .await?,
            objects: MootStore::at_path(directory.as_ref().join("objects.redb"))?,
            tessera: TesseraFileStore::open(directory.as_ref().join("tessera.redb"))?,
            delegations: super::delegation::MootDelegationFileStore::open(
                directory.as_ref().join("delegations.redb"),
                moot_id.0,
            )?,
            membership: super::group::store::MootGroupFileStore::open(
                directory.as_ref().join("membership.redb"),
                moot_id.0,
            )?,
            retention,
        };
        service.refresh_retention_authority().await?;
        Ok(service)
    }
}

impl<B: Backend + Clone> Moot<B> {
    pub fn moot_id(&self) -> MootId {
        self.moot_id
    }

    /// Constitution lane for host-composed LogSync publication.
    pub fn constitution_store(&self) -> MunimentStore<B, ConstitutionExt> {
        self.governance.sync_store()
    }

    /// Lower store boundary for host-composed LogSync and native-drop adapters.
    pub fn object_store(&self) -> &MootStore<B> {
        &self.objects
    }

    /// Lower store boundary for a host-composed Tessera LogSync session.
    pub fn tessera_store(&self) -> &TesseraStore<B> {
        &self.tessera
    }

    /// Independent delegation lane for host-composed LogSync publication.
    pub fn delegation_store(&self) -> &MootDelegationStore<B> {
        &self.delegations
    }

    /// The governance service, for the constitution lane's accept path.
    pub fn governance(&self) -> &MootGovernance<B> {
        &self.governance
    }

    /// Independent membership lane for host-composed LogSync publication.
    pub fn membership_store(&self) -> &MootGroupStore<B> {
        &self.membership
    }

    /// Current effective p2panda-auth membership.
    pub async fn membership(&self) -> Result<MootGroup, MootError> {
        Ok(self.membership.group().await?)
    }

    async fn refresh_retention_authority(&self) -> Result<(), MootError> {
        let authority = self.governance.checkpoint_authority().await?;
        let history = self.governance.checkpoint_authority_history().await?;
        self.objects
            .set_retention_policy(Some(self.retention.resolve(authority, history)));
        Ok(())
    }

    /// Establish this Moot's first constitution and activate its checkpoint
    /// authority for subsequent object commands.
    pub async fn found(
        &self,
        founder_seed: [u8; 32],
        parent_constitution: Option<Digest>,
        divergence_point: Option<Digest>,
        rules: ConstitutionRules,
        at_ms: u64,
    ) -> Result<MootSnapshot, MootError> {
        self.governance
            .found(
                founder_seed,
                parent_constitution,
                divergence_point,
                rules,
                at_ms,
            )
            .await?;
        self.refresh_retention_authority().await?;
        self.snapshot().await
    }

    /// Amend the constitution and atomically switch future checkpoint
    /// admission to the accepted authority revision.
    pub async fn amend(
        &self,
        actor_seed: [u8; 32],
        rules: ConstitutionRules,
        at_ms: u64,
    ) -> Result<MootSnapshot, MootError> {
        self.governance.amend(actor_seed, rules, at_ms).await?;
        self.refresh_retention_authority().await?;
        self.snapshot().await
    }

    /// Evaluate a capability-scoped action under the currently accepted,
    /// signed admission rule.
    ///
    /// The provider supplies mutable membership/capability facts; the rule it
    /// is evaluated against comes only from the accepted constitution. This
    /// prevents a host from quietly changing a Moot from open to members-only
    /// or weakening its standing floor outside the replicated law.
    pub async fn authorize<P: MootAuthorizationProvider>(
        &self,
        provider: &P,
        request: &MootAuthorizationRequest,
    ) -> Result<GateDecision, MootError> {
        let policy = self.governance.snapshot().await?.rules.admission;
        let inputs = provider.inputs(request);
        Ok(authorize(
            &policy,
            inputs.capability_covers,
            &inputs.facts,
            request.at_ms,
        ))
    }

    /// Evaluate a current signed constitutional grant and a provider's live
    /// structural decision together.
    ///
    /// Both checks must pass. The constitutional grant is portable, signed
    /// authority; the provider supplies the present group/session condition
    /// that can narrow it immediately. This permits future group-key rotation
    /// or local device policy to deny access without rewriting constitutional
    /// history.
    pub async fn authorize_constitution_grant<P: MootAuthorizationProvider>(
        &self,
        provider: &P,
        request: &MootAuthorizationRequest,
    ) -> Result<GateDecision, MootError> {
        let governance = self.governance.snapshot().await?;
        let inputs = provider.inputs(request);
        let grant_covers =
            governance
                .rules
                .grant_covers(request.subject, &request.capability_path, request.at_ms);
        Ok(authorize(
            &governance.rules.admission,
            grant_covers && inputs.capability_covers,
            &inputs.facts,
            request.at_ms,
        ))
    }

    /// Evaluate independently delegated authority and the provider's current
    /// structural decision under the accepted constitutional admission rule.
    pub async fn delegations(&self) -> Result<MootDelegations, MootError> {
        let rules = self.governance.snapshot().await?.rules;
        Ok(self.delegations.delegations(&rules).await?)
    }

    /// Deterministic authority projections for a participant graph. Callers
    /// may replace their projection nodes from this value, never petition the
    /// graph to mutate the underlying authority ledger.
    pub async fn delegation_projections(
        &self,
        at_ms: u64,
    ) -> Result<Vec<MootDelegationProjection>, MootError> {
        let rules = self.governance.snapshot().await?.rules;
        Ok(self
            .delegations
            .delegations(&rules)
            .await?
            .projections(self.moot_id.0, &rules, at_ms))
    }

    /// Scope-key epochs the host encryption engine must bind and distribute.
    pub async fn delegation_scope_key_epochs(&self) -> Result<Vec<MootScopeKeyEpoch>, MootError> {
        Ok(self.delegations().await?.scope_key_epochs())
    }

    /// Evaluate the aggregate's retained independent delegation lane.
    pub async fn authorize_current_delegated<P: MootAuthorizationProvider>(
        &self,
        provider: &P,
        request: &MootAuthorizationRequest,
    ) -> Result<GateDecision, MootError> {
        let governance = self.governance.snapshot().await?;
        let delegations = self.delegations.delegations(&governance.rules).await?;
        self.authorize_delegated(&delegations, provider, request)
            .await
    }

    /// Evaluate caller-supplied delegated authority. Prefer
    /// [`Self::authorize_current_delegated`] for the aggregate-owned lane.
    pub async fn authorize_delegated<P: MootAuthorizationProvider>(
        &self,
        delegations: &super::MootDelegations,
        provider: &P,
        request: &MootAuthorizationRequest,
    ) -> Result<GateDecision, MootError> {
        let governance = self.governance.snapshot().await?;
        let inputs = provider.inputs(request);
        let grant_covers = delegations.covers(
            self.moot_id.0,
            &governance.rules,
            request.subject,
            &request.capability_path,
            request.at_ms,
        );
        Ok(authorize(
            &governance.rules.admission,
            grant_covers && inputs.capability_covers,
            &inputs.facts,
            request.at_ms,
        ))
    }

    pub async fn declare(
        &self,
        actor_seed: [u8; 32],
        name: String,
        charter: String,
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        self.author_object(
            actor_seed,
            MootEvent::Declared {
                name,
                charter,
                at_ms,
            },
        )
        .await
    }

    pub async fn join(
        &self,
        actor_seed: [u8; 32],
        name: String,
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        self.author_object(actor_seed, MootEvent::Joined { name, at_ms })
            .await
    }

    pub async fn share(
        &self,
        actor_seed: [u8; 32],
        manifest_id: [u8; 32],
        schema_id: String,
        title: String,
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        self.author_object(
            actor_seed,
            MootEvent::Shared {
                manifest_id,
                schema_id,
                title,
                at_ms,
            },
        )
        .await
    }

    async fn author_object(
        &self,
        actor_seed: [u8; 32],
        event: MootEvent,
    ) -> Result<MootCommandReceipt, MootError> {
        let operation = self
            .objects
            .author_seed(actor_seed, self.moot_id.0, &event)
            .await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            lane: MootLane::Objects,
            snapshot: self.snapshot().await?,
        })
    }

    /// Author a membership change directly under a stable identity key.
    pub async fn update_membership(
        &self,
        actor_seed: [u8; 32],
        action: MootMembershipAction,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        let operation = self.membership.author_seed(actor_seed, action).await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            lane: MootLane::Membership,
            snapshot: self.snapshot().await?,
        })
    }

    /// Author a membership change under a Moot-derived key certified by the
    /// stable Personae root.
    pub async fn update_membership_for_identity<P: identity::IdentityProvider + ?Sized>(
        &self,
        identity: &P,
        action: MootMembershipAction,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        let operation = self
            .membership
            .author_for_identity(identity, action)
            .await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            lane: MootLane::Membership,
            snapshot: self.snapshot().await?,
        })
    }

    /// Record one Tessera fact through the same aggregate command surface.
    /// The receipt can be resolved with [`outbound`](Self::outbound) and
    /// published by the host on its Tessera LogSync handle.
    pub async fn record_tessera(
        &self,
        actor_seed: [u8; 32],
        event: TesseraEvent,
    ) -> Result<MootCommandReceipt, MootError> {
        self.governance.snapshot().await?;
        let operation = self
            .tessera
            .author_seed(actor_seed, self.moot_id.0, &event)
            .await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            lane: MootLane::Tessera,
            snapshot: self.snapshot().await?,
        })
    }

    /// Recover an authored operation for host-side publication. This is the
    /// only operation-typed aggregate API: transport ownership stays outside
    /// Gemot while commands and receipts stay plain.
    pub async fn outbound(
        &self,
        receipt: &MootCommandReceipt,
    ) -> Result<MootOutboundOperation, MootError> {
        let hash = p2panda_core::Hash::from_bytes(receipt.operation);
        match receipt.lane {
            MootLane::Membership => self
                .membership
                .get(&hash)
                .await?
                .map(MootOutboundOperation::Membership)
                .ok_or(MootError::OutboundMissing),
            MootLane::Objects => self
                .objects
                .operation(&hash)
                .await?
                .map(MootOutboundOperation::Object)
                .ok_or(MootError::OutboundMissing),
            MootLane::Tessera => self
                .tessera
                .get(&hash)
                .await?
                .map(MootOutboundOperation::Tessera)
                .ok_or(MootError::OutboundMissing),
        }
    }

    /// Author the next checkpoint under the currently accepted constitution.
    pub async fn checkpoint(
        &self,
        actor_seed: [u8; 32],
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        self.refresh_retention_authority().await?;
        let checkpoint = self.objects.build_checkpoint(self.moot_id.0, at_ms).await?;
        self.author_object(
            actor_seed,
            MootEvent::RetentionCheckpoint {
                checkpoint: Box::new(checkpoint),
            },
        )
        .await
    }

    /// Retire this actor's event prefix at the latest accepted checkpoint.
    pub async fn prune_current(
        &self,
        actor_seed: [u8; 32],
        at_ms: u64,
    ) -> Result<MootCommandReceipt, MootError> {
        let checkpoint = self
            .objects
            .latest_checkpoint(self.moot_id.0)
            .await?
            .ok_or(MootError::CheckpointMissing)?;
        let operation = self
            .objects
            .author_prune_seed(actor_seed, self.moot_id.0, checkpoint.operation, at_ms)
            .await?;
        Ok(MootCommandReceipt {
            operation: *operation.hash.as_bytes(),
            lane: MootLane::Objects,
            snapshot: self.snapshot().await?,
        })
    }

    async fn aggregate_drop_records(
        &self,
        selector: &MootDropSelector,
        budget: DropExportBudget,
    ) -> Result<Vec<DropRecord>, MootError> {
        let evidence = ConstitutionEvidence {
            version: CONSTITUTION_EVIDENCE_VERSION,
            operations: self.governance.drop_records().await?,
        };
        let evidence_bytes =
            encode_cbor(&evidence).map_err(|_| MootError::ConstitutionEvidenceMalformed)?;
        let mut records = vec![DropRecord::Evidence {
            kind: EvidenceKind::CheckpointAuthorization,
            subject: self.moot_id.0,
            bytes: evidence_bytes,
            critical: true,
        }];
        let delegation = DelegationEvidence {
            version: DELEGATION_EVIDENCE_VERSION,
            operations: self.delegations.drop_records().await?,
        };
        let delegation_bytes =
            encode_cbor(&delegation).map_err(|_| MootError::DelegationEvidenceMalformed)?;
        records.push(DropRecord::Evidence {
            kind: EvidenceKind::CapabilityChain,
            subject: self.moot_id.0,
            bytes: delegation_bytes,
            critical: true,
        });
        let domains = DomainEvidence {
            version: DOMAIN_EVIDENCE_VERSION,
            membership_operations: self.membership.drop_records().await?,
            tessera_operations: export_topic_operations::<B, TesseraExt, u64>(
                &self.tessera.sync_store(),
                &p2panda_core::Topic::from(self.moot_id.0),
                DropExportProfile::default(),
            )
            .await
            .map_err(|_| MootError::DomainEvidenceMalformed)?,
        };
        let domain_bytes = encode_cbor(&domains).map_err(|_| MootError::DomainEvidenceMalformed)?;
        records.push(DropRecord::Evidence {
            kind: EvidenceKind::DomainOperations,
            subject: self.moot_id.0,
            bytes: domain_bytes,
            critical: true,
        });
        let (objects, selection) = self
            .objects
            .export_selected_drop_records(self.moot_id.0, selector, budget)
            .await?;
        if selection.budget_omitted != 0 || selection.policy_omitted != 0 {
            return Err(MootError::IncompleteDropBudget(
                selection.budget_omitted + selection.policy_omitted,
            ));
        }
        records.extend(objects);
        Ok(records)
    }

    fn constitution_evidence(&self, records: &[DropRecord]) -> Result<Vec<DropRecord>, MootError> {
        let mut found = None;
        for record in records {
            let DropRecord::Evidence {
                kind: EvidenceKind::CheckpointAuthorization,
                subject,
                bytes,
                critical: true,
            } = record
            else {
                continue;
            };
            if *subject != self.moot_id.0 || found.is_some() {
                return Err(MootError::ConstitutionEvidenceMalformed);
            }
            let evidence: ConstitutionEvidence =
                decode_cbor(&bytes[..]).map_err(|_| MootError::ConstitutionEvidenceMalformed)?;
            if evidence.version != CONSTITUTION_EVIDENCE_VERSION
                || encode_cbor(&evidence).ok().as_deref() != Some(bytes.as_slice())
            {
                return Err(MootError::ConstitutionEvidenceMalformed);
            }
            found = Some(evidence.operations);
        }
        found.ok_or(MootError::ConstitutionEvidenceMissing)
    }

    fn delegation_evidence(&self, records: &[DropRecord]) -> Result<Vec<DropRecord>, MootError> {
        let mut found = None;
        for record in records {
            let DropRecord::Evidence {
                kind: EvidenceKind::CapabilityChain,
                subject,
                bytes,
                critical: true,
            } = record
            else {
                continue;
            };
            if *subject != self.moot_id.0 || found.is_some() {
                return Err(MootError::DelegationEvidenceMalformed);
            }
            let evidence: DelegationEvidence =
                decode_cbor(&bytes[..]).map_err(|_| MootError::DelegationEvidenceMalformed)?;
            if evidence.version != DELEGATION_EVIDENCE_VERSION
                || encode_cbor(&evidence).ok().as_deref() != Some(bytes.as_slice())
            {
                return Err(MootError::DelegationEvidenceMalformed);
            }
            found = Some(evidence.operations);
        }
        Ok(found.unwrap_or_default())
    }

    fn domain_evidence(&self, records: &[DropRecord]) -> Result<DomainEvidence, MootError> {
        let mut found = None;
        for record in records {
            let DropRecord::Evidence {
                kind: EvidenceKind::DomainOperations,
                subject,
                bytes,
                critical: true,
            } = record
            else {
                continue;
            };
            if *subject != self.moot_id.0 || found.is_some() {
                return Err(MootError::DomainEvidenceMalformed);
            }
            let evidence: DomainEvidence =
                decode_cbor(&bytes[..]).map_err(|_| MootError::DomainEvidenceMalformed)?;
            if evidence.version != DOMAIN_EVIDENCE_VERSION
                || encode_cbor(&evidence).ok().as_deref() != Some(bytes.as_slice())
            {
                return Err(MootError::DomainEvidenceMalformed);
            }
            found = Some(evidence);
        }
        Ok(found.unwrap_or(DomainEvidence {
            version: DOMAIN_EVIDENCE_VERSION,
            membership_operations: Vec::new(),
            tessera_operations: Vec::new(),
        }))
    }

    async fn accept_tessera_drop_records(&self, records: &[DropRecord]) -> Result<u64, MootError> {
        let mut accepted = 0;
        for record in records {
            let Some(operation) = decode_operation_record::<TesseraExt>(record)
                .map_err(|_| MootError::DomainEvidenceMalformed)?
            else {
                continue;
            };
            if operation.body.is_none() {
                return Err(MootError::DomainEvidenceMalformed);
            }
            accepted += u64::from(self.tessera.accept(self.moot_id.0, &operation).await?);
        }
        Ok(accepted)
    }

    async fn import_aggregate_records(
        &self,
        drop_id: DropId,
        records: Vec<DropRecord>,
    ) -> Result<MootDropImportReceipt, MootError> {
        let evidence = self.constitution_evidence(&records)?;
        let constitution_operations = self.governance.accept_drop_records(&evidence).await?;
        let delegation_evidence = self.delegation_evidence(&records)?;
        let delegation_operations = self
            .delegations
            .accept_drop_records(&delegation_evidence)
            .await?;
        let domains = self.domain_evidence(&records)?;
        let membership_operations = self
            .membership
            .accept_drop_records(&domains.membership_operations)
            .await?;
        let tessera_operations = self
            .accept_tessera_drop_records(&domains.tessera_operations)
            .await?;
        // The evidence becomes active before the object lane examines its
        // checkpoint chain. This is the dependency order a fresh device needs
        // after a signer rotation.
        self.refresh_retention_authority().await?;
        let import = self
            .objects
            .import_drop_records(self.moot_id.0, drop_id, records)
            .await?;
        Ok(MootDropImportReceipt {
            import,
            constitution_operations,
            delegation_operations,
            membership_operations,
            tessera_operations,
            snapshot: self.snapshot().await?,
        })
    }

    /// Export public or explicitly local Moot state as a self-contained native
    /// drop. The carrier includes critical constitution authority evidence.
    pub async fn export_plain_drop<W: Write>(
        &self,
        writer: &mut W,
        profile: DropExportProfile,
        limits: DropLimits,
    ) -> Result<DropWriteReceipt, MootError> {
        if !profile.include_operation_bodies {
            return Err(MootError::HeaderOnlyDrop);
        }
        let records = self
            .aggregate_drop_records(&MootDropSelector::default(), DropExportBudget::default())
            .await?;
        Ok(write_plain_drop(writer, &records, limits)?)
    }

    /// Export a protected, importable Moot drop. A caller supplies its group
    /// protection suite; Gemot never picks keys or silently falls back to
    /// plaintext.
    pub async fn export_protected_drop<W: Write, D: DropProtector>(
        &self,
        writer: &mut W,
        selector: &MootDropSelector,
        budget: DropExportBudget,
        limits: DropLimits,
        protector: &D,
    ) -> Result<DropWriteReceipt, MootError> {
        let records = self.aggregate_drop_records(selector, budget).await?;
        Ok(write_protected_drop(writer, &records, limits, protector)?)
    }

    /// Import a self-contained plaintext/public Moot drop. Critical
    /// constitution evidence is admitted before the checkpoint chain.
    pub async fn import_plain_drop<R: Read>(
        &self,
        reader: R,
        limits: DropLimits,
    ) -> Result<MootDropImportReceipt, MootError> {
        let (read, records) = read_plain_drop(reader, limits)?;
        self.import_aggregate_records(read.id, records).await
    }

    /// Import a protected Moot drop through the caller's group-key suite.
    pub async fn import_protected_drop<R: Read, D: DropProtector>(
        &self,
        reader: R,
        limits: DropLimits,
        protector: &D,
    ) -> Result<MootDropImportReceipt, MootError> {
        let (read, records) = read_protected_drop(reader, limits, protector)?;
        self.import_aggregate_records(read.id, records).await
    }

    /// The moot's commons **as converged authority sees it**: fauna entries
    /// whose sharer holds the typed `moot/fauna` capability at `at_ms`.
    ///
    /// Today `MootPolicy::admit` accepts a `Shared` event on wire grammar and
    /// moot address alone, so the raw
    /// [`roster.fauna`](super::MootRoster::fauna) is *everything anyone put
    /// there*. This is the authorized view over it, evaluated at read for the
    /// reason recorded on
    /// [`MootRoster::authorized_fauna`](super::MootRoster::authorized_fauna):
    /// authority converges separately from the operations it authorizes, so
    /// refusing at admission would discard operations that become authorized
    /// a moment later.
    ///
    /// Both views are deliberately available. Which one a surface shows is a
    /// product call — the unfiltered record lets a UI show an unauthorized
    /// contribution as *pending* rather than making it vanish.
    pub async fn authorized_fauna(&self, at_ms: u64) -> Result<Vec<FaunaEntry>, MootError> {
        let rules = self.governance.snapshot().await?.rules;
        let delegations = self.delegations.delegations(&rules).await?;
        let roster = self.objects.roster(self.moot_id.0).await?;
        let authority = MootAuthority {
            delegations: &delegations,
            rules: &rules,
            moot_id: self.moot_id.0,
            now_ms: at_ms,
        };
        Ok(roster
            .authorized_fauna(&authority)
            .into_iter()
            .cloned()
            .collect())
    }

    pub async fn snapshot(&self) -> Result<MootSnapshot, MootError> {
        let governance = self.governance.snapshot().await?;
        let membership = self.membership.snapshot().await?;
        let roster = self.objects.roster(self.moot_id.0).await?;
        let checkpoint = self
            .objects
            .latest_checkpoint(self.moot_id.0)
            .await?
            .map(|stored| MootCheckpointSnapshot {
                operation: stored.operation,
                policy_revision: stored.checkpoint.policy_revision,
                authority_revision: stored.checkpoint.authority_revision,
                previous_checkpoint: stored.checkpoint.previous_checkpoint,
                frontier_count: stored.checkpoint.frontier.len(),
                at_ms: stored.checkpoint.at_ms,
            });
        let delegated_certificates = self
            .delegations
            .delegations(&governance.rules)
            .await?
            .certificate_count();
        let tessera_operations = self.tessera.len().await?;
        Ok(MootSnapshot {
            moot_id: self.moot_id,
            governance,
            membership,
            roster,
            checkpoint,
            delegated_certificates,
            tessera_operations,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::moot::constitution::CapabilityGrant;
    use crate::moot::delegation::{MOOT_ACT_ACTION, MOOT_DELEGATION_DOMAIN};
    use crate::moot::tessera::{
        ChainRoot, DenyReason, GateConfig, GateDecision, Policy, TesseraEvent, TesseraFacts,
    };
    use crate::moot::{
        KeepBound, MootAccessLevel, MootMember, MootMembershipAction, MootStoreError,
    };
    use identity::delegation::{
        CapabilityScope, DelegationCertificate, DelegationParent, DelegationRevocation,
        SignedDelegationCertificate, SignedDelegationRevocation, delegation_signing_salt,
    };
    use identity::{IdentityProvider, InMemoryProvider};
    use std::io::Cursor;
    use stickleback::NativeDropError;

    const ID: MootId = MootId([0x6d; 32]);

    fn keypair(seed: u8) -> identity::Ed25519Keypair {
        InMemoryProvider::from_seed([seed; 32])
            .derive_keypair(b"moot-service")
            .unwrap()
    }

    fn retention() -> MootRetentionSettings {
        MootRetentionSettings {
            revision: PolicyRevision(Digest::blake3(b"moot retention settings")),
            availability: AvailabilityPolicy {
                promised_floor: KeepBound::Forever,
            },
            erasure: ErasurePolicy {
                history_ceiling: KeepBound::UntilCheckpoint,
            },
        }
    }

    struct Access {
        capability_covers: bool,
        facts: TesseraFacts,
    }

    impl MootAuthorizationProvider for Access {
        fn inputs(&self, _: &MootAuthorizationRequest) -> MootAuthorizationInputs {
            MootAuthorizationInputs {
                capability_covers: self.capability_covers,
                facts: self.facts.clone(),
            }
        }
    }

    struct TestProtector;

    impl DropProtector for TestProtector {
        fn suite_id(&self) -> u16 {
            77
        }

        fn protect(&self, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>, NativeDropError> {
            Ok(plaintext
                .iter()
                .enumerate()
                .map(|(index, byte)| byte ^ aad[index % aad.len()])
                .collect())
        }

        fn unprotect(
            &self,
            protected: &[u8],
            aad: &[u8],
            max_plaintext_bytes: u64,
        ) -> Result<Vec<u8>, NativeDropError> {
            if protected.len() as u64 > max_plaintext_bytes {
                return Err(NativeDropError::Limit {
                    limit: "test plaintext bytes",
                    actual: protected.len() as u64,
                    maximum: max_plaintext_bytes,
                });
            }
            self.protect(protected, aad)
        }
    }

    #[tokio::test]
    async fn one_service_runs_governance_roster_checkpoint_and_rotation() {
        let founder = keypair(1);
        let successor = keypair(2);
        let service = Moot::in_memory(ID, founder.public_key().to_bytes(), retention());
        service
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder.public_key().to_bytes()),
                1,
            )
            .await
            .unwrap();
        service
            .declare(
                founder.to_seed(),
                "printing circle".into(),
                "shared type".into(),
                2,
            )
            .await
            .unwrap();
        service
            .join(founder.to_seed(), "mark".into(), 3)
            .await
            .unwrap();
        let first = service.checkpoint(founder.to_seed(), 10).await.unwrap();

        let mut rotated = ConstitutionRules::founder_only(founder.public_key().to_bytes());
        rotated.checkpoint_signers.clear();
        rotated
            .checkpoint_signers
            .insert(successor.public_key().to_bytes());
        service.amend(founder.to_seed(), rotated, 11).await.unwrap();
        assert!(matches!(
            service.checkpoint(founder.to_seed(), 12).await,
            Err(MootError::Store(MootStoreError::Process(_)))
        ));
        let second = service.checkpoint(successor.to_seed(), 13).await.unwrap();
        assert_eq!(
            second
                .snapshot
                .checkpoint
                .as_ref()
                .unwrap()
                .previous_checkpoint,
            Some(first.operation)
        );

        service.prune_current(founder.to_seed(), 14).await.unwrap();
        let snapshot = service.snapshot().await.unwrap();
        assert_eq!(snapshot.roster.declaration.unwrap().name, "printing circle");
        assert_eq!(snapshot.roster.members.len(), 1);
        assert_eq!(snapshot.checkpoint.unwrap().operation, second.operation);
    }

    #[tokio::test]
    async fn signed_admission_rule_uses_the_injected_membership_and_capability_inputs() {
        let founder = keypair(8);
        let founder_id = founder.public_key().to_bytes();
        let service = Moot::in_memory(ID, founder_id, retention());
        let mut rules = ConstitutionRules::founder_only(founder_id);
        rules.admission = Policy::MembersOnly {
            rate_limit: 20,
            rate_window_ms: 60_000,
        };
        service
            .found(founder.to_seed(), None, None, rules, 1)
            .await
            .unwrap();
        let request = MootAuthorizationRequest {
            subject: [9; 32],
            capability_path: "moot/fauna/write".into(),
            at_ms: 10,
        };

        assert_eq!(
            service
                .authorize(
                    &Access {
                        capability_covers: false,
                        facts: TesseraFacts {
                            is_member: true,
                            ..Default::default()
                        },
                    },
                    &request,
                )
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );
        assert_eq!(
            service
                .authorize(
                    &Access {
                        capability_covers: true,
                        facts: TesseraFacts {
                            score: 1,
                            ..Default::default()
                        },
                    },
                    &request,
                )
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NotAMember)
        );
        assert_eq!(
            service
                .authorize(
                    &Access {
                        capability_covers: true,
                        facts: TesseraFacts {
                            is_member: true,
                            ..Default::default()
                        },
                    },
                    &request,
                )
                .await
                .unwrap(),
            GateDecision::Allow
        );

        let mut amended = ConstitutionRules::founder_only(founder_id);
        amended.admission = Policy::OpenWithFloor(GateConfig {
            posting_threshold: 2,
            rate_limit: 20,
            rate_window_ms: 60_000,
        });
        service.amend(founder.to_seed(), amended, 11).await.unwrap();
        assert_eq!(
            service
                .authorize(
                    &Access {
                        capability_covers: true,
                        facts: TesseraFacts {
                            score: 1,
                            is_member: true,
                            ..Default::default()
                        },
                    },
                    &request,
                )
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::BelowThreshold)
        );
    }

    #[tokio::test]
    async fn constitutional_grants_narrow_live_capability_inputs_and_revoke_by_amendment() {
        let founder = keypair(9);
        let founder_id = founder.public_key().to_bytes();
        let service = Moot::in_memory(ID, founder_id, retention());
        let grant_id = [0xa9; 32];
        let mut rules = ConstitutionRules::founder_only(founder_id);
        rules.admission = Policy::MembersOnly {
            rate_limit: 20,
            rate_window_ms: 60_000,
        };
        rules.grant(CapabilityGrant {
            id: grant_id,
            subject: [9; 32],
            path_prefix: "moot/fauna".into(),
            not_before_ms: 5,
            expires_at_ms: Some(20),
            delegation_depth: 0,
        });
        service
            .found(founder.to_seed(), None, None, rules.clone(), 1)
            .await
            .unwrap();
        let member = Access {
            capability_covers: true,
            facts: TesseraFacts {
                is_member: true,
                ..Default::default()
            },
        };
        let request = MootAuthorizationRequest {
            subject: [9; 32],
            capability_path: "moot/fauna/write".into(),
            at_ms: 10,
        };
        assert_eq!(
            service
                .authorize_constitution_grant(&member, &request)
                .await
                .unwrap(),
            GateDecision::Allow
        );

        let sibling = MootAuthorizationRequest {
            capability_path: "moot/faunarium/write".into(),
            ..request.clone()
        };
        assert_eq!(
            service
                .authorize_constitution_grant(&member, &sibling)
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );
        let expired = MootAuthorizationRequest {
            at_ms: 21,
            ..request.clone()
        };
        assert_eq!(
            service
                .authorize_constitution_grant(&member, &expired)
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );

        rules.revoke_grant(&grant_id);
        service.amend(founder.to_seed(), rules, 22).await.unwrap();
        assert_eq!(
            service
                .authorize_constitution_grant(&member, &request)
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );
    }

    #[tokio::test]
    async fn delegated_grants_intersect_constitution_group_and_admission() {
        let founder = keypair(10);
        let founder_id = founder.public_key().to_bytes();
        let root_holder = InMemoryProvider::from_seed([0x31; 32]);
        let delegate = InMemoryProvider::from_seed([0x32; 32]);
        let root_id = [0xb1; 32];
        let service = Moot::in_memory(ID, founder_id, retention());
        let mut rules = ConstitutionRules::founder_only(founder_id);
        rules.admission = Policy::MembersOnly {
            rate_limit: 20,
            rate_window_ms: 60_000,
        };
        rules.grant(CapabilityGrant {
            id: root_id,
            subject: root_holder.master_public_key().to_bytes(),
            path_prefix: "moot/fauna".into(),
            not_before_ms: 5,
            expires_at_ms: Some(100),
            delegation_depth: 2,
        });
        service
            .found(founder.to_seed(), None, None, rules.clone(), 1)
            .await
            .unwrap();

        let scope = CapabilityScope {
            domain: MOOT_DELEGATION_DOMAIN.into(),
            resource: ID.0.to_vec(),
            path_prefix: "moot/fauna/research".into(),
            actions: [MOOT_ACT_ACTION.to_string()].into_iter().collect(),
        };
        let certificate = DelegationCertificate::new(
            DelegationParent::Root(root_id),
            root_holder.master_public_key().to_bytes(),
            delegate.master_public_key().to_bytes(),
            scope.clone(),
            5,
            10,
            Some(90),
            1,
            [0x41; 32],
        );
        let delegation_key = root_holder
            .derive_keypair(&delegation_signing_salt(&scope))
            .unwrap();
        service
            .delegation_store()
            .author_issue(
                &delegation_key,
                &rules,
                SignedDelegationCertificate::issue(&root_holder, certificate).unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(service.snapshot().await.unwrap().delegated_certificates, 1);
        let request = MootAuthorizationRequest {
            subject: delegate.master_public_key().to_bytes(),
            capability_path: "moot/fauna/research/write".into(),
            at_ms: 50,
        };
        let member = Access {
            capability_covers: true,
            facts: TesseraFacts {
                is_member: true,
                ..Default::default()
            },
        };
        assert_eq!(
            service
                .authorize_current_delegated(&member, &request)
                .await
                .unwrap(),
            GateDecision::Allow
        );
        assert_eq!(
            service
                .authorize_current_delegated(
                    &Access {
                        capability_covers: false,
                        facts: member.facts.clone(),
                    },
                    &request,
                )
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );

        rules.revoke_grant(&root_id);
        service.amend(founder.to_seed(), rules, 101).await.unwrap();
        assert_eq!(
            service
                .authorize_current_delegated(&member, &request)
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );
    }

    #[tokio::test]
    async fn native_drop_bootstraps_independent_delegation_authority() {
        let founder = keypair(11);
        let founder_id = founder.public_key().to_bytes();
        let root_holder = InMemoryProvider::from_seed([0x51; 32]);
        let delegate = InMemoryProvider::from_seed([0x52; 32]);
        let root_id = [0xc1; 32];
        let mut rules = ConstitutionRules::founder_only(founder_id);
        rules.grant(CapabilityGrant {
            id: root_id,
            subject: root_holder.master_public_key().to_bytes(),
            path_prefix: "moot/fauna".into(),
            not_before_ms: 1,
            expires_at_ms: Some(100),
            delegation_depth: 1,
        });
        let source = Moot::in_memory(ID, founder_id, retention());
        source
            .found(founder.to_seed(), None, None, rules.clone(), 1)
            .await
            .unwrap();
        let scope = CapabilityScope {
            domain: MOOT_DELEGATION_DOMAIN.into(),
            resource: ID.0.to_vec(),
            path_prefix: "moot/fauna/notes".into(),
            actions: [MOOT_ACT_ACTION.to_string()].into_iter().collect(),
        };
        let signed = SignedDelegationCertificate::issue(
            &root_holder,
            DelegationCertificate::new(
                DelegationParent::Root(root_id),
                root_holder.master_public_key().to_bytes(),
                delegate.master_public_key().to_bytes(),
                scope.clone(),
                2,
                3,
                Some(90),
                0,
                [0x53; 32],
            ),
        )
        .unwrap();
        let certificate_id = signed.certificate.id();
        let delegation_key = root_holder
            .derive_keypair(&delegation_signing_salt(&scope))
            .unwrap();
        source
            .delegation_store()
            .author_issue(&delegation_key, &rules, signed)
            .await
            .unwrap();

        let mut bytes = Vec::new();
        source
            .export_plain_drop(
                &mut bytes,
                DropExportProfile::default(),
                DropLimits::default(),
            )
            .await
            .unwrap();
        let target = Moot::in_memory(ID, founder_id, retention());
        let receipt = target
            .import_plain_drop(Cursor::new(bytes), DropLimits::default())
            .await
            .unwrap();
        assert_eq!(receipt.delegation_operations, 1);
        assert_eq!(receipt.snapshot.delegated_certificates, 1);
        assert_eq!(
            target
                .authorize_current_delegated(
                    &Access {
                        capability_covers: true,
                        facts: TesseraFacts {
                            score: 1,
                            ..Default::default()
                        },
                    },
                    &MootAuthorizationRequest {
                        subject: delegate.master_public_key().to_bytes(),
                        capability_path: "moot/fauna/notes/write".into(),
                        at_ms: 50,
                    },
                )
                .await
                .unwrap(),
            GateDecision::Allow
        );

        let revocation = SignedDelegationRevocation::issue(
            &root_holder,
            DelegationRevocation::new(
                certificate_id,
                root_holder.master_public_key().to_bytes(),
                scope.clone(),
                60,
                [0x54; 32],
            ),
        )
        .unwrap();
        source
            .delegation_store()
            .author_revoke(&delegation_key, &rules, revocation)
            .await
            .unwrap();
        let mut revoked_bytes = Vec::new();
        source
            .export_plain_drop(
                &mut revoked_bytes,
                DropExportProfile::default(),
                DropLimits::default(),
            )
            .await
            .unwrap();
        let revoked_receipt = target
            .import_plain_drop(Cursor::new(revoked_bytes), DropLimits::default())
            .await
            .unwrap();
        assert_eq!(revoked_receipt.delegation_operations, 1);
        assert_eq!(
            target.delegation_scope_key_epochs().await.unwrap()[0].epoch,
            1
        );
        assert!(
            target
                .delegation_projections(60)
                .await
                .unwrap()
                .iter()
                .all(|projection| !projection.active)
        );
        assert_eq!(
            target
                .authorize_current_delegated(
                    &Access {
                        capability_covers: true,
                        facts: TesseraFacts {
                            score: 1,
                            ..Default::default()
                        },
                    },
                    &MootAuthorizationRequest {
                        subject: delegate.master_public_key().to_bytes(),
                        capability_path: "moot/fauna/notes/write".into(),
                        at_ms: 60,
                    },
                )
                .await
                .unwrap(),
            GateDecision::Deny(DenyReason::NoCapability)
        );
    }

    #[tokio::test]
    async fn aggregate_drop_reconstructs_all_five_retained_domains_for_late_peer() {
        let founder = keypair(12);
        let founder_id = founder.public_key().to_bytes();
        let member_identity = InMemoryProvider::from_seed([0x61; 32]);
        let member_root = member_identity.master_public_key().to_bytes();
        let root_holder = InMemoryProvider::from_seed([0x62; 32]);
        let delegate = InMemoryProvider::from_seed([0x63; 32]);
        let root_id = [0xd1; 32];
        let mut rules = ConstitutionRules::founder_only(founder_id);
        rules.grant(CapabilityGrant {
            id: root_id,
            subject: root_holder.master_public_key().to_bytes(),
            path_prefix: "moot/fauna".into(),
            not_before_ms: 1,
            expires_at_ms: Some(100),
            delegation_depth: 1,
        });

        let source = Moot::in_memory(ID, founder_id, retention());
        source
            .found(founder.to_seed(), None, None, rules.clone(), 1)
            .await
            .unwrap();
        let membership_receipt = source
            .update_membership_for_identity(
                &member_identity,
                MootMembershipAction::Create {
                    initial_members: vec![MootMember {
                        member: member_root,
                        access: MootAccessLevel::Manage,
                    }],
                },
            )
            .await
            .unwrap();
        assert!(matches!(
            source.outbound(&membership_receipt).await.unwrap(),
            MootOutboundOperation::Membership(_)
        ));

        let scope = CapabilityScope {
            domain: MOOT_DELEGATION_DOMAIN.into(),
            resource: ID.0.to_vec(),
            path_prefix: "moot/fauna/notes".into(),
            actions: [MOOT_ACT_ACTION.to_string()].into_iter().collect(),
        };
        let signed = SignedDelegationCertificate::issue(
            &root_holder,
            DelegationCertificate::new(
                DelegationParent::Root(root_id),
                root_holder.master_public_key().to_bytes(),
                delegate.master_public_key().to_bytes(),
                scope.clone(),
                2,
                3,
                Some(90),
                0,
                [0x64; 32],
            ),
        )
        .unwrap();
        let delegation_key = root_holder
            .derive_keypair(&delegation_signing_salt(&scope))
            .unwrap();
        source
            .delegation_store()
            .author_issue(&delegation_key, &rules, signed)
            .await
            .unwrap();

        source
            .declare(
                founder.to_seed(),
                "peer press".into(),
                "shared place".into(),
                4,
            )
            .await
            .unwrap();
        source
            .join(founder.to_seed(), "founder".into(), 5)
            .await
            .unwrap();
        source
            .share(
                founder.to_seed(),
                [0x65; 32],
                "text/plain".into(),
                "field note".into(),
                6,
            )
            .await
            .unwrap();
        source
            .record_tessera(
                founder.to_seed(),
                TesseraEvent::GovernanceParticipation {
                    by: ChainRoot(member_root),
                    at_ms: 7,
                },
            )
            .await
            .unwrap();
        let expected = source.snapshot().await.unwrap();

        let mut bytes = Vec::new();
        source
            .export_plain_drop(
                &mut bytes,
                DropExportProfile::default(),
                DropLimits::default(),
            )
            .await
            .unwrap();
        let late_peer = Moot::in_memory(ID, founder_id, retention());
        let receipt = late_peer
            .import_plain_drop(Cursor::new(bytes), DropLimits::default())
            .await
            .unwrap();

        assert_eq!(receipt.constitution_operations, 1);
        assert_eq!(receipt.delegation_operations, 1);
        assert_eq!(receipt.membership_operations, 1);
        assert_eq!(receipt.tessera_operations, 1);
        assert_eq!(receipt.snapshot, expected);
        assert_eq!(receipt.snapshot.membership.members[0].member, member_root);
        assert_eq!(receipt.snapshot.roster.members.len(), 1);
        assert_eq!(receipt.snapshot.roster.fauna.len(), 1);
        assert_eq!(receipt.snapshot.delegated_certificates, 1);
        assert_eq!(receipt.snapshot.tessera_operations, 1);
    }

    #[tokio::test]
    async fn durable_service_reopens_both_governance_and_roster() {
        let directory = tempfile::tempdir().unwrap();
        let founder = keypair(3);
        let founder_id = founder.public_key().to_bytes();
        let service = MootFile::open(directory.path(), ID, founder_id, retention())
            .await
            .unwrap();
        service
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        service
            .join(founder.to_seed(), "mark".into(), 2)
            .await
            .unwrap();
        drop(service);

        let reopened = MootFile::open(directory.path(), ID, founder_id, retention())
            .await
            .unwrap();
        assert_eq!(reopened.snapshot().await.unwrap().roster.members.len(), 1);
    }

    #[tokio::test]
    async fn native_drop_bootstraps_checkpoint_and_roster_then_is_idempotent() {
        let founder = keypair(4);
        let founder_id = founder.public_key().to_bytes();
        let source = Moot::in_memory(ID, founder_id, retention());
        let destination = Moot::in_memory(ID, founder_id, retention());
        for service in [&source, &destination] {
            service
                .found(
                    founder.to_seed(),
                    None,
                    None,
                    ConstitutionRules::founder_only(founder_id),
                    1,
                )
                .await
                .unwrap();
        }
        source
            .declare(
                founder.to_seed(),
                "drop circle".into(),
                "travels by file".into(),
                2,
            )
            .await
            .unwrap();
        source
            .join(founder.to_seed(), "mark".into(), 3)
            .await
            .unwrap();
        source.checkpoint(founder.to_seed(), 4).await.unwrap();

        let mut bytes = Vec::new();
        source
            .export_plain_drop(
                &mut bytes,
                DropExportProfile::default(),
                DropLimits::default(),
            )
            .await
            .unwrap();
        let first = destination
            .import_plain_drop(Cursor::new(bytes.clone()), DropLimits::default())
            .await
            .unwrap();
        assert_eq!(first.snapshot.roster.members.len(), 1);
        assert_eq!(
            first.snapshot.roster.declaration.unwrap().name,
            "drop circle"
        );
        assert!(first.snapshot.checkpoint.is_some());

        let repeated = destination
            .import_plain_drop(Cursor::new(bytes), DropLimits::default())
            .await
            .unwrap();
        assert!(repeated.import.receipt_hit);
    }

    #[tokio::test]
    async fn aggregate_drop_bootstraps_rotated_checkpoint_authority() {
        let founder = keypair(5);
        let successor = keypair(6);
        let founder_id = founder.public_key().to_bytes();
        let source = Moot::in_memory(ID, founder_id, retention());
        let destination = Moot::in_memory(ID, founder_id, retention());
        source
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        source
            .join(founder.to_seed(), "mark".into(), 2)
            .await
            .unwrap();
        source.checkpoint(founder.to_seed(), 3).await.unwrap();
        let mut rules = ConstitutionRules::founder_only(founder_id);
        rules.checkpoint_signers.clear();
        rules
            .checkpoint_signers
            .insert(successor.public_key().to_bytes());
        source.amend(founder.to_seed(), rules, 4).await.unwrap();
        let rotated = source.checkpoint(successor.to_seed(), 5).await.unwrap();

        let mut bytes = Vec::new();
        source
            .export_plain_drop(
                &mut bytes,
                DropExportProfile::default(),
                DropLimits::default(),
            )
            .await
            .unwrap();
        let imported = destination
            .import_plain_drop(Cursor::new(bytes), DropLimits::default())
            .await
            .unwrap();
        assert_eq!(imported.constitution_operations, 2);
        assert_eq!(
            imported.snapshot.checkpoint.unwrap().operation,
            rotated.operation
        );
        assert_eq!(imported.snapshot.roster.members.len(), 1);
    }

    #[tokio::test]
    async fn protected_drop_and_tessera_command_expose_publishable_operations() {
        let founder = keypair(7);
        let founder_id = founder.public_key().to_bytes();
        let source = Moot::in_memory(ID, founder_id, retention());
        let destination = Moot::in_memory(ID, founder_id, retention());
        source
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        destination
            .found(
                founder.to_seed(),
                None,
                None,
                ConstitutionRules::founder_only(founder_id),
                1,
            )
            .await
            .unwrap();
        source
            .declare(
                founder.to_seed(),
                "private circle".into(),
                "sealed".into(),
                2,
            )
            .await
            .unwrap();
        let mut bytes = Vec::new();
        source
            .export_protected_drop(
                &mut bytes,
                &MootDropSelector::default(),
                DropExportBudget::default(),
                DropLimits::default(),
                &TestProtector,
            )
            .await
            .unwrap();
        let imported = destination
            .import_protected_drop(Cursor::new(bytes), DropLimits::default(), &TestProtector)
            .await
            .unwrap();
        assert_eq!(
            imported.snapshot.roster.declaration.unwrap().name,
            "private circle"
        );

        let receipt = source
            .record_tessera(
                founder.to_seed(),
                TesseraEvent::GovernanceParticipation {
                    by: ChainRoot(founder_id),
                    at_ms: 3,
                },
            )
            .await
            .unwrap();
        assert_eq!(receipt.lane, MootLane::Tessera);
        assert!(matches!(
            source.outbound(&receipt).await.unwrap(),
            MootOutboundOperation::Tessera(_)
        ));
    }
}