semantic-memory 0.5.10

Local-first hybrid semantic search (SQLite + FTS5 + usearch 2.25) with bitemporal truth and typed receipts
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
//! Atomic, capability-gated authority mutations over the SQLite fact graph.
//!
//! This is deliberately a narrow write surface. Facts remain append-only; the
//! authority tables record lineage heads while graph edges preserve the
//! supersession or redaction event that caused a head transition.

use crate::authority_contracts::{
    AuthorityAdmission, AuthorityFaultStage, AuthorityOperationKind, AuthorityPermit,
    AuthorityReceiptV1, AuthoritySnapshotId, AuthorityStateV1, RetrievalEpoch,
};
use crate::db::with_transaction;
use crate::error::MemoryError;
use crate::origin_authority::{
    decide, label_digest, GovernedAccessRequestV1, GovernedFactAccessV1,
    GovernedFactListResponseV1, GovernedGraphResponseV1, GovernedReplayResponseV1,
    GovernedSearchResponseV1, GovernedStateResolutionResponseV1, OriginAuthorityLabelV1,
    OriginAuthorityRecordV1, OriginDerivationKindV1,
};
use crate::quantize::{self, Quantizer};
use crate::transition_contracts::{
    MemoryTransitionCandidateV1, MemoryTransitionOutcomeV1, MemoryTransitionRecordV1,
    MemoryTransitionVerificationV1, TransitionDisposition, TransitionOperation,
    MEMORY_TRANSITION_RECORD_V1,
};
use crate::transition_verifier::{digest as transition_digest, verify_candidate};
use crate::MemoryStore;
use chrono::Utc;
use rusqlite::{params, Connection, OptionalExtension, Transaction};
use serde::Serialize;
use std::sync::{Arc, Mutex};

const RECEIPT_SCHEMA: &str = "authority_receipt_v1";
const REDACTED_CONTENT: &str = "[REDACTED]";

#[derive(Clone)]
pub struct MemoryAuthority {
    store: MemoryStore,
}

impl MemoryAuthority {
    pub(crate) fn new(store: MemoryStore) -> Self {
        Self { store }
    }

    /// Append a new fact and start a new authority lineage.
    pub async fn append(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        namespace: String,
        content: String,
        source: Option<String>,
    ) -> Result<AuthorityReceiptV1, MemoryError> {
        self.append_with_metadata(
            permit,
            caller_idempotency_key,
            namespace,
            content,
            source,
            None,
        )
        .await
    }

    /// Append a new governed fact with caller metadata atomically bound to the
    /// fact row, authority lineage, journal entry, and idempotency payload.
    ///
    /// Caller metadata must be a JSON object. Reserved `authority` metadata is
    /// always generated by this authority boundary and cannot be caller-set.
    pub async fn append_with_metadata(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        namespace: String,
        content: String,
        source: Option<String>,
        metadata: Option<serde_json::Value>,
    ) -> Result<AuthorityReceiptV1, MemoryError> {
        self.mutate(
            permit,
            caller_idempotency_key,
            Mutation::Append {
                namespace,
                content,
                source,
                metadata,
            },
        )
        .await
    }

    /// Append a replacement fact and supersede the current lineage head.
    pub async fn supersede(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        target_fact_id: String,
        content: String,
        source: Option<String>,
    ) -> Result<AuthorityReceiptV1, MemoryError> {
        self.mutate(
            permit,
            caller_idempotency_key,
            Mutation::Supersede {
                target_fact_id,
                content,
                source,
            },
        )
        .await
    }

    /// Append a redaction tombstone and make it the current lineage head.
    pub async fn redact(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        target_fact_id: String,
        reason: String,
    ) -> Result<AuthorityReceiptV1, MemoryError> {
        self.mutate(
            permit,
            caller_idempotency_key,
            Mutation::Redact {
                target_fact_id,
                reason,
            },
        )
        .await
    }

    /// Forget a canonical fact and every accessible derived artifact in one transaction.
    pub async fn forget(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        request: crate::ForgettingClosureRequestV1,
    ) -> Result<crate::ForgettingClosureReceiptV1, MemoryError> {
        crate::forgetting::forget(&self.store, permit, caller_idempotency_key, request).await
    }

    /// Governed forgetting validates every root against the same policy evaluator before the
    /// closure planner can inspect or invalidate it. Administrative authority is an explicit,
    /// time-bounded elevation rather than an implicit consequence of a write permit.
    pub async fn forget_governed(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        request: crate::ForgettingClosureRequestV1,
        access: GovernedAccessRequestV1,
    ) -> Result<crate::ForgettingClosureReceiptV1, MemoryError> {
        let access = access.with_purpose(crate::GovernedAccessPurposeV1::Admin);
        for fact_id in &request.root_fact_ids {
            let governed = self.get_fact_governed(fact_id, access.clone()).await?;
            if !governed.decision.allowed {
                return Err(MemoryError::OriginAuthorityRejected {
                    principal: access.caller.0.clone(),
                    reason: format!(
                        "governed forgetting denied for '{}': {}",
                        fact_id,
                        governed.decision.reasons.join(",")
                    ),
                });
            }
        }
        self.forget(permit, caller_idempotency_key, request).await
    }

    /// Deterministically verify a source-grounded candidate immediately before authority commit.
    ///
    /// Failed verification is durably quarantined and never invokes canonical mutation. A passing
    /// verification, its immutable evidence, and the existing authority mutation commit in one
    /// SQLite transaction.
    pub async fn verify_and_commit(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        candidate: MemoryTransitionCandidateV1,
    ) -> Result<MemoryTransitionOutcomeV1, MemoryError> {
        let kind = candidate_operation_kind(&candidate);
        validate_authority_request(&permit, &caller_idempotency_key, kind)?;
        let prepared = match candidate_content_for_embedding(&candidate) {
            Some(content) => {
                let (embedding, sparse, sparse_representation) =
                    self.store.embed_text_with_sparse_internal(content).await?;
                self.store.validate_embedding_dimensions(&embedding)?;
                let embedding_bytes = crate::db::embedding_to_bytes(&embedding);
                let q8_bytes = Quantizer::new(self.store.inner.config.embedding.dimensions)
                    .quantize(&embedding)
                    .map(|qv| quantize::pack_quantized(&qv))
                    .ok();
                Some(FactEmbedding {
                    embedding: embedding_bytes,
                    q8: q8_bytes,
                    sparse,
                    sparse_representation,
                })
            }
            None => None,
        };
        let fault = self.store.inner.authority_fault.clone();
        let outcome = self
            .store
            .with_write_conn(move |conn| {
                execute_compiled_transition(
                    conn,
                    &permit,
                    &caller_idempotency_key,
                    candidate,
                    &fault,
                    prepared,
                )
            })
            .await?;
        if matches!(outcome, MemoryTransitionOutcomeV1::Committed { .. }) {
            self.store.clear_search_cache();
        }
        Ok(outcome)
    }

    /// Inspect a committed or quarantined transition by caller idempotency key.
    pub async fn get_transition_by_idempotency_key(
        &self,
        caller_idempotency_key: &str,
    ) -> Result<Option<MemoryTransitionRecordV1>, MemoryError> {
        let key = caller_idempotency_key.to_string();
        self.store
            .with_read_conn(move |conn| get_transition_record(conn, &key))
            .await
    }

    /// Load an immutable selective-forgetting receipt by caller idempotency key.
    pub async fn get_forgetting_receipt_by_idempotency_key(
        &self,
        caller_idempotency_key: &str,
    ) -> Result<Option<crate::ForgettingClosureReceiptV1>, MemoryError> {
        crate::forgetting::get_receipt(&self.store, caller_idempotency_key).await
    }

