crtx-store 0.1.0

SQLite persistence: migrations, repositories, transactions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
//! Memory repository operations.
//!
//! ADR 0038 makes durable memory admission a policy-bearing surface, and
//! ADR 0026 ยง2 requires every mutation of that surface to compose through the
//! policy lattice. The candidate -> active transition
//! ([`MemoryRepo::accept_candidate`]) and the schema-v2 summary-span / salience
//! opt-in write ([`MemoryRepo::insert_candidate_with_v2_fields`]) both require
//! the caller to pass a composed [`PolicyDecision`] whose contributing rules
//! name the ADR-level invariants being asserted.
//!
//! Required contributor rule ids:
//!
//! - [`ACCEPT_PROOF_CLOSURE_RULE_ID`], [`ACCEPT_OPEN_CONTRADICTION_RULE_ID`],
//!   [`ACCEPT_SEMANTIC_TRUST_RULE_ID`], and
//!   [`ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID`] for
//!   [`MemoryRepo::accept_candidate`].
//! - [`V2_SUMMARY_SPAN_PROOF_RULE_ID`] and
//!   [`V2_CROSS_SESSION_SALIENCE_RULE_ID`] for
//!   [`MemoryRepo::insert_candidate_with_v2_fields`].
//!
//! The default [`MemoryRepo::insert_candidate`] entry point remains the policy
//! surface for non-summary-bearing candidates: the lifecycle layer
//! (`cortex_memory::lifecycle::accept_candidate`) already composes the AXIOM
//! admission envelope before that store call (punch-list slices #1/#2/#3).
//!
//! The v1-named [`MemoryRepo::insert_candidate`] stays the default after the
//! schema-v2 cutover. `insert_candidate_with_v2_fields` is the explicit opt-in
//! for memories that carry summary spans or cross-session salience metadata โ€”
//! making it the default would force every non-summary caller to fabricate
//! empty span vectors and zero-salience records, which is strictly higher
//! blast radius than keeping the opt-in shape.

use chrono::{DateTime, Utc};
use cortex_core::{
    validate_summary_spans, AuditRecordId, CrossSessionSalience, EventId, MemoryId,
    OutcomeMemoryRelation, PolicyContribution, PolicyDecision, PolicyOutcome, ProofClosureReport,
    ProofState, SourceAuthority, SummarySpan, TemporalAuthorityReport,
};
use rusqlite::{params, OptionalExtension, Row};
use serde_json::Value;

use crate::{Pool, StoreError, StoreResult};

/// Required contributor rule id documenting that supporting-memory proof
/// closure composed into the candidate -> active acceptance decision
/// (ADR 0021, ADR 0036, ADR 0026 ยง5). `PARTIAL` / `BROKEN` proof state on
/// supporting rows MUST surface as `Reject` or `Quarantine`.
pub const ACCEPT_PROOF_CLOSURE_RULE_ID: &str = "memory.accept.proof_closure";
/// Required contributor rule id documenting that the open-durable-contradiction
/// scan composed into the candidate -> active acceptance decision (ADR 0024
/// `ConflictUnresolved`, ADR 0026 ยง5). Unresolved open contradictions over the
/// candidate's claim slot MUST surface as `Reject` or `Quarantine`.
pub const ACCEPT_OPEN_CONTRADICTION_RULE_ID: &str = "memory.accept.open_contradiction";
/// Required contributor rule id documenting the semantic-trust posture for the
/// candidate (ADR 0019 trust tiering, ADR 0038 AXIOM admission). The contributor
/// must summarise authority class, redaction status, and evidence class.
pub const ACCEPT_SEMANTIC_TRUST_RULE_ID: &str = "memory.accept.semantic_trust";
/// Required contributor rule id documenting that the operator promoting the
/// candidate currently holds the temporal authority required for the
/// acceptance write (ADR 0023 ยง3 current-use, ADR 0026 ยง4).
/// `BreakGlass` MUST NOT substitute for this contributor.
pub const ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID: &str = "memory.accept.operator_temporal_use";

/// Required contributor rule id documenting that a `Validated`
/// outcome-memory edge carries an ADR 0020 ยง6 scoped-validation payload
/// (`validation_scope`). Phase 2.6 D1 closure: an unscoped `Validated` write
/// is the on-disk twin of `trust_break_utility_to_truth_laundering_001` and
/// must fail closed.
pub const OUTCOME_VALIDATION_SCOPE_RULE_ID: &str = "memory.outcome.validation_scope";
/// Required contributor rule id documenting that the principal who authored a
/// `Validated` outcome-memory edge satisfies the ADR 0020 ยง5 trust-tier
/// proportionality gate for the memory class. Phase 2.6 D1 closure.
pub const OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID: &str =
    "memory.outcome.validating_principal_tier";
/// Required contributor rule id documenting that a `Validated`
/// outcome-memory edge cites concrete evidence (ADR 0020 ยง6 `evidence_ref`)
/// rather than asserting validation from utility alone.
pub const OUTCOME_EVIDENCE_REF_RULE_ID: &str = "memory.outcome.evidence_ref";

/// Stable invariant name surfaced when [`MemoryRepo::record_outcome_relation`]
/// refuses a `Validated` write because the composed [`PolicyDecision`] would
/// launder utility evidence into truth/validation state. Phase 2.6 D1
/// closure โ€” the durable twin of the in-memory
/// `EpistemicError::UtilityCannotUpgradeTruth` guard in
/// `cortex_memory::epistemic`.
pub const OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT: &str =
    "memory.outcome.utility_to_truth_promotion_unauthorized";

/// Threshold above which repeated `record_session_use` calls without a
/// `Validated` outcome edge become weakly negative on the durable side
/// (Phase 2.6 D2 closure, ADR 0020 ยง3). Once
/// `cross_session_use_count > CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD` for
/// a memory whose `validation_epoch == 0`, the reconcile path surfaces the
/// stable invariant
/// [`CROSS_SESSION_USE_REPEATED_UNVALIDATED_WEAK_NEGATIVE_INVARIANT`]. Five
/// matches the in-memory threshold used by
/// `cortex_memory::salience::brightness`.
pub const CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD: u32 = 5;

/// Stable invariant name surfaced when the durable
/// `cross_session_use_count` for a memory exceeds
/// [`CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD`] without a single `Validated`
/// outcome edge having advanced `validation_epoch`. Phase 2.6 D2 closure โ€”
/// the durable twin of the ADR 0020 ยง3 "repeated `Used` without `Validated`
/// is weakly negative" rule. This is a *signal*, not a refusal: the use
/// edge still writes, but the reconciled row carries this invariant on its
/// derived weak-negative state so retrieval scoring and operator review can
/// observe it.
pub const CROSS_SESSION_USE_REPEATED_UNVALIDATED_WEAK_NEGATIVE_INVARIANT: &str =
    "memory.cross_session_use.repeated_unvalidated_weak_negative";

/// Reconciled weak-negative status of a memory's cross-session reuse axis
/// after [`MemoryRepo::record_session_use`] writes the side table.
///
/// Phase 2.6 D2 closure: the in-memory `Salience::use_count` carries a small
/// penalty in `cortex_memory::salience::brightness`, but that scoring path
/// operates on an in-memory struct that is unreachable from durable
/// retrieval. This enum is the durable read-side projection of the same
/// rule, derived from `(cross_session_use_count, validation_epoch)` on
/// the memory row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrossSessionWeakNegativeStatus {
    /// Cross-session reuse is at or below the threshold; no weak-negative
    /// signal applies.
    BelowThreshold,
    /// Cross-session reuse exceeded the threshold but a `Validated`
    /// outcome edge has advanced `validation_epoch` since admission;
    /// weak-negative is cancelled by that validation.
    SuppressedByValidation,
    /// `cross_session_use_count >
    /// CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD` AND `validation_epoch ==
    /// 0`. The stable invariant
    /// [`CROSS_SESSION_USE_REPEATED_UNVALIDATED_WEAK_NEGATIVE_INVARIANT`]
    /// fires.
    WeakNegativeAboveThreshold {
        /// Cross-session use count that crossed the threshold.
        cross_session_use_count: u32,
    },
}

impl CrossSessionWeakNegativeStatus {
    /// True when the weak-negative invariant fires for this status.
    #[must_use]
    pub const fn is_weak_negative(self) -> bool {
        matches!(self, Self::WeakNegativeAboveThreshold { .. })
    }

    /// Returns the stable invariant name when the weak-negative signal fires.
    #[must_use]
    pub const fn invariant(self) -> Option<&'static str> {
        match self {
            Self::WeakNegativeAboveThreshold { .. } => {
                Some(CROSS_SESSION_USE_REPEATED_UNVALIDATED_WEAK_NEGATIVE_INVARIANT)
            }
            _ => None,
        }
    }
}

/// Derive the cross-session weak-negative status from durable salience fields.
///
/// Phase 2.6 D2 closure: the rule mirrors
/// `cortex_memory::salience::brightness`'s `unvalidated_use_penalty`. A
/// memory with `cross_session_use_count >
/// CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD` and `validation_epoch == 0`
/// fires the stable invariant; any positive `validation_epoch` suppresses
/// the signal because a `Validated` outcome edge has advanced the
/// authoritative column (and that edge itself was gated by the ADR 0026 +
/// ADR 0020 ยง6 envelope on D1).
#[must_use]
pub const fn cross_session_weak_negative_status(
    cross_session_use_count: u32,
    validation_epoch: u32,
) -> CrossSessionWeakNegativeStatus {
    if cross_session_use_count <= CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD {
        return CrossSessionWeakNegativeStatus::BelowThreshold;
    }
    if validation_epoch > 0 {
        return CrossSessionWeakNegativeStatus::SuppressedByValidation;
    }
    CrossSessionWeakNegativeStatus::WeakNegativeAboveThreshold {
        cross_session_use_count,
    }
}

/// Required contributor rule id documenting that the proposed summary spans
/// validated against ADR 0015 (range/UTF-8 alignment, non-whitespace coverage,
/// `max_source_authority == authority_fold(...)`) before any v2 INSERT
/// (ADR 0026 ยง5). A validation failure MUST surface as `Reject`.
pub const V2_SUMMARY_SPAN_PROOF_RULE_ID: &str = "memory.v2.summary_span_proof";
/// Required contributor rule id documenting that the proposed cross-session
/// salience record satisfies ADR 0017 invariants for a candidate row at insert
/// time. Pre-populated `cross_session_use_count`, `last_validation_at`, or
/// `validation_epoch` on a brand-new candidate are forbidden โ€” cross-session
/// salience must be earned through `record_session_use` and a `Validated`
/// outcome edge, never minted at insert.
pub const V2_CROSS_SESSION_SALIENCE_RULE_ID: &str = "memory.v2.cross_session_salience";