    /// Find a committed authority receipt by operation identity.
    pub async fn get_receipt_by_operation_id(
        &self,
        operation_id: &str,
    ) -> Result<Option<AuthorityReceiptV1>, MemoryError> {
        let operation_id = operation_id.to_string();
        self.store
            .with_read_conn(move |conn| get_receipt(conn, "operation_id", &operation_id))
            .await
    }

    /// Find a committed authority receipt by the caller's idempotency key.
    pub async fn get_receipt_by_idempotency_key(
        &self,
        caller_idempotency_key: &str,
    ) -> Result<Option<AuthorityReceiptV1>, MemoryError> {
        let key = caller_idempotency_key.to_string();
        self.store
            .with_read_conn(move |conn| get_receipt(conn, "caller_idempotency_key", &key))
            .await
    }

    /// Load the immutable write-time origin label for a canonical fact.
    pub async fn get_origin_authority(
        &self,
        fact_id: &str,
    ) -> Result<Option<OriginAuthorityRecordV1>, MemoryError> {
        let fact_id = fact_id.to_string();
        self.store
            .with_read_conn(move |conn| load_origin_record(conn, &fact_id))
            .await
    }

    /// Direct-ID governed recall. Content is never returned when the decision denies access.
    pub async fn get_fact_governed(
        &self,
        fact_id: &str,
        request: GovernedAccessRequestV1,
    ) -> Result<GovernedFactAccessV1, MemoryError> {
        let fact_id = fact_id.to_string();
        self.store
            .with_read_conn(move |conn| governed_fact_access(conn, &fact_id, &request))
            .await
    }

    /// Governed export uses the same decision path as direct recall.
    pub async fn export_fact_governed(
        &self,
        fact_id: &str,
        request: GovernedAccessRequestV1,
    ) -> Result<GovernedFactAccessV1, MemoryError> {
        self.get_fact_governed(
            fact_id,
            request.with_purpose(crate::GovernedAccessPurposeV1::Export),
        )
        .await
    }

    /// Governed hybrid search filters every result after cache retrieval, preventing cache bypass.
    pub async fn search_governed(
        &self,
        query: &str,
        top_k: Option<usize>,
        request: GovernedAccessRequestV1,
    ) -> Result<GovernedSearchResponseV1, MemoryError> {
        self.search_governed_with_view(query, top_k, request, crate::StateView::Current)
            .await
    }

    /// Read the current authority snapshot and retrieval epoch for cache validation.
    pub async fn current_state(&self) -> Result<AuthorityStateV1, MemoryError> {
        self.store
            .with_read_conn(|conn| {
                with_transaction(conn, |tx| {
                    let epoch = current_epoch(tx)?;
                    let snapshot_id = snapshot_id(tx, epoch)?;
                    Ok(AuthorityStateV1 {
                        snapshot_id,
                        retrieval_epoch: RetrievalEpoch(epoch),
                    })
                })
            })
            .await
    }

    /// Read-only compatibility shim for callers that only need the retrieval epoch.
    pub(crate) async fn current_retrieval_epoch(&self) -> Result<RetrievalEpoch, MemoryError> {
        Ok(self.current_state().await?.retrieval_epoch)
    }

    /// Governed current or historical search. The candidate source is intentionally irrelevant:
    /// every returned row is passed through the same canonical evaluator used by direct access.
    pub async fn search_governed_with_view(
        &self,
        query: &str,
        top_k: Option<usize>,
        request: GovernedAccessRequestV1,
        view: crate::StateView,
    ) -> Result<GovernedSearchResponseV1, MemoryError> {
        let namespace = request.scope.namespace.clone();
        let raw = self
            .store
            .search_with_view(query, top_k, Some(&[namespace.as_str()]), None, view)
            .await?;
        let mut results = Vec::new();
        let mut decisions = Vec::new();
        for result in raw {
            let fact_id = match &result.source {
                crate::SearchSource::Fact { fact_id, .. } => fact_id.clone(),
                crate::SearchSource::Chunk { chunk_id, .. } => format!("chunk:{chunk_id}"),
                crate::SearchSource::Message { message_id, .. } => format!("message:{message_id}"),
                crate::SearchSource::Episode { episode_id, .. } => format!("episode:{episode_id}"),
                crate::SearchSource::Projection { projection_id, .. } => {
                    format!("projection:{projection_id}")
                }
            };
            let decision = if matches!(result.source, crate::SearchSource::Fact { .. }) {
                self.get_fact_governed(&fact_id, request.clone())
                    .await?
                    .decision
            } else {
                decide(&fact_id, None, None, None, &request)
            };
            if decision.allowed {
                results.push(result);
            }
            decisions.push(decision);
        }
        Ok(GovernedSearchResponseV1 { results, decisions })
    }

    /// Governed enumeration applies the same direct-ID policy check to every listed fact.
    pub async fn list_facts_governed(
        &self,
        request: GovernedAccessRequestV1,
        limit: usize,
        offset: usize,
        view: crate::StateView,
    ) -> Result<GovernedFactListResponseV1, MemoryError> {
        let facts = self
            .store
            .list_facts_with_view(&request.scope.namespace, limit, offset, view)
            .await?;
        let mut admitted = Vec::new();
        let mut decisions = Vec::new();
        for fact in facts {
            let response = self.get_fact_governed(&fact.id, request.clone()).await?;
            if let Some(fact) = response.fact {
                admitted.push(fact);
            }
            decisions.push(response.decision);
        }
        Ok(GovernedFactListResponseV1 {
            facts: admitted,
            decisions,
        })
    }

    /// State resolution is candidate generation only; this wrapper removes denied assertions
    /// before an answer can leave the crate, including historical state views and cache-backed
    /// searches. The resolution receipt remains an audit record, not a content channel.
    pub async fn resolve_memory_governed(
        &self,
        query: &str,
        top_k: Option<usize>,
        request: GovernedAccessRequestV1,
        mode: crate::StateResolutionMode,
        budget: usize,
    ) -> Result<GovernedStateResolutionResponseV1, MemoryError> {
        let namespaces = [request.scope.namespace.as_str()];
        let mut response = self
            .store
            .resolve_memory(query, top_k, Some(&namespaces), mode, budget)
            .await?;
        let mut decisions = Vec::new();
        response.assertions.retain(|assertion| {
            let Some(fact_id) = assertion.memory_id.strip_prefix("fact:") else {
                return false;
            };
            // This async call cannot occur in `retain`; decisions are collected below.
            !fact_id.is_empty()
        });
        let mut admitted = Vec::new();
        for assertion in response.assertions.drain(..) {
            let fact_id = assertion
                .memory_id
                .strip_prefix("fact:")
                .unwrap_or_default();
            let decision = self
                .get_fact_governed(fact_id, request.clone())
                .await?
                .decision;
            if decision.allowed {
                admitted.push(assertion);
            }
            decisions.push(decision);
        }
        response.assertions = admitted;
        response.alternatives.retain(|alternative| {
            response
                .assertions
                .iter()
                .any(|assertion| assertion.memory_id == alternative.assertion.memory_id)
        });
        response.answer = response
            .assertions
            .first()
            .map(|assertion| assertion.content.clone());
        Ok(GovernedStateResolutionResponseV1 {
            response,
            decisions,
        })
    }

    /// Governed graph traversal authorizes every fact endpoint before returning an edge.
    pub async fn list_graph_edges_for_node_governed(
        &self,
        node_id: &str,
        request: GovernedAccessRequestV1,
    ) -> Result<GovernedGraphResponseV1, MemoryError> {
        let edges = self.store.list_graph_edges_for_node(node_id).await?;
        let mut admitted = Vec::new();
        let mut decisions = Vec::new();
        for edge in edges {
            let mut edge_allowed = true;
            for endpoint in [&edge.source, &edge.target] {
                if let Some(fact_id) = endpoint.strip_prefix("fact:") {
                    let decision = self
                        .get_fact_governed(fact_id, request.clone())
                        .await?
                        .decision;
                    edge_allowed &= decision.allowed;
                    decisions.push(decision);
                }
            }
            if edge_allowed {
                admitted.push(edge);
            }
        }
        Ok(GovernedGraphResponseV1 {
            edges: admitted,
            decisions,
        })
    }

    /// Replay a durable receipt, then authorize every replay result for the current caller.
    pub async fn replay_search_receipt_governed(
        &self,
        receipt_id: &str,
        query: &str,
        top_k: Option<usize>,
        request: GovernedAccessRequestV1,
    ) -> Result<GovernedReplayResponseV1, MemoryError> {
        let request = request.with_purpose(crate::GovernedAccessPurposeV1::Replay);
        let namespace = request.scope.namespace.clone();
        let replay = self
            .store
            .replay_search_receipt(receipt_id, query, top_k, Some(&[namespace.as_str()]), None)
            .await?;
        let mut allowed_result_ids = Vec::new();
        let mut decisions = Vec::new();
        for result_id in &replay.replay_receipt.result_ids {
            let decision = if let Some(fact_id) = result_id.strip_prefix("fact:") {
                self.get_fact_governed(fact_id, request.clone())
                    .await?
                    .decision
            } else {
                decide(result_id, None, None, None, &request)
            };
            if decision.allowed {
                allowed_result_ids.push(result_id.clone());
            }
            decisions.push(decision);
        }
        Ok(GovernedReplayResponseV1 {
            replay,
            allowed_result_ids,
            decisions,
        })
    }

    /// Append an origin revocation without mutating the immutable write-time label.
    pub async fn revoke_origin(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        fact_id: &str,
        revocation_reference: String,
    ) -> Result<crate::OriginAuthorityDecisionV1, MemoryError> {
        if permit.capability != AuthorityPermit::REVOKE_ORIGIN_CAPABILITY
            || permit.principal.trim().is_empty()
            || caller_idempotency_key.trim().is_empty()
            || revocation_reference.trim().is_empty()
            || permit.origin_authority.is_none()
        {
            return Err(MemoryError::OriginAuthorityRejected {
                principal: permit.principal,
                reason: "revocation requires an origin-bound revoke capability and reference"
                    .into(),
            });
        }
        let fact_id = fact_id.to_string();
        let principal = permit.principal.clone();
        let request = GovernedAccessRequestV1::new(
            &principal,
            &principal,
            crate::GovernedAccessPurposeV1::Recall,
            "general",
        );
        self.store
            .with_write_conn(move |conn| {
                with_transaction(conn, |tx| {
                    let existing: Option<(String, String)> = tx
                        .query_row(
                            "SELECT fact_id, revocation_reference FROM origin_authority_revocations
                             WHERE caller_idempotency_key = ?1",
                            params![caller_idempotency_key],
                            |row| Ok((row.get(0)?, row.get(1)?)),
                        )
                        .optional()?;
                    if let Some((existing_fact, existing_reference)) = existing {
                        if existing_fact != fact_id || existing_reference != revocation_reference {
                            return Err(MemoryError::AuthorityIdempotencyConflict {
                                key: caller_idempotency_key,
                            });
                        }
                    } else {
                        let exists: bool = tx.query_row(
                            "SELECT EXISTS(SELECT 1 FROM origin_authority_labels WHERE fact_id = ?1)",
                            params![fact_id],
                            |row| row.get(0),
                        )?;
                        if !exists {
                            return Err(MemoryError::OriginAuthorityRejected {
                                principal: principal.clone(),
                                reason: "cannot revoke a fact without a canonical origin label".into(),
                            });
                        }
                        tx.execute(
                            "INSERT INTO origin_authority_revocations
                             (revocation_id, fact_id, caller_idempotency_key, principal,
                              revocation_reference, revoked_at)
                             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                            params![
                                uuid::Uuid::new_v4().to_string(),
                                fact_id,
                                caller_idempotency_key,
                                principal,
                                revocation_reference,
                                Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string(),
                            ],
                        )?;
                    }
                    let fact = crate::knowledge::get_fact(tx, &fact_id)?;
                    let origin = load_origin_record(tx, &fact_id)?;
                    Ok(decide(
                        &fact_id,
                        fact.as_ref().map(|fact| fact.namespace.as_str()),
                        origin.as_ref(),
                        Some(&revocation_reference),
                        &request,
                    ))
                })
            })
            .await
    }

    /// Install a one-shot fault for the next matching authority stage.
    #[cfg(any(test, feature = "testing"))]
    pub fn set_fault(&self, stage: Option<AuthorityFaultStage>) {
        let mut guard = self
            .store
            .inner
            .authority_fault
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *guard = stage;
    }

    async fn mutate(
        &self,
        permit: AuthorityPermit,
        caller_idempotency_key: String,
        mutation: Mutation,
    ) -> Result<AuthorityReceiptV1, MemoryError> {
        validate_authority_request(&permit, &caller_idempotency_key, mutation.kind())?;

        let prepared = match mutation.content_for_embedding() {
            Some(content) => {
                let (embedding, sparse, sparse_representation) =
                    self.store.embed_text_with_sparse_internal(content).await?;
                self.store.validate_embedding_dimensions(&embedding)?;
                let embedding_bytes = crate::db::embedding_to_bytes(&embedding);
                let q8_bytes = Quantizer::new(self.store.inner.config.embedding.dimensions)
                    .quantize(&embedding)
                    .map(|qv| quantize::pack_quantized(&qv))
                    .ok();

                Some(FactEmbedding {
                    embedding: embedding_bytes,
                    q8: q8_bytes,
                    sparse,
                    sparse_representation,
                })
            }
            None => None,
        };

        let fault = self.store.inner.authority_fault.clone();
        let result = self
            .store
            .with_write_conn(move |conn| {
                execute_mutation(
                    conn,
                    &permit,
                    &caller_idempotency_key,
                    mutation,
                    &fault,
                    prepared,
                )
            })
            .await?;
        self.store.clear_search_cache();
        Ok(result)
    }
}

fn validate_authority_request(
    permit: &AuthorityPermit,
    caller_idempotency_key: &str,
    kind: AuthorityOperationKind,
) -> Result<(), MemoryError> {
    if permit.principal.trim().is_empty()
        || permit.caller_id.trim().is_empty()
        || permit.capability != kind.capability()
        || caller_idempotency_key.trim().is_empty()
    {
        return Err(MemoryError::AuthorityUnauthorized {
            operation: kind.as_str().to_string(),
            principal: permit.principal.clone(),
        });
    }
    let append_admitted = match &permit.admission {
        AuthorityAdmission::OperatorSystem => true,
        AuthorityAdmission::Evidence { evidence_refs } => !evidence_refs.is_empty(),
        AuthorityAdmission::Unspecified => false,
    };
    if kind == AuthorityOperationKind::Append && !append_admitted {
        return Err(MemoryError::AuthorityAdmissionRejected {
            principal: permit.principal.clone(),
            reason: "authoritative append requires evidence or an operator/system permit".into(),
        });
    }
    let origin =
        permit
            .origin_authority
            .as_ref()
            .ok_or_else(|| MemoryError::OriginAuthorityRejected {
                principal: permit.principal.clone(),
                reason: "governed canonical writes require an immutable origin label".into(),
            })?;
    if origin.origin_principal != permit.principal
        || origin.schema_version != crate::origin_authority::ORIGIN_AUTHORITY_LABEL_V1
        || origin.revocation_status != crate::RevocationStatusV1::Active
        || label_digest(origin).is_err()
    {
        return Err(MemoryError::OriginAuthorityRejected {
            principal: permit.principal.clone(),
            reason: "origin label is inconsistent, inactive, or bound to another principal".into(),
        });
    }
    Ok(())
}