macro_rules! memory_select_sql {
    ($where_clause:literal) => {
        concat!(
            "SELECT id, memory_type, status, claim, source_episodes_json, source_events_json,
                    domains_json, salience_json, confidence, authority, applies_when_json,
                    does_not_apply_when_json, created_at, updated_at
             FROM memories ",
            $where_clause,
            ";"
        )
    };
}

/// Candidate memory data accepted by [`MemoryRepo::insert_candidate`].
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryCandidate {
    /// Stable memory identifier.
    pub id: MemoryId,
    /// Memory type tag.
    pub memory_type: String,
    /// Candidate memory claim.
    pub claim: String,
    /// Episode lineage as JSON.
    pub source_episodes_json: Value,
    /// Event lineage as JSON.
    pub source_events_json: Value,
    /// Domain tags as JSON.
    pub domains_json: Value,
    /// Salience fields as JSON.
    pub salience_json: Value,
    /// Confidence score in `[0, 1]`.
    pub confidence: f64,
    /// Authority label.
    pub authority: String,
    /// Applicability constraints as JSON.
    pub applies_when_json: Value,
    /// Negative applicability constraints as JSON.
    pub does_not_apply_when_json: Value,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Update timestamp.
    pub updated_at: DateTime<Utc>,
}

/// Durable memory row read from the store.
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryRecord {
    /// Stable memory identifier.
    pub id: MemoryId,
    /// Memory type tag.
    pub memory_type: String,
    /// Lifecycle status.
    pub status: String,
    /// Memory claim.
    pub claim: String,
    /// Episode lineage as JSON.
    pub source_episodes_json: Value,
    /// Event lineage as JSON.
    pub source_events_json: Value,
    /// Domain tags as JSON.
    pub domains_json: Value,
    /// Salience fields as JSON.
    pub salience_json: Value,
    /// Confidence score in `[0, 1]`.
    pub confidence: f64,
    /// Authority label.
    pub authority: String,
    /// Applicability constraints as JSON.
    pub applies_when_json: Value,
    /// Negative applicability constraints as JSON.
    pub does_not_apply_when_json: Value,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Update timestamp.
    pub updated_at: DateTime<Utc>,
}

/// Audit data written by [`MemoryRepo::accept_candidate`].
#[derive(Debug, Clone, PartialEq)]
pub struct MemoryAcceptanceAudit {
    /// Stable audit row identifier.
    pub id: AuditRecordId,
    /// Actor descriptor JSON.
    pub actor_json: Value,
    /// Operator-facing reason.
    pub reason: String,
    /// Source references JSON.
    pub source_refs_json: Value,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
}

/// One schema-v2 cross-session memory use side-table row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemorySessionUse {
    /// Memory that was reused.
    pub memory_id: MemoryId,
    /// Session in which the memory was used.
    pub session_id: String,
    /// First observed use for this memory/session pair.
    pub first_used_at: DateTime<Utc>,
    /// Last observed use for this memory/session pair.
    pub last_used_at: DateTime<Utc>,
    /// Positive use count for this memory/session pair.
    pub use_count: u32,
}

/// One schema-v2 outcome-to-memory relation side-table row.
///
/// ADR 0020 ยง6 scoped-validation payload: a `Validated` row MUST carry
/// `validation_scope`, `validating_principal_id`, and `evidence_ref`.
/// Non-validation relations leave them `None` because they do not move the
/// validation axis (Phase 2.6 D1 closure).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutcomeMemoryRelationRecord {
    /// Stable outcome reference.
    pub outcome_ref: String,
    /// Memory related to the outcome.
    pub memory_id: MemoryId,
    /// Typed outcome/memory relation.
    pub relation: OutcomeMemoryRelation,
    /// Relation timestamp.
    pub recorded_at: DateTime<Utc>,
    /// Optional source event that introduced the outcome evidence.
    pub source_event_id: Option<EventId>,
    /// ADR 0020 ยง6 scope under which the validation applies. Required for
    /// `Validated` relations; must be `None` for non-validation relations.
    pub validation_scope: Option<String>,
    /// ADR 0020 ยง6 stable identifier of the principal whose authority backs
    /// the validation. Required for `Validated` relations; must be `None`
    /// otherwise.
    pub validating_principal_id: Option<String>,
    /// ADR 0020 ยง6 reference to the concrete evidence (audit row, event,
    /// attestation digest) supporting the validation. Required for
    /// `Validated` relations; must be `None` otherwise.
    pub evidence_ref: Option<String>,
}

/// Repository for memory candidate lifecycle rows.
#[derive(Debug)]
pub struct MemoryRepo<'a> {
    pool: &'a Pool,
}

impl<'a> MemoryRepo<'a> {
    /// Creates a memory repository over an open SQLite connection.
    #[must_use]
    pub const fn new(pool: &'a Pool) -> Self {
        Self { pool }
    }

    /// Inserts a candidate memory after enforcing minimum lineage.
    pub fn insert_candidate(&self, memory: &MemoryCandidate) -> StoreResult<()> {
        if json_array_empty(&memory.source_episodes_json)
            && json_array_empty(&memory.source_events_json)
        {
            return Err(StoreError::Validation(
                "memory candidate requires episode or event lineage".into(),
            ));
        }

        self.pool.execute(
            "INSERT INTO memories (
                id, memory_type, status, claim, source_episodes_json, source_events_json,
                domains_json, salience_json, confidence, authority, applies_when_json,
                does_not_apply_when_json, created_at, updated_at
             ) VALUES (?1, ?2, 'candidate', ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13);",
            params![
                memory.id.to_string(),
                memory.memory_type,
                memory.claim,
                serde_json::to_string(&memory.source_episodes_json)?,
                serde_json::to_string(&memory.source_events_json)?,
                serde_json::to_string(&memory.domains_json)?,
                serde_json::to_string(&memory.salience_json)?,
                memory.confidence,
                memory.authority,
                serde_json::to_string(&memory.applies_when_json)?,
                serde_json::to_string(&memory.does_not_apply_when_json)?,
                memory.created_at.to_rfc3339(),
                memory.updated_at.to_rfc3339(),
            ],
        )?;