#[derive(Debug)]
enum Mutation {
    Append {
        namespace: String,
        content: String,
        source: Option<String>,
        metadata: Option<serde_json::Value>,
    },
    Supersede {
        target_fact_id: String,
        content: String,
        source: Option<String>,
    },
    Redact {
        target_fact_id: String,
        reason: String,
    },
}

impl Mutation {
    fn content_for_embedding(&self) -> Option<&str> {
        match self {
            Self::Append { content, .. } => Some(content),
            Self::Supersede { content, .. } => Some(content),
            Self::Redact { .. } => None,
        }
    }

    fn kind(&self) -> AuthorityOperationKind {
        match self {
            Self::Append { .. } => AuthorityOperationKind::Append,
            Self::Supersede { .. } => AuthorityOperationKind::Supersede,
            Self::Redact { .. } => AuthorityOperationKind::Redact,
        }
    }
}

impl AuthorityOperationKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Append => "append",
            Self::Supersede => "supersede",
            Self::Redact => "redact",
        }
    }

    fn capability(self) -> &'static str {
        match self {
            Self::Append => AuthorityPermit::APPEND_CAPABILITY,
            Self::Supersede => AuthorityPermit::SUPERSEDE_CAPABILITY,
            Self::Redact => AuthorityPermit::REDACT_CAPABILITY,
        }
    }
}

#[derive(Debug)]
struct LineageTarget {
    fact_id: String,
    lineage_id: String,
    namespace: String,
    version: i64,
}

#[derive(Serialize)]
struct Payload<'a> {
    operation_kind: AuthorityOperationKind,
    mutation: &'a MutationForDigest,
    origin_label_digest: &'a str,
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum MutationForDigest {
    Append {
        namespace: String,
        content: String,
        source: Option<String>,
        metadata: Option<serde_json::Value>,
    },
    Supersede {
        target_fact_id: String,
        content: String,
        source: Option<String>,
    },
    Redact {
        target_fact_id: String,
        reason: String,
    },
}

fn candidate_operation_kind(candidate: &MemoryTransitionCandidateV1) -> AuthorityOperationKind {
    match candidate.operation {
        TransitionOperation::Append { .. } => AuthorityOperationKind::Append,
        TransitionOperation::Supersede { .. } => AuthorityOperationKind::Supersede,
        TransitionOperation::Retract { .. } => AuthorityOperationKind::Redact,
    }
}

fn candidate_content_for_embedding(candidate: &MemoryTransitionCandidateV1) -> Option<&str> {
    let assertion_id = match &candidate.operation {
        TransitionOperation::Append { assertion_id } => assertion_id,
        TransitionOperation::Supersede { draft } => &draft.replacement_assertion_id,
        TransitionOperation::Retract { .. } => return None,
    };
    candidate
        .assertions
        .iter()
        .find(|assertion| &assertion.assertion_id == assertion_id)
        .map(|assertion| assertion.content.as_str())
}

fn mutation_from_candidate(
    candidate: &MemoryTransitionCandidateV1,
    candidate_digest: &str,
) -> Result<Mutation, MemoryError> {
    let source = |spans: &[crate::SourceSpanRefV1]| {
        serde_json::to_string(&serde_json::json!({
            "memory_transition_candidate_id": candidate.candidate_id,
            "candidate_digest": candidate_digest,
            "source_spans": spans,
        }))
        .map(Some)
        .map_err(|error| MemoryError::Other(format!("serialize transition source: {error}")))
    };
    match &candidate.operation {
        TransitionOperation::Append { assertion_id } => {
            let assertion = candidate
                .assertions
                .iter()
                .find(|assertion| &assertion.assertion_id == assertion_id)
                .ok_or_else(|| MemoryError::InvalidConfig {
                    field: "transition.operation.assertion_id",
                    reason: "referenced assertion draft is missing".into(),
                })?;
            Ok(Mutation::Append {
                namespace: assertion.namespace.clone(),
                content: assertion.content.clone(),
                source: source(&assertion.source_spans)?,
                metadata: None,
            })
        }
        TransitionOperation::Supersede { draft } => {
            let assertion = candidate
                .assertions
                .iter()
                .find(|assertion| assertion.assertion_id == draft.replacement_assertion_id)
                .ok_or_else(|| MemoryError::InvalidConfig {
                    field: "transition.operation.replacement_assertion_id",
                    reason: "referenced replacement assertion draft is missing".into(),
                })?;
            Ok(Mutation::Supersede {
                target_fact_id: draft.target_fact_id.clone(),
                content: assertion.content.clone(),
                source: source(&assertion.source_spans)?,
            })
        }
        TransitionOperation::Retract {
            target_fact_id,
            reason,
            ..
        } => Ok(Mutation::Redact {
            target_fact_id: target_fact_id.clone(),
            reason: reason.clone(),
        }),
    }
}

fn execute_compiled_transition(
    conn: &Connection,
    permit: &AuthorityPermit,
    key: &str,
    candidate: MemoryTransitionCandidateV1,
    fault: &Arc<Mutex<Option<AuthorityFaultStage>>>,
    prepared: Option<FactEmbedding>,
) -> Result<MemoryTransitionOutcomeV1, MemoryError> {
    let candidate_digest = transition_digest(&candidate)?;
    // Safety: verification, quarantine/evidence persistence, and the existing canonical authority
    // mutation share this transaction, so no verified partial transition can become observable.
    with_transaction(conn, |tx| {
        if let Some(record) = get_transition_record(tx, key)? {
            if record.candidate_digest != candidate_digest
                || record.principal != permit.principal
                || record.caller_id != permit.caller_id
            {
                return Err(MemoryError::AuthorityIdempotencyConflict {
                    key: key.to_string(),
                });
            }
            return outcome_from_record(tx, record);
        }

        let verification = verify_candidate(tx, &candidate)?;
        if verification.candidate_digest != candidate_digest {
            return Err(MemoryError::DigestError(
                "transition verifier candidate digest drift".into(),
            ));
        }
        if verification.disposition == TransitionDisposition::Quarantine {
            let record = build_transition_record(key, permit, candidate, verification, None);
            insert_transition_record(tx, &record)?;
            return Ok(MemoryTransitionOutcomeV1::Quarantined { record });
        }

        let mutation = mutation_from_candidate(&candidate, &candidate_digest)?;
        let authority_receipt = execute_mutation_tx(tx, permit, key, mutation, fault, prepared)?;
        let record = build_transition_record(
            key,
            permit,
            candidate,
            verification.clone(),
            Some(authority_receipt.receipt_id.clone()),
        );
        insert_transition_record(tx, &record)?;
        Ok(MemoryTransitionOutcomeV1::Committed {
            record,
            verification,
            authority_receipt,
        })
    })
}

fn build_transition_record(
    key: &str,
    permit: &AuthorityPermit,
    candidate: MemoryTransitionCandidateV1,
    verification: MemoryTransitionVerificationV1,
    authority_receipt_id: Option<String>,
) -> MemoryTransitionRecordV1 {
    MemoryTransitionRecordV1 {
        schema_version: MEMORY_TRANSITION_RECORD_V1.into(),
        record_id: uuid::Uuid::new_v4().to_string(),
        caller_idempotency_key: key.to_string(),
        principal: permit.principal.clone(),
        caller_id: permit.caller_id.clone(),
        candidate_digest: verification.candidate_digest.clone(),
        disposition: verification.disposition,
        candidate,
        verification,
        authority_receipt_id,
        created_at: Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string(),
    }
}