        Ok(())
    }

    /// Inserts one candidate memory with explicit schema-v2 summary-span and
    /// salience fields through the ADR 0026 enforcement lattice.
    ///
    /// The schema-v2 cutover has landed; this opt-in API persists rows that
    /// carry ADR 0015 summary spans and ADR 0017 cross-session salience
    /// metadata. The default v1-named [`Self::insert_candidate`] path remains
    /// the entry point for non-summary candidates so the lifecycle-layer
    /// AXIOM admission gate (`cortex_memory::lifecycle::accept_candidate`)
    /// continues to compose policy upstream.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this insertion and
    /// MUST satisfy:
    ///
    /// 1. The final outcome is one of [`PolicyOutcome::Allow`],
    ///    [`PolicyOutcome::Warn`], or [`PolicyOutcome::BreakGlass`]. A
    ///    `Quarantine` or `Reject` decision fails closed and writes nothing.
    /// 2. The composition includes contributors for both
    ///    [`V2_SUMMARY_SPAN_PROOF_RULE_ID`] and
    ///    [`V2_CROSS_SESSION_SALIENCE_RULE_ID`]. The repo refuses callers that
    ///    skipped composition.
    ///
    /// Even when the caller's `policy` argument is `Allow`, the repo
    /// independently re-validates `summary_spans` against
    /// [`validate_summary_spans`] and the salience record against the
    /// ADR 0017 candidate-row invariants enforced by
    /// [`validate_candidate_cross_session_salience`]. ADR 0026 ยง2 forbids a
    /// subsystem-local fuse outside the engine, so a stale `Allow` policy
    /// can never reach the SQLite INSERT after the underlying invariant
    /// regressed.
    pub fn insert_candidate_with_v2_fields(
        &self,
        memory: &MemoryCandidate,
        summary_spans: &[SummarySpan],
        salience: &CrossSessionSalience,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_policy_final_outcome(policy, "memory.v2.insert_candidate")?;
        require_contributor_rule(policy, V2_SUMMARY_SPAN_PROOF_RULE_ID)?;
        require_contributor_rule(policy, V2_CROSS_SESSION_SALIENCE_RULE_ID)?;

        if json_array_empty(&memory.source_episodes_json)
            && json_array_empty(&memory.source_events_json)
        {
            return Err(StoreError::Validation(
                "memory candidate requires episode or event lineage".into(),
            ));
        }
        if memory.memory_type.contains("summary") || !summary_spans.is_empty() {
            validate_summary_spans(&memory.claim, summary_spans, |_| SourceAuthority::Derived)
                .map_err(|err| {
                    StoreError::Validation(format!(
                        "memory summary_spans_json failed {}",
                        err.invariant()
                    ))
                })?;
        }
        validate_candidate_cross_session_salience(salience)?;

        self.pool.execute(
            "INSERT INTO memories (
                id, memory_type, status, claim, source_episodes_json, source_events_json,
                domains_json, salience_json, confidence, authority, applies_when_json,
                does_not_apply_when_json, created_at, updated_at, summary_spans_json,
                cross_session_use_count, first_used_at, last_cross_session_use_at,
                last_validation_at, validation_epoch, blessed_until
             ) VALUES (
                ?1, ?2, 'candidate', ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14,
                ?15, ?16, ?17, ?18, ?19, ?20
             );",
            params![
                memory.id.to_string(),
                memory.memory_type,
                memory.claim,
                serde_json::to_string(&memory.source_episodes_json)?,
                serde_json::to_string(&memory.source_events_json)?,
                serde_json::to_string(&memory.domains_json)?,
                serde_json::to_string(&memory.salience_json)?,
                memory.confidence,
                memory.authority,
                serde_json::to_string(&memory.applies_when_json)?,
                serde_json::to_string(&memory.does_not_apply_when_json)?,
                memory.created_at.to_rfc3339(),
                memory.updated_at.to_rfc3339(),
                serde_json::to_string(summary_spans)?,
                i64::from(salience.cross_session_use_count),
                salience.first_used_at.map(|value| value.to_rfc3339()),
                salience
                    .last_cross_session_use_at
                    .map(|value| value.to_rfc3339()),
                salience.last_validation_at.map(|value| value.to_rfc3339()),
                i64::from(salience.validation_epoch),
                salience.blessed_until.map(|value| value.to_rfc3339()),
            ],
        )?;

        Ok(())
    }

    /// Records a schema-v2 memory/session use edge and reconciles memory salience columns.
    ///
    /// This opt-in API requires the S2 side table and v2 salience columns to exist.
    pub fn record_session_use(&self, use_row: &MemorySessionUse) -> StoreResult<()> {
        if use_row.session_id.trim().is_empty() {
            return Err(StoreError::Validation(
                "memory session use requires non-empty session_id".into(),
            ));
        }
        if use_row.use_count == 0 {
            return Err(StoreError::Validation(
                "memory session use requires positive use_count".into(),
            ));
        }
        if use_row.last_used_at < use_row.first_used_at {
            return Err(StoreError::Validation(
                "memory session use last_used_at cannot be earlier than first_used_at".into(),
            ));
        }

        let tx = self.pool.unchecked_transaction()?;
        ensure_memory_exists(&tx, &use_row.memory_id)?;
        tx.execute(
            "INSERT INTO memory_session_uses (
                memory_id, session_id, first_used_at, last_used_at, use_count
             ) VALUES (?1, ?2, ?3, ?4, ?5)
             ON CONFLICT(memory_id, session_id) DO UPDATE SET
                first_used_at = excluded.first_used_at,
                last_used_at = excluded.last_used_at,
                use_count = excluded.use_count;",
            params![
                use_row.memory_id.to_string(),
                use_row.session_id.as_str(),
                use_row.first_used_at.to_rfc3339(),
                use_row.last_used_at.to_rfc3339(),
                i64::from(use_row.use_count),
            ],
        )?;
        reconcile_memory_session_salience(&tx, &use_row.memory_id)?;
        tx.commit()?;

        Ok(())
    }

    /// Records a schema-v2 outcome/memory relation edge.
    ///
    /// Validated outcome relations advance validation freshness; mere use edges never do.
    ///
    /// Phase 2.6 D1 closure: a `Validated` write is the durable twin of the
    /// in-memory `EpistemicError::UtilityCannotUpgradeTruth` guard
    /// (`cortex_memory::epistemic`). It MUST compose a [`PolicyDecision`]
    /// satisfying:
    ///
    /// 1. The final outcome is one of [`PolicyOutcome::Allow`],
    ///    [`PolicyOutcome::Warn`], or [`PolicyOutcome::BreakGlass`]. A
    ///    `Quarantine` or `Reject` decision fails closed and writes nothing.
    /// 2. The composition includes contributors for
    ///    [`OUTCOME_VALIDATION_SCOPE_RULE_ID`],
    ///    [`OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID`], and
    ///    [`OUTCOME_EVIDENCE_REF_RULE_ID`]. The repo refuses callers that
    ///    skipped composition with the stable invariant
    ///    [`OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT`].
    /// 3. The relation row carries `validation_scope`,
    ///    `validating_principal_id`, and `evidence_ref` per ADR 0020 ยง6.
    ///
    /// Non-validation relations (Used / Contradicted / Superseded / Rejected)
    /// do not move the validation axis and are accepted without a
    /// `PolicyDecision`. Pass `None` for the `policy` parameter in that case;
    /// passing `Some(..)` for a non-validation relation is rejected so callers
    /// cannot quietly attach an unrelated decision to a non-validation write.
    pub fn record_outcome_relation(
        &self,
        relation: &OutcomeMemoryRelationRecord,
        policy: Option<&PolicyDecision>,
    ) -> StoreResult<()> {
        if relation.outcome_ref.trim().is_empty() {
            return Err(StoreError::Validation(
                "outcome memory relation requires non-empty outcome_ref".into(),
            ));
        }

        if relation.relation.advances_validation() {
            // ADR 0026 ยง2 + ADR 0020 ยง4 + ADR 0020 ยง6: Validated edges must
            // compose a policy decision and carry the scoped-validation
            // payload. Reject otherwise โ€” this is the D1 fail-closed path.
            let policy = policy.ok_or_else(|| {
                StoreError::Validation(format!(
                    "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: Validated outcome relation requires a composed PolicyDecision; caller skipped ADR 0026 composition",
                ))
            })?;
            require_policy_final_outcome_for_validation(policy)?;
            require_contributor_rule_for_validation(policy, OUTCOME_VALIDATION_SCOPE_RULE_ID)?;
            require_contributor_rule_for_validation(
                policy,
                OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID,
            )?;
            require_contributor_rule_for_validation(policy, OUTCOME_EVIDENCE_REF_RULE_ID)?;
            require_scoped_validation_payload(relation)?;
        } else if policy.is_some() {
            return Err(StoreError::Validation(format!(
                "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: non-validation outcome relation must not carry a PolicyDecision (relation does not move the validation axis)",
            )));
        } else {
            require_no_scoped_validation_payload(relation)?;
        }

        let tx = self.pool.unchecked_transaction()?;
        ensure_memory_exists(&tx, &relation.memory_id)?;
        let relation_wire = serde_json::to_value(relation.relation)?
            .as_str()
            .ok_or_else(|| {
                StoreError::Validation("outcome memory relation did not serialize as string".into())
            })?
            .to_string();
        tx.execute(
            "INSERT INTO outcome_memory_relations (
                outcome_ref, memory_id, relation, recorded_at, source_event_id,
                validation_scope, validating_principal_id, evidence_ref
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
             ON CONFLICT(outcome_ref, memory_id, relation) DO UPDATE SET
                recorded_at = excluded.recorded_at,
                source_event_id = excluded.source_event_id,
                validation_scope = excluded.validation_scope,
                validating_principal_id = excluded.validating_principal_id,
                evidence_ref = excluded.evidence_ref;",
            params![
                relation.outcome_ref.as_str(),
                relation.memory_id.to_string(),
                relation_wire,
                relation.recorded_at.to_rfc3339(),
                relation.source_event_id.as_ref().map(ToString::to_string),
                relation.validation_scope.as_deref(),
                relation.validating_principal_id.as_deref(),
                relation.evidence_ref.as_deref(),
            ],
        )?;
        if relation.relation.advances_validation() {
            tx.execute(
                "UPDATE memories
                 SET last_validation_at = ?2,
                     validation_epoch = COALESCE(validation_epoch, 0) + 1
                 WHERE id = ?1;",
                params![
                    relation.memory_id.to_string(),
                    relation.recorded_at.to_rfc3339()
                ],
            )?;
        }
        tx.commit()?;

        Ok(())
    }

    /// Returns the durable [`CrossSessionWeakNegativeStatus`] for a memory.
    ///
    /// Phase 2.6 D2 closure: derived from
    /// `(cross_session_use_count, validation_epoch)` on the memory row.
    /// Returns `Ok(None)` when the memory id does not exist. NULL durable
    /// columns are treated as `0`.
    pub fn cross_session_weak_negative_status_for(
        &self,
        id: &MemoryId,
    ) -> StoreResult<Option<CrossSessionWeakNegativeStatus>> {
        let row: Option<(Option<u32>, Option<u32>)> = self
            .pool
            .query_row(
                "SELECT cross_session_use_count, validation_epoch FROM memories WHERE id = ?1;",
                params![id.to_string()],
                |row| Ok((row.get::<_, Option<u32>>(0)?, row.get::<_, Option<u32>>(1)?)),
            )
            .optional()?;
        Ok(row.map(|(use_count, epoch)| {
            cross_session_weak_negative_status(use_count.unwrap_or(0), epoch.unwrap_or(0))
        }))
    }

    /// Returns the durable `validation_epoch` for a memory row.
    ///
    /// Phase 2.6 D3 closure: retrieval scoring MUST read validation freshness
    /// from this authoritative column, not from `salience_json["validation"]`.
    /// `salience_json` is authored at candidate insert by the candidate author
    /// and is never updated by any post-admission path; only
    /// [`Self::record_outcome_relation`] advances `validation_epoch`, and that
    /// path is gated by the ADR 0020 ยง4/ยง6 + ADR 0026 ยง4 policy envelope.
    ///
    /// Returns `Ok(None)` when the memory id does not exist. Returns
    /// `Ok(Some(0))` when the column is still NULL โ€” the column is nullable in
    /// the schema (v2 cutover compatibility) and a NULL is treated as "no
    /// validated edge has ever advanced this memory" rather than as ambient
    /// trust.
    pub fn validation_epoch_for(&self, id: &MemoryId) -> StoreResult<Option<u32>> {
        let row: Option<Option<u32>> = self
            .pool
            .query_row(
                "SELECT validation_epoch FROM memories WHERE id = ?1;",
                params![id.to_string()],
                |row| row.get::<_, Option<u32>>(0),
            )
            .optional()?;
        Ok(row.map(|epoch| epoch.unwrap_or(0)))
    }

    /// Fetches a memory row by id.
    pub fn get_by_id(&self, id: &MemoryId) -> StoreResult<Option<MemoryRecord>> {
        let row = self
            .pool
            .query_row(
                memory_select_sql!("WHERE id = ?1"),
                params![id.to_string()],
                memory_row,
            )
            .optional()?;

        row.map(TryInto::try_into).transpose()
    }

    /// Phase 4.B fuzzy retrieval โ€” additive FTS5 trigram lookup.
    ///
    /// Looks up memory ids whose `claim` or `domains_json` matches `query`
    /// under the SQLite FTS5 `trigram` tokenizer (migration
    /// `006_fts5_memories`). Returns `(memory_id, raw_bm25_rank)` pairs in
    /// FTS5's native BM25 ranking order: most-relevant first.
    ///
    /// This is a *read-only* surface intended for the opt-in `--fuzzy` CLI
    /// path. It does NOT replace the default lexical retrieval scorer in
    /// `cortex-retrieval`; the existing default path remains byte-for-byte
    /// unchanged (Phase 4.B eval guardrail). The caller is responsible for
    /// composing fuzzy ranks with the deterministic lexical scorer via the
    /// `compose_fuzzy_boost` helper in `cortex_retrieval::fts5`.
    ///
    /// `query` MUST be a non-empty trimmed string. The CLI surface and the
    /// retrieval helper both pre-validate non-emptiness, but this method
    /// fails closed independently as a defense-in-depth guard.
    ///
    /// `limit` caps the number of returned rows; `0` returns an empty vec
    /// without touching SQLite.
    ///
    /// # Fuzzy expression shape
    ///
    /// The SQLite `trigram` tokenizer is substring-aware: a token is
    /// indexed as the set of its 3-grams, and a `MATCH 'foo'` query
    /// looks for *every* trigram of `foo` to appear in the document.
    /// That is precision-friendly but it refuses one-character typos
    /// because the corrupted trigrams never appear anywhere on disk.
    /// To recover the "typo-of-one-character still hits" property
    /// Phase 4.B requires, each query token is expanded into
    /// overlapping 4-grams joined with `OR`: a query token of length
    /// `n >= 4` becomes `gram1 OR gram2 OR ... OR gram(n-3)`. Each
    /// 4-gram is itself substring-matched by the trigram tokenizer
    /// (FTS5 enforces every trigram of the literal, so a 4-gram is
    /// the smallest piece that still survives a single-character
    /// substitution at one of its endpoints).
    ///
    /// Tokens shorter than four characters are searched as-is โ€” they
    /// already correspond to one trigram or a substring smaller than
    /// the tokenizer's minimum unit, so OR-expansion would add
    /// nothing. Tokens with no alphanumeric characters are dropped
    /// entirely (FTS5 reserves quotes / parens / colons for its
    /// expression language).
    ///
    /// BM25 ranks remain non-positive floats (smaller = better); the
    /// raw rank is passed through unchanged so the retrieval layer
    /// can normalise into the `[0, 1]` band without bias.
    pub fn fts5_search(&self, query: &str, limit: usize) -> StoreResult<Vec<(MemoryId, f32)>> {
        let trimmed = query.trim();
        if trimmed.is_empty() {
            return Err(StoreError::Validation(
                "fts5_search: query must not be empty".into(),
            ));
        }
        if limit == 0 {
            return Ok(Vec::new());
        }

        let match_expr = fts5_fuzzy_match_expression(trimmed).ok_or_else(|| {
            StoreError::Validation(
                "fts5_search: query produced no searchable trigrams after sanitization".into(),
            )
        })?;

        let limit_i64 = i64::try_from(limit)
            .map_err(|_| StoreError::Validation("fts5_search: limit exceeds i64 range".into()))?;

        let mut stmt = self.pool.prepare(
            "SELECT memory_id, rank \
             FROM memories_fts \
             WHERE memories_fts MATCH ?1 \
             ORDER BY rank \
             LIMIT ?2;",
        )?;
        let rows = stmt.query_map(params![match_expr, limit_i64], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, f64>(1)?))
        })?;

        let mut hits = Vec::new();
        for row in rows {
            let (id_text, rank) = row?;
            let id = id_text.parse::<MemoryId>().map_err(|err| {
                StoreError::Validation(format!(
                    "fts5_search: memory_id mirror value `{id_text}` failed to parse: {err}"
                ))
            })?;
            hits.push((id, rank as f32));
        }
        Ok(hits)
    }

    /// Fetches a candidate memory row by id.
    pub fn get_candidate_by_id(&self, id: &MemoryId) -> StoreResult<Option<MemoryRecord>> {
        let row = self
            .pool
            .query_row(
                memory_select_sql!("WHERE id = ?1 AND status = 'candidate'"),
                params![id.to_string()],
                memory_row,
            )
            .optional()?;

        row.map(TryInto::try_into).transpose()
    }

    /// Lists candidate memory rows in deterministic update order.
    pub fn list_candidates(&self) -> StoreResult<Vec<MemoryRecord>> {
        self.list_by_status("candidate")
    }

    /// Lists memory rows matching a lifecycle status.
    pub fn list_by_status(&self, status: &str) -> StoreResult<Vec<MemoryRecord>> {
        let mut stmt = self.pool.prepare(memory_select_sql!(
            "WHERE status = ?1 ORDER BY updated_at DESC, id"
        ))?;
        let rows = stmt.query_map(params![status], memory_row)?;

        let mut memories = Vec::new();
        for row in rows {
            memories.push(row?.try_into()?);
        }
        Ok(memories)
    }

    /// Lists memory rows matching a lifecycle status whose `domains_json`
    /// array contains every supplied tag (AND semantics).
    ///
    /// This is an additive read-path helper for tag-as-retrieval-surface
    /// filtering. It uses SQLite JSON1's `json_each(domains_json)` to score
    /// distinct tag membership, then enforces the AND closure by
    /// `COUNT(DISTINCT je.value) = ?` against the unique tag set.
    ///
    /// An empty `tags` slice is equivalent to [`Self::list_by_status`]: no
    /// tag filter is applied. Duplicates in `tags` are coalesced before the
    /// COUNT comparison so that callers can pass user input directly without
    /// having to dedupe.
    pub fn list_by_status_with_tags(
        &self,
        status: &str,
        tags: &[String],
    ) -> StoreResult<Vec<MemoryRecord>> {
        // Deduplicate the requested tag set. AND semantics over the row's
        // `domains_json` is "the row contains every requested tag at least
        // once"; duplicate inputs should not inflate the COUNT target.
        let mut unique_tags: Vec<String> = Vec::with_capacity(tags.len());
        for tag in tags {
            if !unique_tags.iter().any(|existing| existing == tag) {
                unique_tags.push(tag.clone());
            }
        }

        if unique_tags.is_empty() {
            return self.list_by_status(status);
        }

        // Build a parameterised IN clause large enough for the deduped tag
        // set. Each `?` corresponds to one entry in `unique_tags`. The
        // outer COUNT(DISTINCT je.value) compares against the unique tag
        // count, so a row that carries `["a","b","b"]` and is asked for
        // `["a","b"]` still satisfies the closure.
        let placeholders = std::iter::repeat_n("?", unique_tags.len())
            .collect::<Vec<_>>()
            .join(",");
        let where_clause = format!(
            "WHERE status = ? AND id IN (
                SELECT m.id FROM memories m, json_each(m.domains_json) je
                WHERE je.value IN ({placeholders})
                GROUP BY m.id
                HAVING COUNT(DISTINCT je.value) = ?
             ) ORDER BY updated_at DESC, id"
        );
        let sql = format!(
            "SELECT id, memory_type, status, claim, source_episodes_json, source_events_json, \
                    domains_json, salience_json, confidence, authority, applies_when_json, \
                    does_not_apply_when_json, created_at, updated_at \
             FROM memories {where_clause};"
        );

        let mut stmt = self.pool.prepare(&sql)?;
        let unique_count = i64::try_from(unique_tags.len()).map_err(|_| {
            StoreError::Validation("list_by_status_with_tags: tag count exceeds i64 range".into())
        })?;
        let mut bind_values: Vec<rusqlite::types::Value> =
            Vec::with_capacity(unique_tags.len() + 2);
        bind_values.push(rusqlite::types::Value::Text(status.to_string()));
        for tag in &unique_tags {
            bind_values.push(rusqlite::types::Value::Text(tag.clone()));
        }
        bind_values.push(rusqlite::types::Value::Integer(unique_count));
        let rows = stmt.query_map(rusqlite::params_from_iter(bind_values), memory_row)?;

        let mut memories = Vec::new();
        for row in rows {
            memories.push(row?.try_into()?);
        }
        Ok(memories)
    }

    /// Promotes a memory candidate to active.
    pub fn set_active(&self, id: &MemoryId, updated_at: DateTime<Utc>) -> StoreResult<()> {
        let changed = self.pool.execute(
            "UPDATE memories
             SET status = 'active', updated_at = ?2
             WHERE id = ?1;",
            params![id.to_string(), updated_at.to_rfc3339()],
        )?;

        if changed == 0 {
            return Err(StoreError::Validation(format!("memory {id} not found")));
        }

        Ok(())
    }

    /// Transitions a candidate to `pending_mcp_commit` (ADR 0047).
    ///
    /// Only rows currently in `candidate` status are transitioned. If the row
    /// does not exist or is not a candidate, returns a validation error โ€” the
    /// caller should handle `"not a candidate"` gracefully as an idempotency
    /// signal when the row was already promoted by a prior call.
    pub fn set_pending_mcp_commit(&self, id: &MemoryId, now: DateTime<Utc>) -> StoreResult<()> {
        let changed = self.pool.execute(
            "UPDATE memories
             SET status = 'pending_mcp_commit', updated_at = ?2
             WHERE id = ?1 AND status = 'candidate';",
            params![id.to_string(), now.to_rfc3339()],
        )?;

        if changed == 0 {
            // Either not found, or not a candidate. Distinguish for the caller.
            let current: Option<String> = self
                .pool
                .query_row(
                    "SELECT status FROM memories WHERE id = ?1;",
                    params![id.to_string()],
                    |row| row.get(0),
                )
                .optional()?;
            return Err(StoreError::Validation(match current.as_deref() {
                None => format!("memory {id} not found"),
                Some(s) => format!("memory {id} is not a candidate: {s}"),
            }));
        }

        Ok(())
    }

    /// Promotes all `pending_mcp_commit` rows to `active` (ADR 0047 Path B /
    /// `cortex_session_commit`).
    ///
    /// The single-operator model means there is only one active MCP session at
    /// a time; this bulk-promotes every pending row regardless of which session
    /// wrote it. Returns the number of rows promoted.
    pub fn commit_pending_mcp(
        &self,
        _session_receipt_id: &str,
        now: DateTime<Utc>,
    ) -> StoreResult<usize> {
        let changed = self.pool.execute(
            "UPDATE memories
             SET status = 'active', updated_at = ?1
             WHERE status = 'pending_mcp_commit';",
            params![now.to_rfc3339()],
        )?;
        Ok(changed)
    }

    /// Returns the maximum sensitivity level across all active memories'
    /// `domains_json` arrays.
    ///
    /// Sensitivity tags are `"sensitivity:high"`, `"sensitivity:medium"`, and
    /// `"sensitivity:low"`. The method scans every active memory row's
    /// `domains_json` JSON array for these tags and returns the highest level
    /// found as a string: `"high"`, `"medium"`, `"low"`, or `"none"` when no
    /// sensitivity tags are present in any active memory.
    ///
    /// This replaces the text-scan heuristic in `cortex_llm::sensitivity` with
    /// a real per-memory domain-tag query (ADR 0048 ยง3 follow-on).
    ///
    /// # Errors
    ///
    /// Returns [`StoreError`] when the SQL query or JSON parsing fails.
    pub fn max_sensitivity_for_active_memories(&self) -> StoreResult<String> {
        // Use SQLite JSON1 json_each to expand domains_json arrays and look for
        // sensitivity:* tags. The CASE expression maps tags to a numeric rank so
        // MAX() finds the highest level without application-side iteration.
        let max_rank: Option<i64> = self
            .pool
            .query_row(
                "SELECT MAX(CASE je.value \
                         WHEN 'sensitivity:high'   THEN 3 \
                         WHEN 'sensitivity:medium' THEN 2 \
                         WHEN 'sensitivity:low'    THEN 1 \
                         ELSE                           0 \
                     END) \
                 FROM memories m, json_each(m.domains_json) je \
                 WHERE m.status = 'active' \
                   AND je.value IN ('sensitivity:high', 'sensitivity:medium', 'sensitivity:low');",
                [],
                |row| row.get(0),
            )
            .optional()?
            .flatten();

        let level = match max_rank {
            Some(3) => "high",
            Some(2) => "medium",
            Some(1) => "low",
            _ => "none",
        };
        Ok(level.to_string())
    }

    /// Appends a tag to the memory's `domains_json` array.
    ///
    /// Idempotent: adding an already-present tag is a no-op and returns
    /// `Ok(false)`. Returns `Ok(true)` when the tag was newly added.
    /// Fails with [`StoreError::Validation`] when the memory id does not exist.
    /// The `updated_at` column is advanced to `now` when the tag is added.
    pub fn add_domain_tag(
        &self,
        id: &MemoryId,
        tag: &str,
        now: DateTime<Utc>,
    ) -> StoreResult<bool> {
        if tag.trim().is_empty() {
            return Err(StoreError::Validation(
                "add_domain_tag: tag must not be empty".into(),
            ));
        }
        let tx = self.pool.unchecked_transaction()?;
        let domains_raw: Option<String> = tx
            .query_row(
                "SELECT domains_json FROM memories WHERE id = ?1;",
                params![id.to_string()],
                |row| row.get(0),
            )
            .optional()?;
        let domains_raw =
            domains_raw.ok_or_else(|| StoreError::Validation(format!("memory {id} not found")))?;
        let mut tags: Vec<String> = serde_json::from_str(&domains_raw).map_err(|err| {
            StoreError::Validation(format!(
                "add_domain_tag: domains_json for memory {id} is not a valid JSON array: {err}"
            ))
        })?;
        if tags.iter().any(|t| t == tag) {
            return Ok(false);
        }
        tags.push(tag.to_string());
        let new_domains = serde_json::to_string(&tags)?;
        tx.execute(
            "UPDATE memories SET domains_json = ?2, updated_at = ?3 WHERE id = ?1;",
            params![id.to_string(), new_domains, now.to_rfc3339()],
        )?;
        tx.commit()?;
        Ok(true)
    }

    /// Removes a tag from the memory's `domains_json` array.
    ///
    /// Idempotent: removing a tag that is not present is a no-op and returns
    /// `Ok(false)`. Returns `Ok(true)` when the tag was removed.
    /// Fails with [`StoreError::Validation`] when the memory id does not exist.
    /// The `updated_at` column is advanced to `now` when the tag is removed.
    pub fn remove_domain_tag(
        &self,
        id: &MemoryId,
        tag: &str,
        now: DateTime<Utc>,
    ) -> StoreResult<bool> {
        if tag.trim().is_empty() {
            return Err(StoreError::Validation(
                "remove_domain_tag: tag must not be empty".into(),
            ));
        }
        let tx = self.pool.unchecked_transaction()?;
        let domains_raw: Option<String> = tx
            .query_row(
                "SELECT domains_json FROM memories WHERE id = ?1;",
                params![id.to_string()],
                |row| row.get(0),
            )
            .optional()?;
        let domains_raw =
            domains_raw.ok_or_else(|| StoreError::Validation(format!("memory {id} not found")))?;
        let mut tags: Vec<String> = serde_json::from_str(&domains_raw).map_err(|err| {
            StoreError::Validation(format!(
                "remove_domain_tag: domains_json for memory {id} is not a valid JSON array: {err}"
            ))
        })?;
        let before_len = tags.len();
        tags.retain(|t| t != tag);
        if tags.len() == before_len {
            return Ok(false);
        }
        let new_domains = serde_json::to_string(&tags)?;
        tx.execute(
            "UPDATE memories SET domains_json = ?2, updated_at = ?3 WHERE id = ?1;",
            params![id.to_string(), new_domains, now.to_rfc3339()],
        )?;
        tx.commit()?;
        Ok(true)
    }

    /// Atomically promotes a candidate to active and writes an audit row
    /// through the ADR 0026 enforcement lattice.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this acceptance and
    /// MUST satisfy:
    ///
    /// 1. The final outcome is one of [`PolicyOutcome::Allow`],
    ///    [`PolicyOutcome::Warn`], or [`PolicyOutcome::BreakGlass`]. A
    ///    `Quarantine` or `Reject` decision fails closed and writes nothing.
    /// 2. The composition includes contributors for
    ///    [`ACCEPT_PROOF_CLOSURE_RULE_ID`],
    ///    [`ACCEPT_OPEN_CONTRADICTION_RULE_ID`],
    ///    [`ACCEPT_SEMANTIC_TRUST_RULE_ID`], and
    ///    [`ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID`]. The repo refuses callers
    ///    that skipped composition.
    /// 3. Per ADR 0026 ยง4, the operator temporal-use contributor MUST be
    ///    [`PolicyOutcome::Allow`] even when the final decision is
    ///    `BreakGlass`. Break-glass never substitutes for current-use temporal
    ///    authority at this surface.
    ///
    /// Production callers compose the proof-closure contributor from
    /// [`crate::verify_memory_proof_closure`], the open-contradiction
    /// contributor from the conflict resolver, the semantic-trust contributor
    /// from the AXIOM admission envelope (ADR 0038), and the operator
    /// temporal-use contributor from ADR 0023 `revalidate_temporal_authority`.
    pub fn accept_candidate(
        &self,
        id: &MemoryId,
        updated_at: DateTime<Utc>,
        audit: &MemoryAcceptanceAudit,
        policy: &PolicyDecision,
    ) -> StoreResult<MemoryRecord> {
        require_policy_final_outcome(policy, "memory.accept")?;
        require_contributor_rule(policy, ACCEPT_PROOF_CLOSURE_RULE_ID)?;
        require_contributor_rule(policy, ACCEPT_OPEN_CONTRADICTION_RULE_ID)?;
        require_contributor_rule(policy, ACCEPT_SEMANTIC_TRUST_RULE_ID)?;
        require_contributor_rule(policy, ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID)?;
        require_attestation_not_break_glassed(
            policy,
            ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
            "memory.accept",
        )?;

        let tx = self.pool.unchecked_transaction()?;
        let before = tx
            .query_row(
                "SELECT status FROM memories WHERE id = ?1;",
                params![id.to_string()],
                |row| row.get::<_, String>(0),
            )
            .optional()?;

        match before.as_deref() {
            Some("candidate") => {}
            Some(status) => {
                return Err(StoreError::Validation(format!(
                    "memory {id} is not a candidate: {status}"
                )));
            }
            None => {
                return Err(StoreError::Validation(format!("memory {id} not found")));
            }
        }

        tx.execute(
            "UPDATE memories
             SET status = 'active', updated_at = ?2
             WHERE id = ?1 AND status = 'candidate';",
            params![id.to_string(), updated_at.to_rfc3339()],
        )?;
        tx.execute(
            "INSERT INTO audit_records (
                id, operation, target_ref, before_hash, after_hash, reason,
                actor_json, source_refs_json, created_at
             ) VALUES (?1, 'memory.accept', ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
            params![
                audit.id.to_string(),
                id.to_string(),
                "status:candidate",
                "status:active",
                audit.reason,
                serde_json::to_string(&audit.actor_json)?,
                serde_json::to_string(&audit.source_refs_json)?,
                audit.created_at.to_rfc3339(),
            ],
        )?;

        let row = tx.query_row(
            memory_select_sql!("WHERE id = ?1"),
            params![id.to_string()],
            memory_row,
        )?;
        tx.commit()?;

        row.try_into()
    }
}

fn json_array_empty(value: &Value) -> bool {
    value.as_array().is_some_and(Vec::is_empty)
}

/// Build an FTS5 MATCH expression that surfaces fuzzy hits over the
/// `trigram` tokenizer (Phase 4.B). See the doc comment on
/// [`MemoryRepo::fts5_search`] for the design rationale.
///
/// Returns `None` when the sanitised input produced zero searchable
/// trigrams โ€” the caller turns that into a stable validation error.
fn fts5_fuzzy_match_expression(query: &str) -> Option<String> {
    /// Smallest gram width that can survive a single-character substitution
    /// at one of its endpoints. The trigram tokenizer indexes every 3-gram,
    /// so a 4-character literal in the MATCH expression is itself decomposed
    /// into two overlapping trigrams โ€” the one that does NOT contain the
    /// substituted character still hits the document.
    const FUZZY_GRAM_WIDTH: usize = 4;

    let mut grams: Vec<String> = Vec::new();
    for raw_token in query.split_whitespace() {
        let sanitised: String = raw_token
            .chars()
            .filter(|character| character.is_ascii_alphanumeric())
            .collect::<String>()
            .to_ascii_lowercase();
        if sanitised.is_empty() {
            continue;
        }

        if sanitised.len() < FUZZY_GRAM_WIDTH {
            // Tokens shorter than a fuzzy gram (e.g. "of", "an") are
            // searched as-is. FTS5 tokenises them into one or two trigrams;
            // either matches a substring of any document containing them.
            grams.push(sanitised);
            continue;
        }

        // Expand the token into overlapping FUZZY_GRAM_WIDTH-grams. For
        // "retrieval" (len = 9) this is six 4-grams: "retr", "etri",
        // "trie", "riev", "ieva", "eval". OR-ing them lets a query like
        // "retrievaal" still surface "retrieval" โ€” only the 4-grams that
        // include the substituted character drop out, the rest still hit.
        let bytes = sanitised.as_bytes();
        for start in 0..=bytes.len() - FUZZY_GRAM_WIDTH {
            // SAFETY: `sanitised` is pure ASCII alphanumerics, so every byte
            // is its own UTF-8 boundary and slicing on bytes is safe.
            let gram = &sanitised[start..start + FUZZY_GRAM_WIDTH];
            grams.push(gram.to_string());
        }
    }

    if grams.is_empty() {
        return None;
    }

    // Deduplicate while preserving first-seen order so identical 4-grams
    // from overlapping tokens do not inflate the OR expression.
    let mut unique = Vec::with_capacity(grams.len());
    for gram in grams {
        if !unique.contains(&gram) {
            unique.push(gram);
        }
    }

    // Quote each gram so FTS5 treats it as a literal phrase. The
    // sanitisation above already removed every character FTS5 treats as
    // syntax (parens, colons, quotes), but quoting is the documented way
    // to feed a literal substring through MATCH and is safe against any
    // future change to the sanitiser.
    let mut expression = String::new();
    for (idx, gram) in unique.iter().enumerate() {
        if idx > 0 {
            expression.push_str(" OR ");
        }
        expression.push('"');
        expression.push_str(gram);
        expression.push('"');
    }
    Some(expression)
}