fn insert_transition_record(
    tx: &Transaction<'_>,
    record: &MemoryTransitionRecordV1,
) -> Result<(), MemoryError> {
    let candidate_json = serde_json::to_string(&record.candidate)
        .map_err(|error| MemoryError::Other(format!("serialize transition candidate: {error}")))?;
    let verification_json = serde_json::to_string(&record.verification).map_err(|error| {
        MemoryError::Other(format!("serialize transition verification: {error}"))
    })?;
    tx.execute(
        "INSERT INTO memory_transition_records
         (record_id, caller_idempotency_key, principal, caller_id, candidate_digest,
          candidate_json, verification_json, disposition, authority_receipt_id, created_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
        params![
            record.record_id,
            record.caller_idempotency_key,
            record.principal,
            record.caller_id,
            record.candidate_digest,
            candidate_json,
            verification_json,
            match record.disposition {
                TransitionDisposition::Commit => "commit",
                TransitionDisposition::Quarantine => "quarantine",
            },
            record.authority_receipt_id,
            record.created_at,
        ],
    )?;
    Ok(())
}

fn outcome_from_record(
    conn: &Connection,
    record: MemoryTransitionRecordV1,
) -> Result<MemoryTransitionOutcomeV1, MemoryError> {
    match record.disposition {
        TransitionDisposition::Quarantine => Ok(MemoryTransitionOutcomeV1::Quarantined { record }),
        TransitionDisposition::Commit => {
            let receipt_id =
                record
                    .authority_receipt_id
                    .as_deref()
                    .ok_or_else(|| MemoryError::CorruptData {
                        table: "memory_transition_records",
                        row_id: record.record_id.clone(),
                        detail: "committed transition is missing authority receipt ID".into(),
                    })?;
            let receipt_json: String = conn.query_row(
                "SELECT receipt_json FROM authority_receipts WHERE receipt_id = ?1",
                params![receipt_id],
                |row| row.get(0),
            )?;
            let authority_receipt =
                serde_json::from_str(&receipt_json).map_err(|error| MemoryError::CorruptData {
                    table: "authority_receipts",
                    row_id: receipt_id.to_string(),
                    detail: format!("invalid stored receipt: {error}"),
                })?;
            Ok(MemoryTransitionOutcomeV1::Committed {
                verification: record.verification.clone(),
                record,
                authority_receipt,
            })
        }
    }
}

fn execute_mutation(
    conn: &Connection,
    permit: &AuthorityPermit,
    key: &str,
    mutation: Mutation,
    fault: &Arc<Mutex<Option<AuthorityFaultStage>>>,
    prepared: Option<FactEmbedding>,
) -> Result<AuthorityReceiptV1, MemoryError> {
    // Safety: this closure owns every canonical authority write and only commits after the
    // mutation journal, epoch, lineage, and receipt are complete.
    with_transaction(conn, |tx| {
        execute_mutation_tx(tx, permit, key, mutation, fault, prepared)
    })
}

fn execute_mutation_tx(
    tx: &Transaction<'_>,
    permit: &AuthorityPermit,
    key: &str,
    mutation: Mutation,
    fault: &Arc<Mutex<Option<AuthorityFaultStage>>>,
    mut prepared: Option<FactEmbedding>,
) -> Result<AuthorityReceiptV1, MemoryError> {
    let kind = mutation.kind();
    let origin_label = effective_origin_label(tx, permit, &mutation)?;
    let origin_label_digest = label_digest(&origin_label).map_err(MemoryError::DigestError)?;
    let payload_digest = payload_digest(&mutation, &origin_label_digest)?;
    let operation = kind.as_str().to_string();

    if let Some(existing) = existing_operation(tx, key)? {
        if existing.payload_digest != payload_digest
            || existing.principal != permit.principal
            || existing.caller_id != permit.caller_id
            || existing.operation_kind != operation
        {
            return Err(MemoryError::AuthorityIdempotencyConflict {
                key: key.to_string(),
            });
        }
        let receipt: AuthorityReceiptV1 =
            serde_json::from_str(&existing.receipt_json).map_err(|e| MemoryError::CorruptData {
                table: "authority_receipts",
                row_id: key.to_string(),
                detail: format!("invalid stored receipt: {e}"),
            })?;
        return Ok(receipt);
    }

    verify_all_lineages(tx)?;
    let before_epoch = current_epoch(tx)?;
    let before_snapshot_id = snapshot_id(tx, before_epoch)?;
    let operation_id = uuid::Uuid::new_v4().to_string();
    let content_digest = mutation_content_digest(&mutation)?;

    fault_gate(fault, AuthorityFaultStage::BeforeAppend)?;
    let requires_embedding = matches!(
        mutation.kind(),
        AuthorityOperationKind::Append | AuthorityOperationKind::Supersede
    );
    let prepared = if requires_embedding {
        Some(prepared.take().ok_or_else(|| {
            MemoryError::Other("governed write is missing precomputed embedding".to_string())
        })?)
    } else {
        None
    };
    let (fact_id, lineage_id, target) =
        append_fact(tx, &mutation, &operation_id, &content_digest, prepared)?;
    persist_origin_label(tx, &fact_id, &origin_label, &origin_label_digest)?;
    fault_gate(fault, AuthorityFaultStage::AfterAppend)?;

    fault_gate(fault, AuthorityFaultStage::BeforeLineage)?;
    apply_lineage_transition(
        tx,
        &mutation,
        &operation_id,
        &fact_id,
        &lineage_id,
        target.as_ref(),
        &content_digest,
        before_epoch,
    )?;
    fault_gate(fault, AuthorityFaultStage::AfterLineage)?;
    verify_all_lineages(tx)?;

    let after_epoch = before_epoch
        .checked_add(1)
        .ok_or_else(|| MemoryError::Other("authority retrieval epoch overflow".to_string()))?;
    let affected_ids = affected_ids(&fact_id, &lineage_id, target.as_ref());
    let affected_json = serde_json::to_string(&affected_ids)
        .map_err(|e| MemoryError::Other(format!("serialize affected IDs: {e}")))?;
    let committed_at = Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string();

    fault_gate(fault, AuthorityFaultStage::BeforeJournal)?;
    tx.execute(
        "INSERT INTO operation_journal
             (operation_id, caller_idempotency_key, operation_kind, payload_digest,
              principal, caller_id, before_epoch, after_epoch, affected_ids_json,
              content_digest, committed_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
        params![
            operation_id,
            key,
            operation,
            payload_digest,
            permit.principal,
            permit.caller_id,
            before_epoch as i64,
            after_epoch as i64,
            affected_json,
            content_digest,
            committed_at,
        ],
    )?;
    fault_gate(fault, AuthorityFaultStage::AfterJournal)?;

    fault_gate(fault, AuthorityFaultStage::BeforeEpoch)?;
    let changed = tx.execute(
        "UPDATE authority_state SET retrieval_epoch = ?1 WHERE id = 1 AND retrieval_epoch = ?2",
        params![after_epoch as i64, before_epoch as i64],
    )?;
    if changed != 1 {
        return Err(MemoryError::Other(
            "authority retrieval epoch changed concurrently".to_string(),
        ));
    }
    tx.execute(
        "UPDATE authority_lineages SET updated_epoch = ?1 WHERE lineage_id = ?2",
        params![after_epoch as i64, lineage_id],
    )?;
    fault_gate(fault, AuthorityFaultStage::AfterEpoch)?;

    let after_snapshot_id = snapshot_id(tx, after_epoch)?;
    let receipt_id = uuid::Uuid::new_v4().to_string();
    let mut receipt = AuthorityReceiptV1 {
        schema_version: RECEIPT_SCHEMA.to_string(),
        receipt_id,
        operation_id,
        caller_idempotency_key: key.to_string(),
        principal: permit.principal.clone(),
        caller_id: permit.caller_id.clone(),
        operation_kind: kind,
        before_snapshot_id,
        after_snapshot_id,
        before_epoch: RetrievalEpoch(before_epoch),
        after_epoch: RetrievalEpoch(after_epoch),
        affected_ids,
        content_digest,
        origin_label_digest: Some(origin_label_digest),
        receipt_digest: String::new(),
        committed_at,
    };
    receipt.receipt_digest = digest_serialized(&receipt_without_digest(&receipt)?)?;
    let receipt_json = serde_json::to_string(&receipt)
        .map_err(|e| MemoryError::Other(format!("serialize authority receipt: {e}")))?;

    fault_gate(fault, AuthorityFaultStage::BeforeReceipt)?;
    tx.execute(
            "INSERT INTO authority_receipts
             (receipt_id, operation_id, caller_idempotency_key, receipt_json, receipt_digest, created_at)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                receipt.receipt_id,
                receipt.operation_id,
                receipt.caller_idempotency_key,
                receipt_json,
                receipt.receipt_digest,
                receipt.committed_at,
            ],
        )?;
    fault_gate(fault, AuthorityFaultStage::AfterReceipt)?;
    Ok(receipt)
}

fn append_fact(
    tx: &Transaction<'_>,
    mutation: &Mutation,
    operation_id: &str,
    content_digest: &str,
    prepared: Option<FactEmbedding>,
) -> Result<(String, String, Option<LineageTarget>), MemoryError> {
    let (namespace, content, source, caller_metadata, target) = match mutation {
        Mutation::Append {
            namespace,
            content,
            source,
            metadata,
        } => (
            namespace.clone(),
            content.clone(),
            source.clone(),
            metadata.clone(),
            None,
        ),
        Mutation::Supersede {
            target_fact_id,
            content,
            source,
        } => {
            let target = load_active_target(tx, target_fact_id)?;
            (
                target.namespace.clone(),
                content.clone(),
                source.clone(),
                None,
                Some(target),
            )
        }
        Mutation::Redact {
            target_fact_id,
            reason: _,
        } => {
            let target = load_active_target(tx, target_fact_id)?;
            (
                target.namespace.clone(),
                REDACTED_CONTENT.to_string(),
                None,
                None,
                Some(target),
            )
        }
    };
    let source = source.as_deref();
    if namespace.trim().is_empty() || content.is_empty() {
        return Err(MemoryError::InvalidConfig {
            field: "authority.fact",
            reason: "namespace and content must not be empty".to_string(),
        });
    }

    let fact_id = uuid::Uuid::new_v4().to_string();
    let lineage_id = target
        .as_ref()
        .map(|value| value.lineage_id.clone())
        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

    match mutation.kind() {
        AuthorityOperationKind::Append | AuthorityOperationKind::Supersede => {
            let prepared = prepared.ok_or_else(|| {
                MemoryError::Other("governed write is missing precomputed embedding".to_string())
            })?;
            if prepared.embedding.is_empty() {
                return Err(MemoryError::Other(
                    "governed write produced empty embedding bytes".to_string(),
                ));
            }
            let mut metadata = match caller_metadata {
                Some(serde_json::Value::Object(map)) => map,
                Some(_) => {
                    return Err(MemoryError::InvalidConfig {
                        field: "authority.fact.metadata",
                        reason: "caller metadata must be a JSON object".to_string(),
                    })
                }
                None => serde_json::Map::new(),
            };
            // Authority-owned fields are generated inside this transaction and
            // overwrite any caller attempt to spoof the reserved key.
            metadata.insert(
                "authority".to_string(),
                serde_json::json!({
                    "operation_id": operation_id,
                    "lineage_id": lineage_id,
                    "content_digest": content_digest,
                }),
            );
            let metadata = serde_json::Value::Object(metadata);
            crate::knowledge::insert_fact_in_tx(
                tx,
                &fact_id,
                &namespace,
                &content,
                &prepared.embedding,
                prepared.q8.as_deref(),
                source,
                Some(&metadata),
            )?;
            if let Some((weights, representation)) = prepared
                .sparse
                .as_ref()
                .zip(prepared.sparse_representation.as_deref())
            {
                crate::db::store_sparse_vector(
                    tx,
                    &format!("fact:{fact_id}"),
                    weights,
                    representation,
                )?;
            }
        }
        AuthorityOperationKind::Redact => {
            let metadata = serde_json::json!({
                "authority": {
                    "operation_id": operation_id,
                    "lineage_id": lineage_id,
                    "content_digest": content_digest,
                }
            })
            .to_string();
            tx.execute(
                "INSERT INTO facts (id, namespace, content, source, embedding, metadata)
                 VALUES (?1, ?2, ?3, ?4, NULL, ?5)",
                params![fact_id, namespace, content, source, metadata],
            )?;
            tx.execute(
                "INSERT INTO facts_rowid_map (fact_id) VALUES (?1)",
                params![fact_id],
            )?;
            let fts_rowid = tx.last_insert_rowid();
            tx.execute(
                "INSERT INTO facts_fts(rowid, content) VALUES (?1, ?2)",
                params![fts_rowid, content],
            )?;
        }
    }
    Ok((fact_id, lineage_id, target))
}

#[derive(Debug)]
struct FactEmbedding {
    embedding: Vec<u8>,
    q8: Option<Vec<u8>>,
    sparse: Option<crate::SparseWeights>,
    sparse_representation: Option<String>,
}

fn apply_lineage_transition(
    tx: &Transaction<'_>,
    mutation: &Mutation,
    operation_id: &str,
    fact_id: &str,
    lineage_id: &str,
    target: Option<&LineageTarget>,
    content_digest: &str,
    before_epoch: u64,
) -> Result<(), MemoryError> {
    let kind = mutation.kind().as_str();
    if let Some(target) = target {
        let relation = if matches!(mutation, Mutation::Redact { .. }) {
            "redacts"
        } else {
            "supersedes"
        };
        let recorded_at = Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string();
        let edge_type = serde_json::json!({"type": "entity", "relation": relation}).to_string();
        let edge_metadata = serde_json::json!({
            "operation_id": operation_id,
            "lineage_id": lineage_id,
        })
        .to_string();
        let edge_digest = digest_serialized(&(
            format!("fact:{fact_id}"),
            format!("fact:{}", target_fact_id(target)),
            edge_type.clone(),
            edge_metadata.clone(),
        ))?;
        tx.execute(
            "INSERT INTO graph_edges
             (id, source, target, edge_type, weight, metadata, content_digest,
              recorded_at, valid_time, recorded_time)
             VALUES (?1, ?2, ?3, ?4, 1.0, ?5, ?6, ?7, ?7, ?7)",
            params![
                uuid::Uuid::new_v4().to_string(),
                format!("fact:{fact_id}"),
                format!("fact:{}", target_fact_id(target)),
                edge_type,
                edge_metadata,
                edge_digest,
                recorded_at,
            ],
        )?;
        tx.execute(
            "UPDATE authority_versions SET is_active = 0 WHERE fact_id = ?1 AND is_active = 1",
            params![target_fact_id(target)],
        )?;
        crate::db::delete_sparse_vector(tx, &format!("fact:{}", target_fact_id(target)))?;
        tx.execute(
            "INSERT INTO authority_versions
             (fact_id, lineage_id, version, operation_kind, is_active, is_redacted, content_digest)
             VALUES (?1, ?2, ?3, ?4, 1, ?5, ?6)",
            params![
                fact_id,
                lineage_id,
                target.version + 1,
                kind,
                if matches!(mutation, Mutation::Redact { .. }) {
                    1
                } else {
                    0
                },
                content_digest,
            ],
        )?;
        tx.execute(
            "UPDATE authority_lineages SET active_head_id = ?1 WHERE lineage_id = ?2",
            params![fact_id, lineage_id],
        )?;
    } else {
        tx.execute(
            "INSERT INTO authority_lineages (lineage_id, active_head_id, updated_epoch)
             VALUES (?1, ?2, ?3)",
            params![lineage_id, fact_id, before_epoch as i64],
        )?;
        tx.execute(
            "INSERT INTO authority_versions
             (fact_id, lineage_id, version, operation_kind, is_active, is_redacted, content_digest)
             VALUES (?1, ?2, 1, ?3, 1, 0, ?4)",
            params![fact_id, lineage_id, kind, content_digest],
        )?;
    }
    verify_lineage(tx, lineage_id)
}

fn target_fact_id(target: &LineageTarget) -> &str {
    &target.fact_id
}

fn load_active_target(tx: &Transaction<'_>, fact_id: &str) -> Result<LineageTarget, MemoryError> {
    let target: Option<(String, String, i64, i64, String)> = tx
        .query_row(
            "SELECT av.lineage_id, f.namespace, av.version, av.is_active, al.active_head_id
             FROM authority_versions av
             JOIN facts f ON f.id = av.fact_id
             JOIN authority_lineages al ON al.lineage_id = av.lineage_id
             WHERE av.fact_id = ?1",
            params![fact_id],
            |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                ))
            },
        )
        .optional()?;
    let Some((lineage_id, namespace, version, is_active, active_head_id)) = target else {
        return Err(MemoryError::FactNotFound(fact_id.to_string()));
    };
    if is_active != 1 || active_head_id != fact_id {
        return Err(MemoryError::AuthorityLineageInconsistent {
            lineage_id,
            detail: "target is not the active head".to_string(),
        });
    }
    verify_lineage(tx, &lineage_id)?;
    Ok(LineageTarget {
        fact_id: fact_id.to_string(),
        lineage_id,
        namespace,
        version,
    })
}