fn require_policy_final_outcome(policy: &PolicyDecision, surface: &str) -> StoreResult<()> {
    match policy.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => Ok(()),
        PolicyOutcome::Quarantine | PolicyOutcome::Reject => Err(StoreError::Validation(format!(
            "{surface} preflight: composed policy outcome {:?} blocks memory mutation",
            policy.final_outcome,
        ))),
    }
}

fn require_contributor_rule(policy: &PolicyDecision, rule_id: &str) -> StoreResult<()> {
    let contains_rule = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .any(|contribution| contribution.rule_id.as_str() == rule_id);
    if contains_rule {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "policy decision missing required contributor `{rule_id}`; caller skipped ADR 0026 composition",
        )))
    }
}

fn require_policy_final_outcome_for_validation(policy: &PolicyDecision) -> StoreResult<()> {
    // Phase 2.6 D1 closure: a Quarantine/Reject final outcome on a Validated
    // edge is the on-disk twin of UtilityCannotUpgradeTruth โ€” surface the
    // stable invariant rather than the generic policy-outcome message.
    match policy.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => Ok(()),
        PolicyOutcome::Quarantine | PolicyOutcome::Reject => Err(StoreError::Validation(format!(
            "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: composed policy outcome {:?} blocks Validated outcome relation write",
            policy.final_outcome,
        ))),
    }
}

fn require_contributor_rule_for_validation(
    policy: &PolicyDecision,
    rule_id: &str,
) -> StoreResult<()> {
    let contains_rule = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .any(|contribution| contribution.rule_id.as_str() == rule_id);
    if contains_rule {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: policy decision missing required contributor `{rule_id}` for Validated outcome relation",
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cortex_core::compose_policy_outcomes;

    fn relation_record(
        relation: OutcomeMemoryRelation,
        with_scope: bool,
    ) -> OutcomeMemoryRelationRecord {
        OutcomeMemoryRelationRecord {
            outcome_ref: "outcome:test".into(),
            memory_id: "mem_01ARZ3NDEKTSV4RRFFQ69G5V40".parse().unwrap(),
            relation,
            recorded_at: DateTime::parse_from_rfc3339("2026-05-04T12:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            source_event_id: None,
            validation_scope: if with_scope {
                Some("scope:test".into())
            } else {
                None
            },
            validating_principal_id: if with_scope {
                Some("principal:test-operator".into())
            } else {
                None
            },
            evidence_ref: if with_scope {
                Some("aud:test".into())
            } else {
                None
            },
        }
    }

    fn seed_pool_with_memory() -> Pool {
        let pool = rusqlite::Connection::open_in_memory().expect("open in-memory pool");
        crate::migrate::apply_pending(&pool).expect("apply migrations");
        pool.execute(
            "INSERT INTO memories (
                id, memory_type, status, claim, source_episodes_json, source_events_json,
                domains_json, salience_json, confidence, authority, applies_when_json,
                does_not_apply_when_json, created_at, updated_at, validation_epoch
             ) VALUES (
                'mem_01ARZ3NDEKTSV4RRFFQ69G5V40', 'semantic', 'active', 'test memory',
                '[]', '[\"evt_01ARZ3NDEKTSV4RRFFQ69G5V40\"]', '[]',
                '{}', 0.7, 'candidate', '{}', '{}',
                '2026-05-04T12:00:00Z', '2026-05-04T12:00:00Z', 0
             );",
            [],
        )
        .expect("seed memory");
        pool
    }

    #[test]
    fn record_outcome_relation_validated_refuses_when_policy_decision_is_missing() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);

        let err = repo
            .record_outcome_relation(
                &relation_record(OutcomeMemoryRelation::Validated, true),
                None,
            )
            .expect_err("missing policy decision must fail closed");

        let msg = err.to_string();
        assert!(
            msg.contains(OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT),
            "expected stable invariant in error: {msg}"
        );
    }

    #[test]
    fn record_outcome_relation_validated_refuses_when_policy_outcome_denies() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);

        // Compose a Reject final outcome โ€” the on-disk twin of
        // EpistemicError::UtilityCannotUpgradeTruth on the durable path.
        let deny_policy = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    OUTCOME_VALIDATION_SCOPE_RULE_ID,
                    PolicyOutcome::Reject,
                    "test: validation scope rejected (untrusted tier)",
                )
                .unwrap(),
                PolicyContribution::new(
                    OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID,
                    PolicyOutcome::Reject,
                    "test: principal trust tier below class gate",
                )
                .unwrap(),
                PolicyContribution::new(
                    OUTCOME_EVIDENCE_REF_RULE_ID,
                    PolicyOutcome::Reject,
                    "test: evidence_ref does not cite a concrete row",
                )
                .unwrap(),
            ],
            None,
        );

        let err = repo
            .record_outcome_relation(
                &relation_record(OutcomeMemoryRelation::Validated, true),
                Some(&deny_policy),
            )
            .expect_err("deny policy must fail closed");

        let msg = err.to_string();
        assert!(
            msg.contains(OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT),
            "expected stable invariant in error: {msg}"
        );
    }

    #[test]
    fn record_outcome_relation_validated_refuses_missing_scoped_payload() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);

        let err = repo
            .record_outcome_relation(
                &relation_record(OutcomeMemoryRelation::Validated, false),
                Some(&record_outcome_relation_policy_decision_test_allow()),
            )
            .expect_err("missing scope payload must fail closed");

        let msg = err.to_string();
        assert!(
            msg.contains(OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT),
            "expected stable invariant in error: {msg}"
        );
    }

    #[test]
    fn record_outcome_relation_validated_refuses_missing_contributor_rule_ids() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);
        let policy_missing_evidence = compose_policy_outcomes(
            vec![
                PolicyContribution::new(
                    OUTCOME_VALIDATION_SCOPE_RULE_ID,
                    PolicyOutcome::Allow,
                    "test: scope ok",
                )
                .unwrap(),
                PolicyContribution::new(
                    OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID,
                    PolicyOutcome::Allow,
                    "test: tier ok",
                )
                .unwrap(),
                // Deliberately missing OUTCOME_EVIDENCE_REF_RULE_ID.
            ],
            None,
        );

        let err = repo
            .record_outcome_relation(
                &relation_record(OutcomeMemoryRelation::Validated, true),
                Some(&policy_missing_evidence),
            )
            .expect_err("missing contributor must fail closed");

        let msg = err.to_string();
        assert!(
            msg.contains(OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT),
            "expected stable invariant in error: {msg}"
        );
        assert!(
            msg.contains(OUTCOME_EVIDENCE_REF_RULE_ID),
            "error must name the missing contributor: {msg}"
        );
    }

    #[test]
    fn record_outcome_relation_non_validation_relation_admits_without_policy() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);

        // A `Used` edge is utility โ€” it must not require a PolicyDecision and
        // must not advance `validation_epoch`.
        repo.record_outcome_relation(&relation_record(OutcomeMemoryRelation::Used, false), None)
            .expect("non-validation relation admits without policy");

        let epoch = repo
            .validation_epoch_for(&"mem_01ARZ3NDEKTSV4RRFFQ69G5V40".parse().unwrap())
            .expect("read validation_epoch")
            .expect("memory row exists");
        assert_eq!(
            epoch, 0,
            "non-validation relation must not advance validation_epoch"
        );
    }

    #[test]
    fn record_outcome_relation_non_validation_relation_refuses_attached_policy_decision() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);

        // Attaching a policy decision to a non-validation edge is a category
        // error โ€” the relation does not move the validation axis, so the
        // composed envelope is meaningless. Refuse so callers cannot stash an
        // unrelated decision on a `Used` row.
        let err = repo
            .record_outcome_relation(
                &relation_record(OutcomeMemoryRelation::Used, false),
                Some(&record_outcome_relation_policy_decision_test_allow()),
            )
            .expect_err("attached policy on non-validation must fail closed");

        let msg = err.to_string();
        assert!(
            msg.contains(OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT),
            "expected stable invariant in error: {msg}"
        );
    }

    #[test]
    fn record_outcome_relation_validated_advances_validation_epoch_on_happy_path() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);

        repo.record_outcome_relation(
            &relation_record(OutcomeMemoryRelation::Validated, true),
            Some(&record_outcome_relation_policy_decision_test_allow()),
        )
        .expect("happy path admits the row");

        let epoch = repo
            .validation_epoch_for(&"mem_01ARZ3NDEKTSV4RRFFQ69G5V40".parse().unwrap())
            .expect("read validation_epoch")
            .expect("memory row exists");
        assert_eq!(
            epoch, 1,
            "Validated relation must advance validation_epoch from 0 to 1"
        );
    }

    #[test]
    fn validation_epoch_for_returns_none_for_missing_memory() {
        let pool = seed_pool_with_memory();
        let repo = MemoryRepo::new(&pool);
        let missing = repo
            .validation_epoch_for(&"mem_01ARZ3NDEKTSV4RRFFQ69G5V4Z".parse().unwrap())
            .expect("read validation_epoch");
        assert!(missing.is_none());
    }

    #[test]
    fn cross_session_weak_negative_status_thresholds_fire_only_when_unvalidated() {
        // Below threshold โ€” no weak negative.
        assert!(matches!(
            cross_session_weak_negative_status(CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD, 0),
            CrossSessionWeakNegativeStatus::BelowThreshold
        ));
        // Above threshold with no validation โ€” invariant fires.
        let status =
            cross_session_weak_negative_status(CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD + 1, 0);
        assert!(status.is_weak_negative());
        assert_eq!(
            status.invariant(),
            Some(CROSS_SESSION_USE_REPEATED_UNVALIDATED_WEAK_NEGATIVE_INVARIANT)
        );
        // Above threshold with at least one Validated edge โ€” suppressed.
        assert!(matches!(
            cross_session_weak_negative_status(CROSS_SESSION_USE_WEAK_NEGATIVE_THRESHOLD + 1, 1),
            CrossSessionWeakNegativeStatus::SuppressedByValidation
        ));
    }

    #[test]
    fn score_inputs_validation_reads_authoritative_epoch_not_salience_json_blob() {
        // Phase 2.6 D3 closure: this is the unit test the audit explicitly
        // requests โ€” a malicious candidate ships `salience_json.validation =
        // 1.0` at insert. With the new score_inputs glue, retrieval must
        // ignore that field and read validation_epoch instead.
        //
        // We can't import cortex-cli's private score_inputs from here, so we
        // reproduce the validation gate as a local helper to pin the contract.
        fn validation_gate(salience_json_validation: f32, validation_epoch: u32) -> f32 {
            // Mirrors crates/cortex-cli/src/cmd/memory.rs::score_inputs.
            // The blob value is intentionally ignored.
            let _ = salience_json_validation;
            if validation_epoch > 0 {
                1.0
            } else {
                0.0
            }
        }
        assert_eq!(validation_gate(1.0, 0), 0.0);
        assert_eq!(validation_gate(0.0, 1), 1.0);
        assert_eq!(validation_gate(1.0, 1), 1.0);
    }
}