fn verify_lineage(tx: &Transaction<'_>, lineage_id: &str) -> Result<(), MemoryError> {
    let (active_count, active_head, stored_head): (i64, Option<String>, Option<String>) = tx
        .query_row(
            "SELECT
                 (SELECT COUNT(*) FROM authority_versions WHERE lineage_id = ?1 AND is_active = 1),
                 (SELECT fact_id FROM authority_versions WHERE lineage_id = ?1 AND is_active = 1),
                 (SELECT active_head_id FROM authority_lineages WHERE lineage_id = ?1)",
            params![lineage_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )?;
    if active_count != 1 || active_head.is_none() || active_head != stored_head {
        return Err(MemoryError::AuthorityLineageInconsistent {
            lineage_id: lineage_id.to_string(),
            detail: format!(
                "expected one active version matching stored head; count={active_count}, active={active_head:?}, stored={stored_head:?}"
            ),
        });
    }
    Ok(())
}

fn verify_all_lineages(tx: &Transaction<'_>) -> Result<(), MemoryError> {
    let mut stmt = tx.prepare("SELECT lineage_id FROM authority_lineages ORDER BY lineage_id")?;
    let lineage_ids: Vec<String> = stmt
        .query_map([], |row| row.get(0))?
        .collect::<Result<Vec<_>, _>>()?;
    for lineage_id in lineage_ids {
        verify_lineage(tx, &lineage_id)?;
    }
    Ok(())
}

fn current_epoch(tx: &Transaction<'_>) -> Result<u64, MemoryError> {
    let value: i64 = tx.query_row(
        "SELECT retrieval_epoch FROM authority_state WHERE id = 1",
        [],
        |row| row.get(0),
    )?;
    u64::try_from(value).map_err(|_| MemoryError::Other("negative authority epoch".to_string()))
}

fn snapshot_id(tx: &Transaction<'_>, epoch: u64) -> Result<AuthoritySnapshotId, MemoryError> {
    let mut stmt = tx
        .prepare("SELECT lineage_id, active_head_id FROM authority_lineages ORDER BY lineage_id")?;
    let heads: Vec<(String, String)> = stmt
        .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
        .collect::<Result<Vec<_>, _>>()?;
    let digest = digest_serialized(&(epoch, heads))?;
    Ok(AuthoritySnapshotId(format!("epoch:{epoch}:{digest}")))
}

fn affected_ids(fact_id: &str, lineage_id: &str, target: Option<&LineageTarget>) -> Vec<String> {
    let mut ids = vec![fact_id.to_string(), lineage_id.to_string()];
    if let Some(target) = target {
        ids.push(target_fact_id(target).to_string());
    }
    ids
}

fn payload_digest(mutation: &Mutation, origin_label_digest: &str) -> Result<String, MemoryError> {
    let digest_mutation = match mutation {
        Mutation::Append {
            namespace,
            content,
            source,
            metadata,
        } => MutationForDigest::Append {
            namespace: namespace.clone(),
            content: content.clone(),
            source: source.clone(),
            metadata: metadata.clone(),
        },
        Mutation::Supersede {
            target_fact_id,
            content,
            source,
        } => MutationForDigest::Supersede {
            target_fact_id: target_fact_id.clone(),
            content: content.clone(),
            source: source.clone(),
        },
        Mutation::Redact {
            target_fact_id,
            reason,
        } => MutationForDigest::Redact {
            target_fact_id: target_fact_id.clone(),
            reason: reason.clone(),
        },
    };
    digest_serialized(&Payload {
        operation_kind: mutation.kind(),
        mutation: &digest_mutation,
        origin_label_digest,
    })
}

fn effective_origin_label(
    tx: &Transaction<'_>,
    permit: &AuthorityPermit,
    mutation: &Mutation,
) -> Result<OriginAuthorityLabelV1, MemoryError> {
    let proposed =
        permit
            .origin_authority
            .clone()
            .ok_or_else(|| MemoryError::OriginAuthorityRejected {
                principal: permit.principal.clone(),
                reason: "canonical write has no origin label".into(),
            })?;
    let target_id = match mutation {
        Mutation::Append { namespace, .. } => {
            return proposed
                .bind_resource_scope(crate::NamespaceScopeV1::exact(namespace))
                .map_err(|reason| MemoryError::OriginAuthorityRejected {
                    principal: permit.principal.clone(),
                    reason,
                })
        }
        Mutation::Supersede { target_fact_id, .. } | Mutation::Redact { target_fact_id, .. } => {
            target_fact_id
        }
    };
    let target =
        load_origin_record(tx, target_id)?.ok_or_else(|| MemoryError::OriginAuthorityRejected {
            principal: permit.principal.clone(),
            reason: format!("target '{target_id}' has no canonical origin label"),
        })?;
    // A replacement inherits the target's immutable resource scope. A caller cannot use a
    // freshly supplied, broader label to widen a lineage during supersession or redaction.
    let proposed = proposed
        .bind_resource_scope(target.label.resource_scope.clone())
        .map_err(|reason| MemoryError::OriginAuthorityRejected {
            principal: permit.principal.clone(),
            reason,
        })?;
    let content_digest = mutation_content_digest(mutation)?;
    OriginAuthorityLabelV1::derive(
        &[target.label, proposed],
        OriginDerivationKindV1::Other,
        content_digest,
    )
    .map_err(|reason| MemoryError::OriginAuthorityRejected {
        principal: permit.principal.clone(),
        reason,
    })
}

fn persist_origin_label(
    tx: &Transaction<'_>,
    fact_id: &str,
    label: &OriginAuthorityLabelV1,
    label_digest: &str,
) -> Result<(), MemoryError> {
    let label_json = serde_json::to_string(label)
        .map_err(|error| MemoryError::Other(format!("serialize origin label: {error}")))?;
    tx.execute(
        "INSERT INTO origin_authority_labels (fact_id, label_json, label_digest, recorded_at)
         VALUES (?1, ?2, ?3, ?4)",
        params![
            fact_id,
            label_json,
            label_digest,
            Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string(),
        ],
    )?;
    Ok(())
}

fn load_origin_record(
    conn: &Connection,
    fact_id: &str,
) -> Result<Option<OriginAuthorityRecordV1>, MemoryError> {
    let row: Option<(String, String, String)> = conn
        .query_row(
            "SELECT label_json, label_digest, recorded_at FROM origin_authority_labels
             WHERE fact_id = ?1",
            params![fact_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .optional()?;
    row.map(|(json, label_digest, recorded_at)| {
        let label = serde_json::from_str(&json).map_err(|error| MemoryError::CorruptData {
            table: "origin_authority_labels",
            row_id: fact_id.into(),
            detail: format!("invalid origin label: {error}"),
        })?;
        Ok(OriginAuthorityRecordV1 {
            fact_id: fact_id.into(),
            label,
            label_digest,
            recorded_at,
        })
    })
    .transpose()
}

fn governed_fact_access(
    conn: &Connection,
    fact_id: &str,
    request: &GovernedAccessRequestV1,
) -> Result<GovernedFactAccessV1, MemoryError> {
    let fact = crate::knowledge::get_fact(conn, fact_id)?;
    let origin = load_origin_record(conn, fact_id)?;
    let revocation_reference: Option<String> = conn
        .query_row(
            "SELECT revocation_reference FROM origin_authority_revocations
             WHERE fact_id = ?1 ORDER BY revoked_at DESC LIMIT 1",
            params![fact_id],
            |row| row.get(0),
        )
        .optional()?;
    let decision = decide(
        fact_id,
        fact.as_ref().map(|fact| fact.namespace.as_str()),
        origin.as_ref(),
        revocation_reference.as_deref(),
        request,
    );
    Ok(GovernedFactAccessV1 {
        fact: decision.allowed.then_some(fact).flatten(),
        decision,
        origin,
    })
}

fn mutation_content_digest(mutation: &Mutation) -> Result<String, MemoryError> {
    match mutation {
        Mutation::Append {
            namespace,
            content,
            source,
            metadata,
        } => digest_serialized(&(namespace, content, source, metadata)),
        Mutation::Supersede {
            target_fact_id,
            content,
            source,
        } => digest_serialized(&(target_fact_id, content, source)),
        Mutation::Redact {
            target_fact_id,
            reason,
        } => digest_serialized(&(REDACTED_CONTENT, target_fact_id, reason)),
    }
}

fn digest_serialized<T: Serialize>(value: &T) -> Result<String, MemoryError> {
    let bytes = serde_json::to_vec(value)
        .map_err(|e| MemoryError::DigestError(format!("serialize digest input: {e}")))?;
    Ok(blake3::hash(&bytes).to_hex().to_string())
}

fn receipt_without_digest(receipt: &AuthorityReceiptV1) -> Result<AuthorityReceiptV1, MemoryError> {
    let mut value = receipt.clone();
    value.receipt_digest.clear();
    Ok(value)
}

#[derive(Debug)]
struct ExistingOperation {
    payload_digest: String,
    principal: String,
    caller_id: String,
    operation_kind: String,
    receipt_json: String,
}

fn existing_operation(
    tx: &Transaction<'_>,
    key: &str,
) -> Result<Option<ExistingOperation>, MemoryError> {
    tx.query_row(
        "SELECT oj.payload_digest, oj.principal, oj.caller_id, oj.operation_kind,
                ar.receipt_json
         FROM operation_journal oj
         JOIN authority_receipts ar ON ar.operation_id = oj.operation_id
         WHERE oj.caller_idempotency_key = ?1",
        params![key],
        |row| {
            Ok(ExistingOperation {
                payload_digest: row.get(0)?,
                principal: row.get(1)?,
                caller_id: row.get(2)?,
                operation_kind: row.get(3)?,
                receipt_json: row.get(4)?,
            })
        },
    )
    .optional()
    .map_err(MemoryError::Database)
}

fn get_receipt(
    conn: &Connection,
    field: &str,
    value: &str,
) -> Result<Option<AuthorityReceiptV1>, MemoryError> {
    let sql = format!("SELECT receipt_json FROM authority_receipts WHERE {field} = ?1");
    let json: Option<String> = conn
        .query_row(&sql, params![value], |row| row.get(0))
        .optional()?;
    json.map(|raw| {
        serde_json::from_str(&raw).map_err(|e| MemoryError::CorruptData {
            table: "authority_receipts",
            row_id: value.to_string(),
            detail: format!("invalid stored receipt: {e}"),
        })
    })
    .transpose()
}

fn get_transition_record(
    conn: &Connection,
    key: &str,
) -> Result<Option<MemoryTransitionRecordV1>, MemoryError> {
    type TransitionRow = (
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        Option<String>,
        String,
    );
    let row: Option<TransitionRow> = conn
        .query_row(
            "SELECT record_id, principal, caller_id, candidate_digest, candidate_json,
                    verification_json, disposition, authority_receipt_id, created_at
             FROM memory_transition_records WHERE caller_idempotency_key = ?1",
            params![key],
            |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                    row.get(5)?,
                    row.get(6)?,
                    row.get(7)?,
                    row.get(8)?,
                ))
            },
        )
        .optional()?;
    let Some((
        record_id,
        principal,
        caller_id,
        candidate_digest,
        candidate_json,
        verification_json,
        disposition,
        authority_receipt_id,
        created_at,
    )) = row
    else {
        return Ok(None);
    };
    let candidate =
        serde_json::from_str(&candidate_json).map_err(|error| MemoryError::CorruptData {
            table: "memory_transition_records",
            row_id: record_id.clone(),
            detail: format!("invalid candidate JSON: {error}"),
        })?;
    let verification =
        serde_json::from_str(&verification_json).map_err(|error| MemoryError::CorruptData {
            table: "memory_transition_records",
            row_id: record_id.clone(),
            detail: format!("invalid verification JSON: {error}"),
        })?;
    let disposition = match disposition.as_str() {
        "commit" => TransitionDisposition::Commit,
        "quarantine" => TransitionDisposition::Quarantine,
        other => {
            return Err(MemoryError::CorruptData {
                table: "memory_transition_records",
                row_id: record_id,
                detail: format!("invalid transition disposition '{other}'"),
            })
        }
    };
    Ok(Some(MemoryTransitionRecordV1 {
        schema_version: MEMORY_TRANSITION_RECORD_V1.into(),
        record_id,
        caller_idempotency_key: key.to_string(),
        principal,
        caller_id,
        candidate_digest,
        candidate,
        verification,
        disposition,
        authority_receipt_id,
        created_at,
    }))
}

fn fault_gate(
    fault: &Arc<Mutex<Option<AuthorityFaultStage>>>,
    stage: AuthorityFaultStage,
) -> Result<(), MemoryError> {
    let mut guard = fault
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if *guard == Some(stage) {
        *guard = None;
        return Err(MemoryError::AuthorityFaultInjected { stage });
    }
    Ok(())
}