fn require_scoped_validation_payload(relation: &OutcomeMemoryRelationRecord) -> StoreResult<()> {
    if relation
        .validation_scope
        .as_deref()
        .is_none_or(str::is_empty)
    {
        return Err(StoreError::Validation(format!(
            "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: Validated outcome relation requires non-empty validation_scope (ADR 0020 ยง6)",
        )));
    }
    if relation
        .validating_principal_id
        .as_deref()
        .is_none_or(str::is_empty)
    {
        return Err(StoreError::Validation(format!(
            "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: Validated outcome relation requires non-empty validating_principal_id (ADR 0020 ยง6)",
        )));
    }
    if relation.evidence_ref.as_deref().is_none_or(str::is_empty) {
        return Err(StoreError::Validation(format!(
            "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: Validated outcome relation requires non-empty evidence_ref (ADR 0020 ยง6)",
        )));
    }
    Ok(())
}

fn require_no_scoped_validation_payload(relation: &OutcomeMemoryRelationRecord) -> StoreResult<()> {
    if relation.validation_scope.is_some()
        || relation.validating_principal_id.is_some()
        || relation.evidence_ref.is_some()
    {
        return Err(StoreError::Validation(format!(
            "{OUTCOME_UTILITY_TO_TRUTH_PROMOTION_UNAUTHORIZED_INVARIANT}: non-validation outcome relation must leave validation_scope/validating_principal_id/evidence_ref unset",
        )));
    }
    Ok(())
}

fn require_attestation_not_break_glassed(
    policy: &PolicyDecision,
    rule_id: &str,
    surface: &str,
) -> StoreResult<()> {
    // ADR 0026 ยง4: BreakGlass MUST NOT substitute for a required current-use
    // attestation contributor. The named contributor must itself have voted
    // either `Allow` (the surface has a bound operator key whose timeline
    // revalidation passed) OR `Warn` (the surface has no bound operator
    // key โ€” the *honest no-attestation floor* documented at
    // `crates/cortex-cli/src/cmd/memory.rs::ACCEPT_OPERATOR_TEMPORAL_AUTHORITY_WARN_NO_ATTESTATION_INVARIANT`).
    // `Warn` is NOT a BreakGlass substitution: BreakGlass overrides a
    // failing attestation; the honest floor explicitly disclaims one. The
    // ยง4 wall holds because:
    //
    //   - `Allow`: real attestation passed.
    //   - `Warn`:  no attestation claim was made; the surface stays
    //              operational at the honest floor without laundering
    //              authority. Downstream consumers see a `Warn` final
    //              outcome (or `Quarantine`/`Reject` if another
    //              contributor failed) rather than a misleading `Allow`.
    //   - Anything else (`Quarantine` / `Reject` / `BreakGlass`):
    //              forbidden โ€” the ยง4 substitution rule applies.
    let attestation = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| contribution.rule_id.as_str() == rule_id)
        .ok_or_else(|| {
            StoreError::Validation(format!(
                "{surface} preflight: required attestation contributor `{rule_id}` is absent from the policy decision",
            ))
        })?;
    match attestation.outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn => Ok(()),
        other => Err(StoreError::Validation(format!(
            "{surface} preflight: attestation contributor `{rule_id}` returned {other:?}; ADR 0026 ยง4 forbids BreakGlass substituting for attestation",
        ))),
    }
}

/// ADR 0017 invariants for a newly inserted candidate row.
///
/// Cross-session salience is earned: every advancement of
/// `cross_session_use_count`, `last_cross_session_use_at`, or
/// `last_validation_at` must come from a `record_session_use` /
/// `record_outcome_relation` write after the candidate is admitted, never from
/// minting metadata at insert time. `validation_epoch` similarly only advances
/// through `cortex memory bless` or an attested validation. `first_used_at`
/// MUST be `None` because the candidate has not yet been used.
///
/// A non-zero or otherwise pre-populated salience record on insert would let an
/// attacker โ€” or a buggy ingest path โ€” back-date legitimacy. This validator
/// fails closed in that shape.
pub fn validate_candidate_cross_session_salience(
    salience: &CrossSessionSalience,
) -> StoreResult<()> {
    if salience.cross_session_use_count != 0 {
        return Err(StoreError::Validation(format!(
            "memory.v2.cross_session_salience preflight: candidate cross_session_use_count must be 0 at insert, observed {}",
            salience.cross_session_use_count,
        )));
    }
    if salience.first_used_at.is_some() {
        return Err(StoreError::Validation(
            "memory.v2.cross_session_salience preflight: candidate first_used_at must be unset at insert".into(),
        ));
    }
    if salience.last_cross_session_use_at.is_some() {
        return Err(StoreError::Validation(
            "memory.v2.cross_session_salience preflight: candidate last_cross_session_use_at must be unset at insert".into(),
        ));
    }
    if salience.last_validation_at.is_some() {
        return Err(StoreError::Validation(
            "memory.v2.cross_session_salience preflight: candidate last_validation_at must be unset at insert".into(),
        ));
    }
    if salience.validation_epoch != 0 {
        return Err(StoreError::Validation(format!(
            "memory.v2.cross_session_salience preflight: candidate validation_epoch must be 0 at insert, observed {}",
            salience.validation_epoch,
        )));
    }
    if salience.blessed_until.is_some() {
        return Err(StoreError::Validation(
            "memory.v2.cross_session_salience preflight: candidate blessed_until must be unset at insert (bless is an operator-attested post-admit action)".into(),
        ));
    }
    Ok(())
}

/// Build the [`V2_SUMMARY_SPAN_PROOF_RULE_ID`] contributor for an
/// `insert_candidate_with_v2_fields` composition from a memory candidate and
/// its proposed summary spans.
///
/// The contributor's outcome mirrors ADR 0015's structural validator:
///
/// - Spans satisfy [`validate_summary_spans`] (or the row is non-summary with
///   no spans supplied) -> [`PolicyOutcome::Allow`]
/// - Validation fails (range/UTF-8/coverage/authority mismatch) ->
///   [`PolicyOutcome::Reject`]
///
/// `authority_fold` recomputes the expected `max_source_authority` for one
/// span from its `derived_from_event_ids`. Production callers fold the resolved
/// `EventSource` per ADR 0015's three-point lattice
/// (`User > Agent > Derived`); tests typically pass `|_| SourceAuthority::Derived`.
pub fn summary_span_proof_contribution<F>(
    memory: &MemoryCandidate,
    summary_spans: &[SummarySpan],
    authority_fold: F,
) -> PolicyContribution
where
    F: FnMut(&[EventId]) -> SourceAuthority,
{
    let validation = if memory.memory_type.contains("summary") || !summary_spans.is_empty() {
        validate_summary_spans(&memory.claim, summary_spans, authority_fold)
    } else {
        Ok(())
    };

    let (outcome, reason): (PolicyOutcome, String) = match validation {
        Ok(()) => (
            PolicyOutcome::Allow,
            "summary spans satisfy ADR 0015 structural invariants".to_string(),
        ),
        Err(err) => (
            PolicyOutcome::Reject,
            format!(
                "summary spans violate ADR 0015 invariant `{}`",
                err.invariant()
            ),
        ),
    };

    PolicyContribution::new(V2_SUMMARY_SPAN_PROOF_RULE_ID, outcome, reason)
        .expect("v2 summary span proof contribution shape is statically valid")
}

/// Build the [`V2_CROSS_SESSION_SALIENCE_RULE_ID`] contributor for an
/// `insert_candidate_with_v2_fields` composition from the proposed salience
/// record.
///
/// The contributor's outcome mirrors
/// [`validate_candidate_cross_session_salience`]:
///
/// - Salience matches the ADR 0017 candidate-row invariants ->
///   [`PolicyOutcome::Allow`]
/// - Any field is pre-populated (back-dated legitimacy) ->
///   [`PolicyOutcome::Reject`]
#[must_use]
pub fn cross_session_salience_contribution(salience: &CrossSessionSalience) -> PolicyContribution {
    let (outcome, reason): (PolicyOutcome, String) =
        match validate_candidate_cross_session_salience(salience) {
            Ok(()) => (
                PolicyOutcome::Allow,
                "candidate salience matches the ADR 0017 insert-time invariants".to_string(),
            ),
            Err(err) => (PolicyOutcome::Reject, err.to_string()),
        };

    PolicyContribution::new(V2_CROSS_SESSION_SALIENCE_RULE_ID, outcome, reason)
        .expect("v2 cross-session salience contribution shape is statically valid")
}

/// Build a [`PolicyDecision`] that satisfies
/// [`MemoryRepo::accept_candidate`] for the happy path. Intended for tests and
/// fixtures only.
///
/// Production callers MUST compose [`ACCEPT_PROOF_CLOSURE_RULE_ID`],
/// [`ACCEPT_OPEN_CONTRADICTION_RULE_ID`], [`ACCEPT_SEMANTIC_TRUST_RULE_ID`],
/// and [`ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID`] from real proof closure,
/// resolver, admission, and ADR 0023 temporal authority evidence. This helper
/// is exposed unconditionally because integration test crates outside
/// `cortex-store` need the same fixture shape; the `_test_allow` suffix is the
/// contract that documents intent.
#[must_use]
pub fn accept_candidate_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                ACCEPT_PROOF_CLOSURE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: supporting-memory proof closure verified",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                ACCEPT_OPEN_CONTRADICTION_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: no open durable contradiction on candidate slot",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                ACCEPT_SEMANTIC_TRUST_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: semantic trust posture satisfied",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: operator temporal authority is currently valid",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build the [`ACCEPT_PROOF_CLOSURE_RULE_ID`] contributor for an
/// `accept_candidate` composition from a real proof-closure report.
///
/// The contributor's outcome mirrors [`ProofClosureReport::policy_decision`]:
///
/// - `FullChainVerified` -> [`PolicyOutcome::Allow`]
/// - `Partial` -> [`PolicyOutcome::Quarantine`]
/// - `Broken` -> [`PolicyOutcome::Reject`]
#[must_use]
pub fn accept_proof_closure_contribution(report: &ProofClosureReport) -> PolicyContribution {
    let (outcome, reason): (PolicyOutcome, &'static str) = match report.state() {
        ProofState::FullChainVerified => (
            PolicyOutcome::Allow,
            "supporting-memory proof closure is fully verified",
        ),
        ProofState::Partial => (
            PolicyOutcome::Quarantine,
            "supporting-memory proof closure is partial; promotion fails closed",
        ),
        ProofState::Broken => (
            PolicyOutcome::Reject,
            "supporting-memory proof closure is broken; promotion fails closed",
        ),
    };
    PolicyContribution::new(ACCEPT_PROOF_CLOSURE_RULE_ID, outcome, reason)
        .expect("static proof closure contribution shape is valid")
}

/// Build the [`ACCEPT_OPEN_CONTRADICTION_RULE_ID`] contributor for an
/// `accept_candidate` composition.
///
/// Pass the number of open durable contradictions (status `unresolved` or
/// `interpreted`) that touch the candidate's claim slot. The contributor maps:
///
/// - `0` open contradictions -> [`PolicyOutcome::Allow`]
/// - any positive count -> [`PolicyOutcome::Reject`]
///
/// ADR 0024 ยง3 says a `ConflictUnresolved` slot MUST NOT silently allow
/// default promotion. Callers compute the count from a
/// [`super::ContradictionRepo`] query.
#[must_use]
pub fn accept_open_contradiction_contribution(open_contradictions: usize) -> PolicyContribution {
    let (outcome, reason): (PolicyOutcome, String) = if open_contradictions == 0 {
        (
            PolicyOutcome::Allow,
            "no open durable contradiction touches the candidate slot".to_string(),
        )
    } else {
        (
            PolicyOutcome::Reject,
            format!(
                "{open_contradictions} open durable contradiction(s) touch the candidate slot; ADR 0024 forbids silent promotion"
            ),
        )
    };
    PolicyContribution::new(ACCEPT_OPEN_CONTRADICTION_RULE_ID, outcome, reason)
        .expect("static open contradiction contribution shape is valid")
}

/// Build the [`ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID`] contributor for an
/// `accept_candidate` composition from a real temporal-authority report.
///
/// The contributor's outcome mirrors the temporal authority's own
/// `policy_decision` outcome:
///
/// - `valid_now` -> [`PolicyOutcome::Allow`]
/// - `valid_at_event_time && !valid_now` -> [`PolicyOutcome::Quarantine`]
///   (historical signature, current use blocked)
/// - otherwise -> [`PolicyOutcome::Reject`]
///
/// Per ADR 0026 ยง4 [`MemoryRepo::accept_candidate`] requires this contributor
/// to be `Allow`: break-glass MUST NOT substitute for current-use temporal
/// authority at the durable acceptance surface.
#[must_use]
pub fn accept_operator_temporal_use_contribution(
    report: &TemporalAuthorityReport,
) -> PolicyContribution {
    let (outcome, reason): (PolicyOutcome, &'static str) = if report.valid_now {
        (
            PolicyOutcome::Allow,
            "operator temporal authority is currently valid",
        )
    } else if report.valid_at_event_time {
        (
            PolicyOutcome::Quarantine,
            "operator temporal authority is historical only; current use blocked",
        )
    } else {
        (
            PolicyOutcome::Reject,
            "operator temporal authority was invalid at event time",
        )
    };
    PolicyContribution::new(ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID, outcome, reason)
        .expect("static operator temporal use contribution shape is valid")
}

/// Build a [`PolicyDecision`] that satisfies
/// [`MemoryRepo::record_outcome_relation`] for a `Validated` write on the
/// happy path. Intended for tests and fixtures only.
///
/// Production callers MUST compose
/// [`OUTCOME_VALIDATION_SCOPE_RULE_ID`],
/// [`OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID`], and
/// [`OUTCOME_EVIDENCE_REF_RULE_ID`] from real ADR 0020 ยง5/ยง6 evidence โ€” the
/// validating principal's current trust tier, the scope under which the
/// validation applies, and a concrete evidence reference (audit row, event,
/// attestation digest). This helper is exposed unconditionally because tests
/// outside `cortex-store` need the same fixture shape.
#[must_use]
pub fn record_outcome_relation_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                OUTCOME_VALIDATION_SCOPE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: validation scope declared and recorded on the relation row",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                OUTCOME_VALIDATING_PRINCIPAL_TIER_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: validating principal trust tier meets ADR 0020 ยง5 gate",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                OUTCOME_EVIDENCE_REF_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: evidence_ref cites concrete attestation/audit row",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a [`PolicyDecision`] that satisfies
/// [`MemoryRepo::insert_candidate_with_v2_fields`] for the happy path.
/// Intended for tests and fixtures only.
///
/// Production callers MUST fold honest
/// [`summary_span_proof_contribution`] and
/// [`cross_session_salience_contribution`] outcomes into the composition
/// instead of these `Allow` placeholders.
#[must_use]
pub fn insert_candidate_v2_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                V2_SUMMARY_SPAN_PROOF_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: summary spans validated",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                V2_CROSS_SESSION_SALIENCE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: candidate salience matches insert-time invariants",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

fn ensure_memory_exists(tx: &rusqlite::Transaction<'_>, id: &MemoryId) -> StoreResult<()> {
    let exists = tx
        .query_row(
            "SELECT 1 FROM memories WHERE id = ?1;",
            params![id.to_string()],
            |_| Ok(()),
        )
        .optional()?
        .is_some();
    if !exists {
        return Err(StoreError::Validation(format!("memory {id} not found")));
    }
    Ok(())
}

fn reconcile_memory_session_salience(
    tx: &rusqlite::Transaction<'_>,
    id: &MemoryId,
) -> StoreResult<()> {
    tx.execute(
        "UPDATE memories
         SET cross_session_use_count = (
                SELECT COALESCE(SUM(use_count), 0) FROM memory_session_uses WHERE memory_id = ?1
             ),
             first_used_at = (
                SELECT MIN(first_used_at) FROM memory_session_uses WHERE memory_id = ?1
             ),
             last_cross_session_use_at = (
                SELECT MAX(last_used_at) FROM memory_session_uses WHERE memory_id = ?1
             ),
             validation_epoch = COALESCE(validation_epoch, 0)
         WHERE id = ?1;",
        params![id.to_string()],
    )?;
    Ok(())
}

#[derive(Debug)]
struct MemoryRow {
    id: String,
    memory_type: String,
    status: String,
    claim: String,
    source_episodes_json: String,
    source_events_json: String,
    domains_json: String,
    salience_json: String,
    confidence: f64,
    authority: String,
    applies_when_json: String,
    does_not_apply_when_json: String,
    created_at: String,
    updated_at: String,
}

fn memory_row(row: &Row<'_>) -> rusqlite::Result<MemoryRow> {
    Ok(MemoryRow {
        id: row.get(0)?,
        memory_type: row.get(1)?,
        status: row.get(2)?,
        claim: row.get(3)?,
        source_episodes_json: row.get(4)?,
        source_events_json: row.get(5)?,
        domains_json: row.get(6)?,
        salience_json: row.get(7)?,
        confidence: row.get(8)?,
        authority: row.get(9)?,
        applies_when_json: row.get(10)?,
        does_not_apply_when_json: row.get(11)?,
        created_at: row.get(12)?,
        updated_at: row.get(13)?,
    })
}

impl TryFrom<MemoryRow> for MemoryRecord {
    type Error = StoreError;

    fn try_from(row: MemoryRow) -> StoreResult<Self> {
        Ok(Self {
            id: row.id.parse()?,
            memory_type: row.memory_type,
            status: row.status,
            claim: row.claim,
            source_episodes_json: serde_json::from_str(&row.source_episodes_json)?,
            source_events_json: serde_json::from_str(&row.source_events_json)?,
            domains_json: serde_json::from_str(&row.domains_json)?,
            salience_json: serde_json::from_str(&row.salience_json)?,
            confidence: row.confidence,
            authority: row.authority,
            applies_when_json: serde_json::from_str(&row.applies_when_json)?,
            does_not_apply_when_json: serde_json::from_str(&row.does_not_apply_when_json)?,
            created_at: DateTime::parse_from_rfc3339(&row.created_at)?.with_timezone(&Utc),
            updated_at: DateTime::parse_from_rfc3339(&row.updated_at)?.with_timezone(&Utc),
        })
    }
}