aidaemon-memory 0.25.0

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

const FACT_SEMANTIC_MIN_SCORE: f32 = 0.3;
const FACT_LEXICAL_MIN_SCORE: f32 = 0.3;
const FACT_LEXICAL_MAX_SCORE: f32 = 0.55;
const FACT_FRESHNESS_MAX_BOOST: f32 = 0.15;
const FACT_FRESHNESS_DECAY_HOURS: f32 = 168.0; // 7 days

/// Conservative fallback for passive prompt recall when embeddings are
/// unavailable. Returning recent facts regardless of relevance leaks unrelated
/// context into the model; an empty result is safer because explicit memory
/// search remains available to the agent.
fn lexical_relevant_facts(facts: &[Fact], query: &str, max: usize) -> Vec<Fact> {
    let query_lower = query.to_lowercase();
    let tokens = query_tokens(&query_lower);
    let mut scored = facts
        .iter()
        .filter_map(|fact| {
            let score = lexical_fallback_score(&query_lower, &tokens, fact);
            (score > FACT_LEXICAL_MIN_SCORE).then_some((fact, score))
        })
        .collect::<Vec<_>>();
    scored.sort_by(|left, right| {
        right
            .1
            .partial_cmp(&left.1)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| right.0.updated_at.cmp(&left.0.updated_at))
    });
    scored
        .into_iter()
        .take(max)
        .map(|(fact, _)| fact.clone())
        .collect()
}

/// Build a key-only embedding text for semantic dedup comparison.
///
/// Focuses on category + readable key (no value) so that dedup detects
/// keys referring to the same concept regardless of their values.
fn build_dedup_key_text(category: &str, key: &str) -> String {
    let readable_key = key.replace(['_', '-'], " ");
    format!(
        "The user's {} {}. {} attribute: {}",
        category, readable_key, category, readable_key
    )
}

fn hybrid_fact_score(
    fact: &Fact,
    semantic: f32,
    lexical: f32,
    graph_match: bool,
    freshness: f32,
) -> f32 {
    crate::HybridWeights::default().fuse(&crate::Signals {
        semantic,
        lexical,
        graph: if graph_match { 1.0 } else { 0.0 },
        freshness: (freshness / FACT_FRESHNESS_MAX_BOOST).clamp(0.0, 1.0),
        confidence: if fact.source == "consolidation" {
            0.7
        } else {
            1.0
        },
        provenance: if fact.source_excerpt.is_some() {
            1.0
        } else {
            0.3
        },
    })
}

/// Build a natural-language embedding text for a fact.
///
/// Instead of `[project] inter_service: gRPC`, this produces something like:
/// `"Project: inter-service communication technology is gRPC"`
///
/// Natural language embeds much better against natural language queries
/// like "What tech stack does my project use?".
pub fn build_fact_embedding_text(category: &str, key: &str, value: &str) -> String {
    // Convert underscore/hyphen keys to readable form
    let readable_key = key.replace(['_', '-'], " ");

    // Build a natural-language sentence
    format!(
        "{} - {}: {}. The user's {} is {}.",
        category, readable_key, value, readable_key, value
    )
}

/// Whether two canonical fact keys are structurally distinct concepts that
/// must never be merged, whatever their embeddings say.
///
/// Merge-safe: zero token overlap (possible synonyms), pure reordering
/// ("company_previous" / "previous_company"), and a subset whose extra tokens
/// are all known qualifiers ("editor" / "preferred_editor"). Distinct: two
/// single-token keys (short keys embed too alike: "age" / "name"), partial
/// overlap ("dog_name_old" / "dog_name_new"), and a subset whose extra token
/// is likely an entity ("birthday" / "carlos_birthday", "age" / "child_age").
pub(super) fn keys_name_distinct_concepts(
    new_tokens: &std::collections::HashSet<&str>,
    existing_tokens: &std::collections::HashSet<&str>,
) -> bool {
    const SAFE_MODIFIERS: &[&str] = &[
        "preferred",
        "favorite",
        "fav",
        "default",
        "primary",
        "current",
        "previous",
        "old",
        "new",
        "last",
        "first",
        "main",
        "secondary",
        "alternate",
        "alt",
        "other",
        "work",
        "home",
        "personal",
        "daily",
        "weekly",
        "morning",
        "evening",
        "night",
    ];
    let shared = new_tokens.intersection(existing_tokens).count();
    let new_count = new_tokens.len();
    let existing_count = existing_tokens.len();
    if new_count <= 1 && existing_count <= 1 {
        return true;
    }
    let is_subset = new_tokens.is_subset(existing_tokens) || existing_tokens.is_subset(new_tokens);
    if shared > 0 && !is_subset {
        return true;
    }
    if is_subset && new_count != existing_count {
        let (larger, smaller) = if new_count > existing_count {
            (new_tokens, existing_tokens)
        } else {
            (existing_tokens, new_tokens)
        };
        return !larger
            .difference(smaller)
            .all(|token| SAFE_MODIFIERS.contains(token));
    }
    false
}

/// Whether two keys name one attribute (`editor` / `preferred_editor`,
/// `oauth_expiry` / `oauth_expiration`), as opposed to two attributes that
/// share a word (`dog_name_old` / `dog_name_new`, `age` / `child_age`).
pub fn keys_name_same_attribute(a: &str, b: &str) -> bool {
    let (a, b) = (canonicalize_fact_key(a), canonicalize_fact_key(b));
    a == b || {
        let a_tokens = a.split('_').filter(|t| !t.is_empty()).collect();
        let b_tokens = b.split('_').filter(|t| !t.is_empty()).collect();
        !keys_name_distinct_concepts(&a_tokens, &b_tokens)
    }
}

/// Sources that record the owner's own words. Background extractors can
/// never overwrite these, only restate or add beside them.
pub fn is_owner_authored_fact_source(source: &str) -> bool {
    matches!(source, "agent" | "user_stated" | "owner" | "owner-stated")
}

/// Source of a per-turn fact the owner asserted, with a verbatim quote from
/// their own message checked against it. Not owner-authored (the quote
/// proves the words, not that the value follows from them, nor who wrote
/// pasted text), but above anything a background extractor inferred.
pub const OWNER_QUOTED_SOURCE: &str = "owner_quoted";

/// How close a fact's source is to the owner's own words: 2 stated
/// explicitly, 1 quoted from the owner's message, 0 inferred. A write may
/// replace a different value only at equal or higher rank, and a restatement
/// never lowers a row's rank.
pub fn fact_source_rank(source: &str) -> u8 {
    if is_owner_authored_fact_source(source) {
        2
    } else if source == OWNER_QUOTED_SOURCE {
        1
    } else {
        0
    }
}

/// Full-fact (key + value) embedding similarity at which an automated write is
/// a restatement of an active fact rather than new knowledge. Measured on the
/// live store: pairs at or above this are paraphrased keys for one value
/// ("blog_deploy_stack" / "blog_deployment_stack", "tweet_account" /
/// "twitter_account"); below it, distinct values start to appear.
pub(crate) const FACT_RESTATEMENT_MIN_SIMILARITY: f32 = 0.93;

/// Categories whose keys name a person or their attributes, where a key that
/// differs by an entity token must stay separate even at high similarity.
pub fn fact_category_is_personal(category: &str) -> bool {
    matches!(
        category.trim().to_ascii_lowercase().as_str(),
        "user" | "people" | "relationship" | "relationships" | "family"
    )
}

fn value_tokens(value: &str) -> std::collections::HashSet<String> {
    crate::text::words(value).collect()
}

/// Values carry the same claim: identical numbers (versions, dates, counts,
/// ids differ in one digit and the embedding cannot see it) and at least half
/// of their words shared.
fn values_make_the_same_claim(a: &str, b: &str) -> bool {
    let (a, b) = (value_tokens(a), value_tokens(b));
    if a.is_empty() || b.is_empty() {
        return false;
    }
    let numbers = |tokens: &std::collections::HashSet<String>| {
        tokens
            .iter()
            .filter(|token| token.chars().any(|c| c.is_ascii_digit()))
            .cloned()
            .collect::<std::collections::BTreeSet<_>>()
    };
    if numbers(&a) != numbers(&b) {
        return false;
    }
    let shared = a.intersection(&b).count();
    shared * 2 >= a.union(&b).count()
}

/// Whether two active facts in one category are the same knowledge.
pub fn facts_are_restatements(
    category: &str,
    a: (&str, &str),
    b: (&str, &str),
    similarity: f32,
) -> bool {
    similarity >= FACT_RESTATEMENT_MIN_SIMILARITY && facts_make_the_same_claim(category, a, b)
}

/// The similarity-independent half of [`facts_are_restatements`]: similar
/// text still has to carry one claim about one thing.
pub(crate) fn facts_make_the_same_claim(
    category: &str,
    (key_a, value_a): (&str, &str),
    (key_b, value_b): (&str, &str),
) -> bool {
    if !values_make_the_same_claim(value_a, value_b) {
        return false;
    }
    if !fact_category_is_personal(category) {
        return true;
    }
    let a = canonicalize_fact_key(key_a);
    let b = canonicalize_fact_key(key_b);
    let a_tokens = a.split('_').filter(|t| !t.is_empty()).collect();
    let b_tokens = b.split('_').filter(|t| !t.is_empty()).collect();
    a == b || !keys_name_distinct_concepts(&a_tokens, &b_tokens)
}

pub(super) use crate::text::{canonical_personal_key, canonicalize_fact_key};

fn prefer_canonical_facts(
    mut canonical: Vec<Fact>,
    legacy: Vec<Fact>,
    query: &str,
    max: usize,
) -> Vec<Fact> {
    let query_lower = query.to_lowercase();
    let query_words = query_tokens(&query_lower);
    if !query.trim().is_empty() {
        canonical.retain(|fact| {
            lexical_fallback_score(&query_lower, &query_words, fact) > 0.0
                || fact.value.to_lowercase().contains(query_lower.trim())
        });
    }

    let canonical_owner_keys: std::collections::HashSet<String> = canonical
        .iter()
        .filter(|fact| fact.category == "user")
        .map(|fact| canonical_personal_key(&fact.key))
        .collect();
    let has_relationships = canonical
        .iter()
        .any(|fact| fact.category == "relationships");
    canonical.extend(legacy.into_iter().filter(|fact| {
        !(fact.category == "user"
            && canonical_owner_keys.contains(&canonical_personal_key(&fact.key))
            || has_relationships
                && matches!(
                    canonicalize_fact_key(&fact.key).as_str(),
                    "daughter"
                        | "son"
                        | "child"
                        | "mother"
                        | "father"
                        | "parent"
                        | "daughter_name"
                        | "son_name"
                        | "child_name"
                        | "mother_name"
                        | "father_name"
                ))
    }));
    // Preserve semantic/graph ranking within each group, but always surface an
    // exact structured-key hit before loosely related embedding matches. This
    // is critical for short profile questions such as "my dad" (`dad_name`) or
    // "my mom" (`mom_name`), where generic identity facts otherwise outrank the
    // answer-bearing record.
    canonical.sort_by_key(|fact| {
        let key = fact.key.to_ascii_lowercase();
        std::cmp::Reverse(
            query_words
                .iter()
                .filter(|word| contains_word(&key, word))
                .count(),
        )
    });
    canonical.truncate(max);
    canonical
}

fn fact_freshness_boost(now: DateTime<Utc>, updated_at: DateTime<Utc>) -> f32 {
    let age_hours = (now - updated_at).num_hours().max(0) as f32;
    FACT_FRESHNESS_MAX_BOOST * (1.0 - (age_hours / FACT_FRESHNESS_DECAY_HOURS).min(1.0))
}

pub(super) use crate::scoring::is_stopword;

fn query_tokens(query_lower: &str) -> Vec<&str> {
    query_lower
        .split(|c: char| !c.is_alphanumeric())
        .filter(|t| t.len() >= 3)
        .filter(|t| !is_stopword(t))
        .collect()
}

fn contains_word(haystack_lower: &str, needle: &str) -> bool {
    if needle.is_empty() {
        return false;
    }
    haystack_lower
        .split(|c: char| !c.is_alphanumeric())
        .any(|w| w == needle)
}

fn lexical_fallback_score(query_lower: &str, tokens: &[&str], fact: &Fact) -> f32 {
    let q = query_lower.trim();
    if q.is_empty() || tokens.is_empty() {
        return 0.0;
    }

    let key = fact.key.to_lowercase();
    let value = fact.value.to_lowercase();
    let category = fact.category.to_lowercase();

    let q_is_token = q.chars().all(|c| c.is_alphanumeric());
    let value_has_q = q_is_token && contains_word(&value, q);

    // Keys/categories are structured; substring matching is fine.
    // Values are natural language; prefer word-boundary matching to avoid
    // false positives like "dog" matching "dodger".
    if key.contains(q) || category.contains(q) || value_has_q {
        return FACT_LEXICAL_MAX_SCORE;
    }

    // If any query token matches the structured key exactly (word boundary),
    // treat as high-confidence lexical relevance.
    if tokens.iter().any(|t| contains_word(&key, t)) {
        return FACT_LEXICAL_MAX_SCORE;
    }

    let mut matched = 0usize;
    for t in tokens {
        if key.contains(t) || category.contains(t) || contains_word(&value, t) {
            matched += 1;
        }
    }
    (matched as f32 / tokens.len() as f32) * FACT_LEXICAL_MAX_SCORE
}

impl SqliteMemory {
    /// Cosine scores for the facts in `ids` that `indexed` has no score for,
    /// from each fact's own stored vector. Usually none: every fact with a
    /// claim is in the embedding index. Read in chunks, so a recall never
    /// loads every fact's blob.
    async fn unindexed_fact_scores(
        &self,
        query_vec: &[f32],
        ids: impl Iterator<Item = i64>,
        indexed: &std::collections::HashMap<i64, f32>,
    ) -> std::collections::HashMap<i64, f32> {
        let missing: Vec<i64> = ids.filter(|id| !indexed.contains_key(id)).collect();
        let mut scores = std::collections::HashMap::new();
        for chunk in missing.chunks(500) {
            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
                "SELECT id, embedding FROM facts WHERE embedding IS NOT NULL AND id IN (",
            );
            let mut separated = builder.separated(", ");
            for id in chunk {
                separated.push_bind(*id);
            }
            separated.push_unseparated(")");
            let rows = match builder.build().fetch_all(&self.pool).await {
                Ok(rows) => rows,
                Err(error) => {
                    tracing::warn!(%error, "could not read fact vectors for recall");
                    return scores;
                }
            };
            for row in rows {
                let blob: Vec<u8> = row.get("embedding");
                if let Ok(vector) = self.embedding_service.decode(&blob) {
                    scores.insert(row.get("id"), cosine_similarity(query_vec, &vector));
                }
            }
        }
        scores
    }

    /// The active fact a key with no active row was folded into, following
    /// later folds of that fact. None for a key that is active, never
    /// existed, or was retired any other way.
    async fn folded_survivor(
        &self,
        category: &str,
        key: &str,
    ) -> anyhow::Result<Option<(String, String)>> {
        let canonical = canonicalize_fact_key(key);
        let active: Option<i64> = sqlx::query_scalar(
            "SELECT id FROM facts WHERE category = ? AND key IN (?, ?) AND superseded_at IS NULL",
        )
        .bind(category)
        .bind(key)
        .bind(&canonical)
        .fetch_optional(&self.pool)
        .await?;
        if active.is_some() {
            return Ok(None);
        }
        let mut next: Option<i64> = sqlx::query_scalar(
            "SELECT folded_into FROM facts
             WHERE category = ? AND key IN (?, ?) AND superseded_reason = 'folded'
               AND folded_into IS NOT NULL
             ORDER BY superseded_at DESC LIMIT 1",
        )
        .bind(category)
        .bind(key)
        .bind(&canonical)
        .fetch_optional(&self.pool)
        .await?
        .flatten();
        // A survivor folded later points on; a short chain, never a loop.
        for _ in 0..8 {
            let Some(id) = next else {
                return Ok(None);
            };
            let row: Option<FoldLink> = sqlx::query_as(
                "SELECT category, key, superseded_at, folded_into, superseded_reason
                     FROM facts WHERE id = ?",
            )
            .bind(id)
            .fetch_optional(&self.pool)
            .await?;
            match row {
                Some((category, key, None, _, _)) => return Ok(Some((category, key))),
                Some((_, _, Some(_), Some(into), Some(reason)))
                    if reason == SupersededReason::Folded.as_str() =>
                {
                    next = Some(into)
                }
                _ => return Ok(None),
            }
        }
        Ok(None)
    }

    /// Every active fact with a vector, as the fold planner reads it.
    pub async fn fold_candidates(&self) -> anyhow::Result<Vec<super::fact_folds::FoldCandidate>> {
        let rows = sqlx::query(
            "SELECT id, category, key, value, source, COALESCE(recall_count, 0) AS recall_count,
                    COALESCE(privacy, 'global') AS privacy, channel_id, embedding
             FROM facts
             WHERE superseded_at IS NULL AND embedding IS NOT NULL
             ORDER BY id ASC",
        )
        .fetch_all(&self.pool)
        .await?;
        Ok(rows
            .into_iter()
            .filter_map(|row| {
                let blob: Vec<u8> = row.get("embedding");
                let vector = self.embedding_service.decode(&blob).ok()?;
                let category: String = row.get("category");
                let source: String = row.get("source");
                Some(super::fact_folds::FoldCandidate {
                    id: row.get("id"),
                    pinned: crate::full::recall::IDENTITY_CATEGORIES
                        .contains(&category.trim().to_ascii_lowercase().as_str()),
                    category,
                    key: row.get("key"),
                    value: row.get("value"),
                    source_rank: fact_source_rank(&source),
                    recall_count: row.get("recall_count"),
                    privacy: row.get("privacy"),
                    channel_id: row.get("channel_id"),
                    vector,
                })
            })
            .collect())
    }

    /// Retired rows, with no active row left for their key, that cover an
    /// automated write of one of `keys = value` in `category`
    /// ([`retirement_covers`]).
    /// Whether a fact under one of `keys` (any category) took a value other
    /// than `value` after `seen`: evidence from `seen` is older than it.
    async fn corrected_since(
        &self,
        keys: &[&str],
        value: &str,
        seen: DateTime<Utc>,
    ) -> anyhow::Result<bool> {
        let keys: Vec<&str> = keys
            .iter()
            .map(|key| key.trim())
            .filter(|key| !key.is_empty())
            .collect();
        if keys.is_empty() {
            return Ok(false);
        }
        // At most three spellings of one key; repeat the first to fill.
        let key = |i: usize| keys.get(i).copied().unwrap_or(keys[0]);
        let rows: Vec<(String, String)> =
            sqlx::query_as("SELECT value, created_at FROM facts WHERE key IN (?, ?, ?)")
                .bind(key(0))
                .bind(key(1))
                .bind(key(2))
                .fetch_all(&self.pool)
                .await?;
        let new_value = crate::text::normalize_fact_value(value);
        Ok(rows.into_iter().any(|(other, created_at)| {
            crate::types::parse_ts(&created_at).is_some_and(|at| at > seen)
                && crate::text::normalize_fact_value(&other) != new_value
        }))
    }

    async fn retired_knowledge(
        &self,
        category: &str,
        keys: &[&str],
        value: &str,
    ) -> anyhow::Result<Vec<RetiredKnowledge>> {
        let rows: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
            "SELECT f.category, f.key, f.value, f.superseded_at, f.superseded_reason
             FROM facts f
             WHERE f.superseded_at IS NOT NULL
               AND NOT EXISTS (SELECT 1 FROM facts a WHERE a.superseded_at IS NULL
                                AND a.category = f.category AND a.key = f.key)
             ORDER BY f.superseded_at DESC",
        )
        .fetch_all(&self.pool)
        .await?;
        Ok(rows
            .into_iter()
            .filter(
                |(retired_category, retired_key, retired_value, _, reason)| {
                    retirement_covers(
                        (category, keys, value),
                        (retired_category, retired_key, retired_value),
                        reason.as_deref(),
                    )
                },
            )
            .map(|(category, key, _, retired_at, _)| RetiredKnowledge {
                category,
                key,
                // An unreadable time still retires: no evidence is newer.
                retired_at: crate::types::parse_ts(&retired_at).unwrap_or(DateTime::<Utc>::MAX_UTC),
            })
            .collect())
    }

    /// Ends the active copies of a fact the owner just changed or forgot:
    /// facts in any category that hold the same value under a key whose words
    /// contain, or are contained in, those of `key` (`favorite_tea` beside `test_favorite_tea`,
    /// `user/marker` beside `personal/marker`). Background extraction stores
    /// such copies; left active, the old value survived the change.
    async fn supersede_copies(
        &self,
        changed_id: i64,
        key: &str,
        value: &str,
        reason: SupersededReason,
        max_source_rank: u8,
    ) -> anyhow::Result<()> {
        let value = value.trim();
        if value.is_empty() {
            return Ok(());
        }
        let canonical = canonicalize_fact_key(key);
        let tokens: std::collections::HashSet<&str> =
            canonical.split('_').filter(|t| !t.is_empty()).collect();
        let rows: Vec<(i64, String, String)> = sqlx::query_as(
            "SELECT id, key, source FROM facts
             WHERE superseded_at IS NULL AND id <> ? AND LOWER(TRIM(value)) = LOWER(?)",
        )
        .bind(changed_id)
        .bind(value)
        .fetch_all(&self.pool)
        .await?;
        let now = Utc::now().to_rfc3339();
        for (id, other_key, other_source) in rows {
            // A quoted change never retires what the owner stated.
            if fact_source_rank(&other_source) > max_source_rank {
                continue;
            }
            let other = canonicalize_fact_key(&other_key);
            let other: std::collections::HashSet<&str> =
                other.split('_').filter(|t| !t.is_empty()).collect();
            // One key must name the other with modifiers added: a shared
            // word alone (`pet_name`, `daughter_name`) is a different fact.
            if !(tokens.is_subset(&other) || other.is_subset(&tokens)) {
                continue;
            }
            sqlx::query(
                "UPDATE facts SET superseded_at = ?, superseded_reason = ?
                 WHERE id = ? AND superseded_at IS NULL",
            )
            .bind(&now)
            .bind(reason.as_str())
            .bind(id)
            .execute(&self.pool)
            .await?;
            if let Err(error) = self.project_fact_memory(id).await {
                tracing::warn!(%error, fact_id = id, "Deferred superseded-copy projection");
            }
        }
        Ok(())
    }
}

fn key_tokens(canonical: &str) -> std::collections::HashSet<&str> {
    canonical.split('_').filter(|t| !t.is_empty()).collect()
}

/// A row's category, key, retirement time, fold target and reason.
type FoldLink = (String, String, Option<String>, Option<i64>, Option<String>);

/// A retired fact row that an automated write would bring back.
#[derive(Debug, Clone)]
pub(crate) struct RetiredKnowledge {
    pub category: String,
    pub key: String,
    pub retired_at: DateTime<Utc>,
}

/// Whether a retired row (`retired_*`, with no active row for its key)
/// covers an automated write of `key = value` in `category`.
///
/// - Same category, same canonical key: always, whatever the reason.
/// - Another category, only with the same value: `project/status` and
///   `technical/status` are different facts. Deleted by the owner: the same
///   canonical key, or one naming the other with words added. Retired before
///   reasons were recorded: the same canonical key only, since the row may
///   be a fold or a value change rather than a deletion.
///
/// A value alone never matches: `true` or `main` under unrelated keys are
/// different facts.
fn retirement_covers(
    (category, key, value): (&str, &[&str], &str),
    (retired_category, retired_key, retired_value): (&str, &str, &str),
    reason: Option<&str>,
) -> bool {
    let retired_canonical = canonicalize_fact_key(retired_key);
    let same_key = key
        .iter()
        .any(|key| canonicalize_fact_key(key) == retired_canonical);
    if retired_category
        .trim()
        .eq_ignore_ascii_case(category.trim())
    {
        return same_key;
    }
    let value = crate::text::normalize_fact_value(value);
    if value.is_empty() || value != crate::text::normalize_fact_value(retired_value) {
        return false;
    }
    match reason {
        Some("deleted") => {
            same_key
                || key.iter().any(|key| {
                    let canonical = canonicalize_fact_key(key);
                    let (a, b) = (key_tokens(&canonical), key_tokens(&retired_canonical));
                    !a.is_empty() && !b.is_empty() && (a.is_subset(&b) || b.is_subset(&a))
                })
        }
        None => same_key,
        Some(_) => false,
    }
}

/// Why a fact row stopped being active, stored in `facts.superseded_reason`.
/// Rows retired before the column existed have none, and are read as
/// "unknown": a deletion, a fold or a value change. Operator cleanups
/// (`db_probe --retire-inferred-behavior`, `--fact-conflict-audit --apply`)
/// write `retired` and `replaced`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SupersededReason {
    /// The owner forgot it (or a copy of what they forgot).
    Deleted,
    /// A newer value replaced it.
    Replaced,
    /// It restated another active fact (`folded_into`).
    Folded,
}

impl SupersededReason {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Deleted => "deleted",
            Self::Replaced => "replaced",
            Self::Folded => "folded",
        }
    }
}

/// Owner type of the cached key-text vectors fact dedup compares. The fact
/// row owns its vector, so retention drops it with the fact; lookups go by
/// the key text's hash.
const DEDUP_KEY_OWNER: &str = "fact_key";
const DEDUP_KEY_PURPOSE: &str = "dedup";

impl SqliteMemory {
    /// Vectors for fact-dedup key texts, in order. `texts` pairs each text
    /// with the fact row it belongs to, if any; a stored row's vector is
    /// cached under that row and read back next time: a category holds
    /// thousands of keys, and embedding them all on every write took
    /// seconds.
    async fn dedup_key_vectors(
        &self,
        texts: Vec<(Option<i64>, String)>,
    ) -> anyhow::Result<Vec<Vec<f32>>> {
        use crate::embedding_index::content_hash;
        let model = self.embedding_service.model_id();
        let hashes: Vec<String> = texts.iter().map(|(_, t)| content_hash(t)).collect();
        let mut cached: std::collections::HashMap<String, Vec<f32>> =
            std::collections::HashMap::new();
        let mut unique: Vec<&String> = hashes.iter().collect();
        unique.sort();
        unique.dedup();
        for chunk in unique.chunks(500) {
            let mut builder = sqlx::QueryBuilder::<sqlx::Sqlite>::new(
                "SELECT content_hash, embedding FROM memory_embeddings
                 WHERE owner_type = ",
            );
            builder
                .push_bind(DEDUP_KEY_OWNER)
                .push(" AND embedding_purpose = ")
                .push_bind(DEDUP_KEY_PURPOSE)
                .push(" AND embedding_model = ")
                .push_bind(&model)
                .push(" AND stale_at IS NULL AND content_hash IN (");
            let mut separated = builder.separated(", ");
            for hash in chunk {
                separated.push_bind(*hash);
            }
            separated.push_unseparated(")");
            for row in builder.build().fetch_all(&self.pool).await? {
                let blob: Vec<u8> = row.get("embedding");
                if let Ok(vector) = self.embedding_service.decode(&blob) {
                    cached.insert(row.get("content_hash"), vector);
                }
            }
        }

        // (hash, owning fact, text)
        let mut missing: Vec<(String, Option<i64>, String)> = Vec::new();
        let mut queued = std::collections::HashSet::new();
        for ((owner, text), hash) in texts.iter().zip(&hashes) {
            if !cached.contains_key(hash) && queued.insert(hash.clone()) {
                missing.push((hash.clone(), *owner, text.clone()));
            }
        }
        if !missing.is_empty() {
            let vectors = self
                .embedding_service
                .embed_many(missing.iter().map(|(_, _, text)| text.clone()).collect())
                .await?;
            let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
            for ((hash, owner, _), vector) in missing.iter().zip(&vectors) {
                let Some(owner) = owner else {
                    continue;
                };
                sqlx::query(
                    "INSERT INTO memory_embeddings
                        (owner_type, owner_id, embedding_purpose, embedding_model,
                         embedding_dim, content_hash, embedding, created_at, updated_at)
                     VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
                     ON CONFLICT(owner_type, owner_id, embedding_purpose, embedding_model, content_hash)
                     DO UPDATE SET embedding = excluded.embedding, stale_at = NULL,
                                   updated_at = datetime('now')",
                )
                .bind(DEDUP_KEY_OWNER)
                .bind(owner.to_string())
                .bind(DEDUP_KEY_PURPOSE)
                .bind(&model)
                .bind(vector.len() as i64)
                .bind(hash)
                .bind(encode_embedding(vector))
                .execute(&mut *tx)
                .await?;
            }
            tx.commit().await?;
            for ((hash, _, _), vector) in missing.into_iter().zip(vectors) {
                cached.insert(hash, vector);
            }
        }
        hashes
            .iter()
            .map(|hash| {
                cached
                    .get(hash)
                    .cloned()
                    .ok_or_else(|| anyhow::anyhow!("no dedup vector for a key"))
            })
            .collect()
    }

    /// Every fact an explicit search ranks, loaded once: canonical
    /// projections, then active rows, minus owner rows a projection already
    /// covers. The map sends each such projection to the raw row it
    /// replaced, whose vector stands in for it: projections have no vector
    /// of their own, and without one they would be reachable by keyword only.
    async fn explicit_search_facts(
        &self,
    ) -> anyhow::Result<(Vec<Fact>, std::collections::HashMap<i64, i64>)> {
        let mut facts = self.canonical_personal_facts().await?;
        let projection_by_key: std::collections::HashMap<String, i64> = facts
            .iter()
            .filter(|fact| fact.category == "user")
            .map(|fact| (canonical_personal_key(&fact.key), fact.id))
            .collect();
        // The newest covered row stands in.
        let mut newest: std::collections::HashMap<i64, (i64, DateTime<Utc>)> =
            std::collections::HashMap::new();
        for fact in self.get_all_facts_with_provenance().await? {
            let covering = (fact.category == "user")
                .then(|| projection_by_key.get(&canonical_personal_key(&fact.key)))
                .flatten();
            match covering {
                Some(projection) => {
                    let slot = newest
                        .entry(*projection)
                        .or_insert((fact.id, fact.updated_at));
                    if fact.updated_at > slot.1 {
                        *slot = (fact.id, fact.updated_at);
                    }
                }
                None => facts.push(fact),
            }
        }
        let stand_ins = newest.into_iter().map(|(p, (id, _))| (p, id)).collect();
        Ok((facts, stand_ins))
    }

    /// Cosine of the query against every fact with a current vector, by
    /// position in `facts`. Empty when the query cannot be embedded.
    async fn explicit_search_cosine(
        &self,
        query: &str,
        facts: &[Fact],
        stand_ins: &std::collections::HashMap<i64, i64>,
    ) -> Vec<(usize, f32)> {
        let query_vec = match self.embedding_service.embed(query.to_string()).await {
            Ok(vector) => vector,
            Err(error) => {
                tracing::warn!(target: "memory_recall", %error, "explicit fact search: query embedding failed; lexical only");
                return Vec::new();
            }
        };
        let vector_id = |fact: &Fact| stand_ins.get(&fact.id).copied().unwrap_or(fact.id);
        let indexed = self
            .fact_embedding_scores(&query_vec, facts.len() + stand_ins.len())
            .await
            .unwrap_or_default();
        let fallback = self
            .unindexed_fact_scores(
                &query_vec,
                facts.iter().map(vector_id).filter(|id| *id > 0),
                &indexed,
            )
            .await;
        facts
            .iter()
            .enumerate()
            .filter_map(|(i, fact)| {
                let id = vector_id(fact);
                indexed
                    .get(&id)
                    .or_else(|| fallback.get(&id))
                    .map(|score| (i, *score))
            })
            .collect()
    }
}

#[async_trait]
impl FactStore for SqliteMemory {
    async fn search_facts(
        &self,
        query: &str,
        limit: usize,
        config: &crate::search::FactSearchConfig,
    ) -> anyhow::Result<crate::search::FactSearchReport> {
        use crate::neighborhood::{eligible_neighbors, is_relationship_key, seeds_from_hits};
        use crate::search::{self, LexicalIndex};

        if query.trim().is_empty() || limit == 0 {
            return Ok(search::FactSearchReport::default());
        }
        let started = std::time::Instant::now();
        let (facts, stand_ins) = self.explicit_search_facts().await?;
        let load_ms = started.elapsed().as_millis() as u64;

        let stage = std::time::Instant::now();
        let lexical = LexicalIndex::build(&facts).score(query);
        let lexical_ms = stage.elapsed().as_millis() as u64;

        let stage = std::time::Instant::now();
        let cosine = self.explicit_search_cosine(query, &facts, &stand_ins).await;
        let embed_ms = stage.elapsed().as_millis() as u64;

        let stage = std::time::Instant::now();
        let pool = search::candidates(&facts, &lexical, &cosine, config);
        let mut report = search::rank(&facts, &pool, limit, config);
        let rank_ms = stage.elapsed().as_millis() as u64;

        // Expansion seeds come only from the hits actually returned.
        let stage = std::time::Instant::now();
        let hit_facts: Vec<Fact> = report.hits.iter().map(|h| h.fact.clone()).collect();
        let known_people: Vec<String> = PeopleStore::get_all_people(self)
            .await
            .unwrap_or_default()
            .into_iter()
            .flat_map(|p| std::iter::once(p.name).chain(p.aliases))
            .collect();
        let seeds = seeds_from_hits(&hit_facts, &known_people);
        let relationship_cluster = hit_facts.iter().any(|f| is_relationship_key(&f.key));
        if !seeds.is_empty() || relationship_cluster {
            let exclude: std::collections::HashSet<i64> = hit_facts.iter().map(|f| f.id).collect();
            let mut neighbors = eligible_neighbors(&facts, &seeds, relationship_cluster, &exclude);
            // A neighbor duplicating a hit's content is not new context.
            let shown: std::collections::HashSet<(&str, &str, &str)> = hit_facts
                .iter()
                .map(|f| (f.category.as_str(), f.key.as_str(), f.value.as_str()))
                .collect();
            neighbors.retain(|f| {
                !shown.contains(&(f.category.as_str(), f.key.as_str(), f.value.as_str()))
            });

            let position: std::collections::HashMap<i64, usize> =
                facts.iter().enumerate().map(|(i, f)| (f.id, i)).collect();
            let cosine_by_index: std::collections::HashMap<usize, f32> =
                cosine.iter().copied().collect();
            let lexical_by_index: std::collections::HashMap<usize, f32> =
                lexical.iter().map(|h| (h.index, h.score)).collect();
            let prior = |f: &Fact| -> f32 {
                let index = position[&f.id];
                if cosine.is_empty() {
                    lexical_by_index.get(&index).copied().unwrap_or(0.0)
                } else {
                    cosine_by_index.get(&index).copied().unwrap_or(0.0)
                }
            };
            if neighbors.len() > config.related_pool {
                neighbors.sort_by(|a, b| prior(b).total_cmp(&prior(a)).then(a.id.cmp(&b.id)));
                neighbors.truncate(config.related_pool);
            }
            let scores: Vec<(usize, f32)> = neighbors
                .iter()
                .enumerate()
                .map(|(i, f)| (i, prior(f)))
                .collect();
            report.related = search::rank_related(&neighbors, &scores, config);
        }
        let expand_ms = stage.elapsed().as_millis() as u64;

        // Scores of the leading hits: `key=score (kind)`.
        let summarize = |hits: &[search::SearchHit]| {
            hits.iter()
                .take(3)
                .map(|h| format!("{}={:.3} ({:?})", h.fact.key, h.score, h.kind))
                .collect::<Vec<_>>()
                .join(", ")
        };
        let top = summarize(&report.hits);
        let related_top = summarize(&report.related);
        tracing::info!(
            target: "memory_recall",
            load_ms,
            lexical_ms,
            embed_ms,
            rank_ms,
            expand_ms,
            considered = report.considered,
            returned = report.hits.len(),
            related = report.related.len(),
            top = %top,
            related_top = %related_top,
            "explicit fact search"
        );
        Ok(report)
    }

    async fn stamp_fact_provenance(
        &self,
        category: &str,
        key: &str,
        source: &str,
        first_seen_at: Option<DateTime<Utc>>,
        source_excerpt: Option<&str>,
    ) -> anyhow::Result<()> {
        sqlx::query(
            "UPDATE facts
             SET source = ?, first_seen_at = ?, source_excerpt = ?
             WHERE category = ? AND key = ? AND superseded_at IS NULL",
        )
        .bind(source)
        .bind(first_seen_at.map(|at| at.to_rfc3339()))
        .bind(source_excerpt)
        .bind(category)
        .bind(key)
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    async fn reconcile_personal_memory(
        &self,
        write: &crate::records::PersonalMemoryWrite,
        source: &str,
        source_excerpt: Option<&str>,
        channel_id: Option<&str>,
        privacy: FactPrivacy,
    ) -> anyhow::Result<crate::records::PersonalMemoryWriteResult> {
        self.reconcile_structured_personal_memory(
            write,
            source,
            source_excerpt,
            channel_id,
            privacy,
        )
        .await
    }

    async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
        self.canonical_personal_facts().await
    }

    async fn record_memory_recall(
        &self,
        fact_ids: &[i64],
        episode_ids: &[i64],
    ) -> anyhow::Result<()> {
        // Canonical projections carry synthetic negative ids; they have no
        // row to count against.
        let now = Utc::now().to_rfc3339();
        for (table, ids) in [("facts", fact_ids), ("episodes", episode_ids)] {
            let ids: Vec<i64> = ids.iter().copied().filter(|id| *id > 0).collect();
            if ids.is_empty() {
                continue;
            }
            let placeholders = vec!["?"; ids.len()].join(", ");
            let sql = format!(
                "UPDATE {table} SET recall_count = COALESCE(recall_count, 0) + 1, last_recalled_at = ? WHERE id IN ({placeholders})"
            );
            let mut query = sqlx::query(sqlx::AssertSqlSafe(&*sql)).bind(&now);
            for id in &ids {
                query = query.bind(id);
            }
            query.execute(&self.pool).await?;
        }
        Ok(())
    }

    async fn fold_restated_facts(&self) -> anyhow::Result<usize> {
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let mut candidates = self.fold_candidates().await?;
        let folded: Vec<(i64, i64)> = super::fact_folds::plan_folds(&mut candidates)
            .into_iter()
            .map(|fold| (fold.folded, fold.kept))
            .collect();
        if folded.is_empty() {
            return Ok(0);
        }
        let now = Utc::now().to_rfc3339();
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        for (folded_id, kept_id) in &folded {
            sqlx::query(
                "UPDATE facts SET superseded_at = ?, superseded_reason = ?, folded_into = ?
                 WHERE id = ? AND superseded_at IS NULL",
            )
            .bind(&now)
            .bind(SupersededReason::Folded.as_str())
            .bind(kept_id)
            .bind(folded_id)
            .execute(&mut *tx)
            .await?;
            sqlx::query(
                "UPDATE facts SET recall_count = MAX(COALESCE(recall_count, 0),
                     (SELECT COALESCE(recall_count, 0) FROM facts WHERE id = ?))
                 WHERE id = ?",
            )
            .bind(folded_id)
            .bind(kept_id)
            .execute(&mut *tx)
            .await?;
        }
        tx.commit().await?;
        // A folded row leaves recall's projections too, as a copy does.
        for (folded_id, _) in &folded {
            if let Err(error) = self.project_fact_memory(*folded_id).await {
                tracing::warn!(%error, fact_id = folded_id, "Deferred folded-fact projection");
            }
        }
        tracing::info!(
            folded = folded.len(),
            "Folded restated facts into their representatives"
        );
        Ok(folded.len())
    }

    async fn memory_health_report(&self) -> anyhow::Result<crate::records::MemoryHealthReport> {
        self.canonical_memory_health().await
    }

    async fn repair_memory_projections(
        &self,
    ) -> anyhow::Result<crate::records::MemoryHealthReport> {
        self.backfill_missing_memory_projections().await?;
        self.canonical_memory_health().await
    }

    async fn refresh_fact_memory(&self, category: &str, key: &str) -> anyhow::Result<()> {
        if let Some(id) = sqlx::query_scalar::<_, i64>(
            "SELECT id FROM facts WHERE lower(category) = lower(?) AND lower(key) = lower(?)
             AND superseded_at IS NULL ORDER BY updated_at DESC LIMIT 1",
        )
        .bind(category)
        .bind(key)
        .fetch_optional(&self.pool)
        .await?
        {
            self.project_fact_memory(id).await?;
        }
        Ok(())
    }

    async fn project_extracted_fact_graph(
        &self,
        category: &str,
        key: &str,
        source_excerpt: &str,
        graph: &crate::records::ExtractedMemoryGraph,
    ) -> anyhow::Result<()> {
        self.persist_extracted_fact_graph(category, key, source_excerpt, graph)
            .await
    }

    #[allow(clippy::too_many_arguments)]
    async fn upsert_fact_with_provenance(
        &self,
        category: &str,
        key: &str,
        value: &str,
        source: &str,
        channel_id: Option<&str>,
        privacy: FactPrivacy,
        first_seen_at: Option<DateTime<Utc>>,
        source_excerpt: Option<&str>,
    ) -> anyhow::Result<()> {
        // The legacy flat-fact API performs a read/reconcile/write sequence.
        // Serialize that sequence so two concurrent writes for the same key
        // cannot both supersede the active row and race through the unique
        // active-fact constraint. Structured personal-memory writes use their
        // own explicit SQL transaction and do not take this compatibility lock.
        // A key folded into another fact writes through to that fact: a later
        // value for the folded key is an update of the knowledge it carries,
        // not a resurrection to refuse.
        if let Some((survivor_category, survivor_key)) =
            self.folded_survivor(category.trim(), key.trim()).await?
        {
            tracing::debug!(
                category,
                key,
                survivor_category = survivor_category.as_str(),
                survivor_key = survivor_key.as_str(),
                "Fact write redirected to the fact its key was folded into"
            );
            return self
                .upsert_fact_with_provenance(
                    &survivor_category,
                    &survivor_key,
                    value,
                    source,
                    channel_id,
                    privacy,
                    first_seen_at,
                    source_excerpt,
                )
                .await;
        }
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let now = Utc::now().to_rfc3339();
        let privacy_str = privacy.to_string();

        let category_clean = category.trim();
        let key_clean = key.trim();
        let canonical_key = canonicalize_fact_key(key_clean);

        // Find existing current fact (not superseded).
        // Prefer exact match; fall back to canonical match to avoid key drift
        // ("dog name" vs "dog_name") creating duplicates.
        let mut existing: Option<(i64, String, String)> = None;

        if let Some(row) = sqlx::query(
            "SELECT id, key, value FROM facts WHERE category = ? AND key = ? AND superseded_at IS NULL",
        )
        .bind(category_clean)
        .bind(key_clean)
        .fetch_optional(&self.pool)
        .await?
        {
            existing = Some((row.get("id"), row.get("key"), row.get("value")));
        } else {
            if canonical_key != key_clean
                && let Some(row) = sqlx::query(
                    "SELECT id, key, value FROM facts WHERE category = ? AND key = ? AND superseded_at IS NULL",
                )
                .bind(category_clean)
                .bind(&canonical_key)
                .fetch_optional(&self.pool)
                .await?
                {
                    existing = Some((row.get("id"), row.get("key"), row.get("value")));
                }

            if existing.is_none() && !canonical_key.is_empty() {
                // Canonical scan: match an existing key by canonical form.
                // Limits churn when historical keys were not canonicalized.
                let rows = sqlx::query(
                    "SELECT id, key, value FROM facts WHERE category = ? AND superseded_at IS NULL ORDER BY updated_at DESC",
                )
                .bind(category_clean)
                .fetch_all(&self.pool)
                .await?;
                for row in rows {
                    let existing_key: String = row.get("key");
                    if canonicalize_fact_key(&existing_key) == canonical_key {
                        existing = Some((row.get("id"), existing_key, row.get("value")));
                        break;
                    }
                }
            }
        }

        // Semantic dedup: if key-based matching found nothing, check if any active
        // fact in the same category is semantically equivalent (different key, same
        // concept). Catches synonym keys like "editor" vs "preferred_editor".
        //
        // We compare key-only embeddings (category + readable key) rather than
        // full fact embeddings (which include value), because dedup should detect
        // that two keys refer to the same concept regardless of their values.
        if existing.is_none() {
            let category_facts = sqlx::query(
                "SELECT id, key, value FROM facts
                 WHERE category = ? AND superseded_at IS NULL",
            )
            .bind(category_clean)
            .fetch_all(&self.pool)
            .await?;

            let new_tokens: std::collections::HashSet<&str> =
                canonical_key.split('_').filter(|t| !t.is_empty()).collect();

            // Guard against false semantic matches for keys that are
            // structurally similar but intentionally distinct.
            //
            // If keys share SOME tokens, have the same token count, but
            // differ in at least one token, they're variants of the same
            // base concept (e.g., "dog_name_old" vs "dog_name_new") — skip.
            //
            // But allow through:
            // - Keys that are a subset/superset (modifier pattern):
            //   "editor" vs "preferred_editor" — different count, proceed.
            // - Keys that are just reordered (same tokens, same count):
            //   "company_previous" vs "previous_company" — all shared, proceed.
            // - Keys with zero overlap: completely different concepts.
            let comparable: Vec<&sqlx::sqlite::SqliteRow> = category_facts
                .iter()
                .filter(|row| {
                    let existing_canonical = canonicalize_fact_key(&row.get::<String, _>("key"));
                    let existing_tokens: std::collections::HashSet<&str> = existing_canonical
                        .split('_')
                        .filter(|t| !t.is_empty())
                        .collect();
                    !keys_name_distinct_concepts(&new_tokens, &existing_tokens)
                })
                .collect();

            // One embedder call for the new key and every comparable key: a
            // call per row costs a model hop each and made one write into a
            // large category take seconds.
            if !comparable.is_empty() {
                let mut texts = Vec::with_capacity(comparable.len() + 1);
                texts.push((None, build_dedup_key_text(category_clean, key_clean)));
                texts.extend(comparable.iter().map(|row| {
                    (
                        Some(row.get::<i64, _>("id")),
                        build_dedup_key_text(category_clean, &row.get::<String, _>("key")),
                    )
                }));
                if let Ok(vectors) = self.dedup_key_vectors(texts).await {
                    let new_vec = &vectors[0];
                    let mut best_match: Option<(i64, String, String, f32)> = None;
                    for (row, existing_vec) in comparable.iter().zip(&vectors[1..]) {
                        let sim = cosine_similarity(new_vec, existing_vec);
                        if sim > 0.85 && sim > best_match.as_ref().map_or(0.0, |m| m.3) {
                            best_match = Some((
                                row.get("id"),
                                row.get::<String, _>("key"),
                                row.get::<String, _>("value"),
                                sim,
                            ));
                        }
                    }

                    if let Some((id, matched_key, matched_value, sim)) = best_match {
                        tracing::info!(
                            category = category_clean,
                            new_key = key_clean,
                            matched_key = matched_key.as_str(),
                            similarity = sim,
                            "Semantic dedup: matched existing fact by embedding similarity"
                        );
                        existing = Some((id, matched_key, matched_value));
                    }
                }
            }
        }

        let key_for_write = existing
            .as_ref()
            .map(|(_, k, _)| k.clone())
            .unwrap_or_else(|| {
                if canonical_key.is_empty() {
                    key_clean.to_string()
                } else {
                    canonical_key.clone()
                }
            });

        // Pre-compute embedding for the fact text (best-effort).
        let fact_text = build_fact_embedding_text(category_clean, &key_for_write, value);
        let embedding_blob = self
            .embedding_service
            .embed(fact_text)
            .await
            .ok()
            .map(|v| encode_embedding(&v));

        let automated_source = !is_owner_authored_fact_source(source);
        // Background extraction reads conversations after the fact: evidence
        // older than a later, different value of the same knowledge (its key,
        // in any category) is what the owner corrected since, and must not
        // replace or compete with the correction.
        if automated_source
            && let Some(seen) = first_seen_at
            && self
                .corrected_since(&[key_clean, &canonical_key, &key_for_write], value, seen)
                .await?
        {
            tracing::debug!(
                category = category_clean,
                key = key_clean,
                source,
                "Automated fact write skipped: a later value of this knowledge replaced it"
            );
            return Ok(());
        }
        if existing.is_none() && automated_source {
            // Knowledge the owner deleted, or a key merged away, must not be
            // brought back by background extraction, in any category the
            // extractor picks. Evidence newer than the retirement is the
            // owner saying it again, and is let through.
            if let Some(tombstone) = self
                .retired_knowledge(category_clean, &[key_clean, &key_for_write], value)
                .await?
                .into_iter()
                .find(|tombstone| first_seen_at.is_none_or(|seen| seen <= tombstone.retired_at))
            {
                tracing::debug!(
                    category = category_clean,
                    key = key_clean,
                    source,
                    retired_category = tombstone.category.as_str(),
                    retired_key = tombstone.key.as_str(),
                    "Automated fact write skipped: that knowledge was deleted or merged"
                );
                return Ok(());
            }
            // Paraphrased key, same knowledge: refresh the active fact rather
            // than storing a second copy that competes for recall slots. A
            // restatement is looked for in this category; the same value
            // under a reworded key in any category. Never across scopes.
            if let Some(new_vec) = embedding_blob
                .as_deref()
                .and_then(|blob| self.embedding_service.decode(blob).ok())
            {
                let candidates = sqlx::query(
                    "SELECT id, category, key, value, source, embedding FROM facts
                     WHERE superseded_at IS NULL AND embedding IS NOT NULL
                       AND COALESCE(privacy, 'global') = ? AND channel_id IS ?",
                )
                .bind(&privacy_str)
                .bind(channel_id)
                .fetch_all(&self.pool)
                .await?;
                let new_value = crate::text::normalize_fact_value(value);
                let restated = candidates.iter().find_map(|row| {
                    let other_category: String = row.get("category");
                    let other_key: String = row.get("key");
                    let other_value: String = row.get("value");
                    let same_category = other_category.trim() == category_clean;
                    // Decode only what either rule could match.
                    if !same_category
                        && crate::text::normalize_fact_value(&other_value) != new_value
                    {
                        return None;
                    }
                    let blob: Vec<u8> = row.get("embedding");
                    let other_vec = self.embedding_service.decode(&blob).ok()?;
                    let sim = cosine_similarity(&new_vec, &other_vec);
                    let restates = same_category
                        && facts_are_restatements(
                            category_clean,
                            (key_clean, value),
                            (&other_key, &other_value),
                            sim,
                        );
                    (restates
                        || super::fact_folds::facts_hold_one_value(
                            (category_clean, key_clean, value),
                            (&other_category, &other_key, &other_value),
                            sim,
                        ))
                    .then(|| {
                        (
                            row.get::<i64, _>("id"),
                            other_key,
                            sim,
                            row.get::<String, _>("source"),
                        )
                    })
                });
                if let Some((id, matched_key, sim, matched_source)) = restated {
                    tracing::info!(
                        category = category_clean,
                        new_key = key_clean,
                        matched_key = matched_key.as_str(),
                        similarity = sim,
                        source,
                        "Automated fact write folded into existing restatement"
                    );
                    // The owner quoting what an extractor inferred raises the
                    // kept fact to the quote's rank, with the quote.
                    if fact_source_rank(source) > fact_source_rank(&matched_source) {
                        sqlx::query(
                            "UPDATE facts SET updated_at = ?, source = ?,
                                 source_excerpt = COALESCE(?, source_excerpt) WHERE id = ?",
                        )
                        .bind(&now)
                        .bind(source)
                        .bind(source_excerpt)
                        .bind(id)
                        .execute(&self.pool)
                        .await?;
                    } else {
                        sqlx::query("UPDATE facts SET updated_at = ? WHERE id = ?")
                            .bind(&now)
                            .bind(id)
                            .execute(&self.pool)
                            .await?;
                    }
                    return Ok(());
                }
            }
        }

        if let Some((old_id, _old_key, old_value)) = &existing {
            // Spacing and punctuation are not a new value: rewriting
            // "~/projects/" as "~/projects" refreshes the row instead of
            // replacing it and resetting its recall history. Case is kept
            // (paths and handles can be case-sensitive).
            let words = |text: &str| -> Vec<String> {
                text.split(|c: char| !c.is_alphanumeric())
                    .filter(|word| !word.is_empty())
                    .map(str::to_string)
                    .collect()
            };
            let old_value = if !words(value).is_empty() && words(old_value) == words(value) {
                value
            } else {
                old_value.as_str()
            };
            // If the value is different, mark old as superseded and insert new.
            //
            // Source priority guard: a write replaces a different value only
            // at equal or higher source rank. Background extractors read tool
            // output and paraphrase; they can lift a wrong value from a
            // hallucinated or stale message, so they never replace what the
            // owner stated or a value quoted from the owner's message (an
            // hour-old consolidation batch cannot revert a fresh correction).
            if old_value != value {
                let existing_source: Option<String> =
                    sqlx::query_scalar("SELECT source FROM facts WHERE id = ?")
                        .bind(old_id)
                        .fetch_optional(&self.pool)
                        .await?;
                if existing_source
                    .as_deref()
                    .is_some_and(|existing| fact_source_rank(existing) > fact_source_rank(source))
                {
                    tracing::info!(
                        category = category_clean,
                        key = key_clean,
                        existing_source = ?existing_source,
                        source,
                        "Fact write skipped: refusing to overwrite a fact from a closer source"
                    );
                    return Ok(());
                }
            }
            if old_value != value {
                sqlx::query("UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced' WHERE id = ?")
                    .bind(&now)
                    .bind(old_id)
                    .execute(&self.pool)
                    .await?;

                // Insert new fact with embedding — ignore duplicate entry errors (code 2067)
                // that can occur due to active-unique constraint race conditions.
                let insert_result = sqlx::query(
                    "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count, channel_id, privacy, embedding, first_seen_at, source_excerpt)
                     VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
                )
                .bind(category_clean)
                .bind(&key_for_write)
                .bind(value)
                .bind(source)
                .bind(&now)
                .bind(&now)
                .bind(channel_id)
                .bind(&privacy_str)
                .bind(&embedding_blob)
                .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                .bind(source_excerpt)
                .execute(&self.pool)
                .await;

                match insert_result {
                    Ok(_) => {}
                    Err(sqlx::Error::Database(ref db_err))
                        if db_err.code().as_deref() == Some("2067") =>
                    {
                        // Duplicate entry — another active row already exists (concurrent upsert).
                        // Update the active row to "last write wins" without resurrecting the
                        // superseded row (which would violate partial unique indexes).
                        let updated = sqlx::query(
                            "UPDATE facts
                             SET value = ?, source = ?, updated_at = ?,
                                 channel_id = ?, privacy = ?,
                                 embedding = COALESCE(?, embedding),
                                 first_seen_at = COALESCE(?, first_seen_at),
                                 source_excerpt = COALESCE(?, source_excerpt)
                             WHERE category = ? AND key = ? AND superseded_at IS NULL",
                        )
                        .bind(value)
                        .bind(source)
                        .bind(&now)
                        .bind(channel_id)
                        .bind(&privacy_str)
                        .bind(&embedding_blob)
                        .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                        .bind(source_excerpt)
                        .bind(category_clean)
                        .bind(&key_for_write)
                        .execute(&self.pool)
                        .await?;

                        // Legacy fallback: if no active row exists (e.g., old UNIQUE(category,key)
                        // constraint), keep data consistent by updating in-place.
                        if updated.rows_affected() == 0 {
                            sqlx::query(
                                "UPDATE facts
                                 SET value = ?, source = ?, updated_at = ?, superseded_at = NULL, superseded_reason = NULL, folded_into = NULL,
                                     channel_id = ?, privacy = ?,
                                     embedding = COALESCE(?, embedding),
                                     first_seen_at = COALESCE(?, first_seen_at),
                                     source_excerpt = COALESCE(?, source_excerpt)
                                 WHERE id = ?",
                            )
                            .bind(value)
                            .bind(source)
                            .bind(&now)
                            .bind(channel_id)
                            .bind(&privacy_str)
                            .bind(&embedding_blob)
                            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                            .bind(source_excerpt)
                            .bind(old_id)
                            .execute(&self.pool)
                            .await?;
                        }
                    }
                    Err(e) => return Err(e.into()),
                }
                if fact_source_rank(source) > 0 {
                    self.supersede_copies(
                        *old_id,
                        &key_for_write,
                        old_value,
                        SupersededReason::Replaced,
                        fact_source_rank(source),
                    )
                    .await?;
                }
            } else {
                // Same value — update timestamp and backfill embedding.
                // A restatement never lowers the row's source rank; a closer
                // source raises it and brings its quote.
                let existing_source: Option<String> =
                    sqlx::query_scalar("SELECT source FROM facts WHERE id = ?")
                        .bind(old_id)
                        .fetch_optional(&self.pool)
                        .await?;
                let existing_rank = existing_source.as_deref().map_or(0, fact_source_rank);
                if fact_source_rank(source) < existing_rank {
                    sqlx::query(
                        "UPDATE facts SET updated_at = ?, embedding = COALESCE(embedding, ?) WHERE id = ?",
                    )
                    .bind(&now)
                    .bind(&embedding_blob)
                    .bind(old_id)
                    .execute(&self.pool)
                    .await?;
                } else if fact_source_rank(source) > existing_rank {
                    sqlx::query(
                        "UPDATE facts SET source = ?, updated_at = ?, embedding = COALESCE(embedding, ?), first_seen_at = COALESCE(first_seen_at, ?), source_excerpt = COALESCE(?, source_excerpt) WHERE id = ?",
                    )
                    .bind(source)
                    .bind(&now)
                    .bind(&embedding_blob)
                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                    .bind(source_excerpt)
                    .bind(old_id)
                    .execute(&self.pool)
                    .await?;
                } else {
                    sqlx::query(
                        "UPDATE facts SET source = ?, updated_at = ?, embedding = COALESCE(embedding, ?), first_seen_at = COALESCE(first_seen_at, ?), source_excerpt = COALESCE(source_excerpt, ?) WHERE id = ?",
                    )
                    .bind(source)
                    .bind(&now)
                    .bind(&embedding_blob)
                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                    .bind(source_excerpt)
                    .bind(old_id)
                    .execute(&self.pool)
                    .await?;
                }
            }
        } else {
            // No existing fact - insert new with embedding
            // Ignore duplicate entry errors (code 2067) from concurrent inserts
            let insert_result = sqlx::query(
                "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count, channel_id, privacy, embedding, first_seen_at, source_excerpt)
                 VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)",
            )
            .bind(category_clean)
            .bind(&key_for_write)
            .bind(value)
            .bind(source)
            .bind(&now)
            .bind(&now)
            .bind(channel_id)
            .bind(&privacy_str)
            .bind(&embedding_blob)
            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
            .bind(source_excerpt)
            .execute(&self.pool)
            .await;

            match insert_result {
                Ok(_) => {}
                Err(sqlx::Error::Database(ref db_err))
                    if db_err.code().as_deref() == Some("2067") =>
                {
                    // Duplicate entry — another active row already exists (concurrent upsert).
                    // Update the active row to "last write wins".
                    let updated = sqlx::query(
                        "UPDATE facts
                         SET value = ?, source = ?, updated_at = ?,
                             channel_id = ?, privacy = ?,
                             embedding = COALESCE(?, embedding),
                             first_seen_at = COALESCE(?, first_seen_at),
                             source_excerpt = COALESCE(?, source_excerpt)
                         WHERE category = ? AND key = ? AND superseded_at IS NULL",
                    )
                    .bind(value)
                    .bind(source)
                    .bind(&now)
                    .bind(channel_id)
                    .bind(&privacy_str)
                    .bind(&embedding_blob)
                    .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                    .bind(source_excerpt)
                    .bind(category_clean)
                    .bind(&key_for_write)
                    .execute(&self.pool)
                    .await?;

                    if updated.rows_affected() == 0 {
                        // If there is no active row, update the most recent version in-place.
                        // This can happen on legacy schemas where a superseded row still blocks
                        // inserts (old UNIQUE(category,key) constraint).
                        if let Some(row) = sqlx::query(
                            "SELECT id FROM facts WHERE category = ? AND key = ? ORDER BY updated_at DESC LIMIT 1",
                        )
                        .bind(category_clean)
                        .bind(&key_for_write)
                        .fetch_optional(&self.pool)
                        .await?
                        {
                            let id: i64 = row.get("id");
                            sqlx::query(
                                "UPDATE facts
                                 SET value = ?, source = ?, updated_at = ?, superseded_at = NULL, superseded_reason = NULL, folded_into = NULL,
                                     channel_id = ?, privacy = ?,
                                     embedding = COALESCE(?, embedding),
                                     first_seen_at = COALESCE(?, first_seen_at),
                                     source_excerpt = COALESCE(?, source_excerpt)
                                 WHERE id = ?",
                            )
                            .bind(value)
                            .bind(source)
                            .bind(&now)
                            .bind(channel_id)
                            .bind(&privacy_str)
                            .bind(&embedding_blob)
                            .bind(first_seen_at.as_ref().map(|dt| dt.to_rfc3339()))
                            .bind(source_excerpt)
                            .bind(id)
                            .execute(&self.pool)
                            .await?;
                        }
                    }
                }
                Err(e) => return Err(e.into()),
            }
        }

        // ── Post-store conflict sweep ──────────────────────────────────
        //
        // When the owner stores a fact through remember_fact (source ==
        // "agent"), an active row in the same category whose key names the
        // same attribute in canonical form ("dog name" / "dog_name" left by
        // an older, uncanonicalized write) and holds another value is stale:
        // it is superseded. Identity is the canonical key only. Facts under
        // different keys are never superseded here, whatever words or
        // embedding they share ("favorite_drink: green tea" must never
        // retire "allergy: green tea").
        if source == "agent" {
            let canonical_written = canonicalize_fact_key(&key_for_write);
            let others = sqlx::query(
                "SELECT id, key, value FROM facts
                         WHERE category = ? AND superseded_at IS NULL
                           AND key != ?",
            )
            .bind(category_clean)
            .bind(&key_for_write)
            .fetch_all(&self.pool)
            .await
            .unwrap_or_default();

            for row in &others {
                let other_id: i64 = row.get("id");
                let other_key: String = row.get("key");
                let other_value: String = row.get("value");
                if canonicalize_fact_key(&other_key) != canonical_written || other_value == value {
                    continue;
                }
                tracing::info!(
                    category = category_clean,
                    new_key = key_clean,
                    new_value = value,
                    conflicting_key = other_key.as_str(),
                    conflicting_value = other_value.as_str(),
                    "Conflict sweep: superseding stale fact under the same canonical key"
                );
                let _ = sqlx::query(
                    "UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced' WHERE id = ?",
                )
                .bind(&now)
                .bind(other_id)
                .execute(&self.pool)
                .await;
            }
        }

        if let Err(error) = self.sync_fact_memory_written_at(category_clean, &now).await {
            tracing::warn!(%error, category = category_clean, "Deferred fact memory projection");
        }
        Ok(())
    }

    async fn get_facts(&self, category: Option<&str>) -> anyhow::Result<Vec<Fact>> {
        // Only return current (non-superseded) facts
        let rows = if let Some(cat) = category {
            sqlx::query("SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt FROM facts WHERE category = ? AND superseded_at IS NULL ORDER BY updated_at DESC")
                .bind(cat)
                .fetch_all(&self.pool)
                .await?
        } else {
            sqlx::query("SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt FROM facts WHERE superseded_at IS NULL ORDER BY updated_at DESC")
                .fetch_all(&self.pool)
                .await?
        };

        let mut facts = Vec::with_capacity(rows.len());
        for row in rows {
            facts.push(Self::row_to_fact(&row));
        }
        Ok(facts)
    }

    async fn get_relevant_facts(&self, query: &str, max: usize) -> anyhow::Result<Vec<Fact>> {
        // Load facts; vectors come from the embedding index, and only facts
        // it has none for read their own blob (`unindexed_fact_scores`).
        let rows = sqlx::query(
            "SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt
             FROM facts WHERE superseded_at IS NULL ORDER BY updated_at DESC",
        )
        .fetch_all(&self.pool)
        .await?;

        let all_facts: Vec<Fact> = rows.iter().map(Self::row_to_fact).collect();

        if all_facts.is_empty() || query.trim().is_empty() {
            let mut facts = all_facts;
            facts.truncate(max);
            let canonical = self.canonical_personal_facts().await.unwrap_or_default();
            return Ok(prefer_canonical_facts(canonical, facts, query, max));
        }

        // Embed the query
        let query_vec = match self.embedding_service.embed(query.to_string()).await {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(
                    "Failed to embed query for passive fact filtering; using lexical matches: {}",
                    e
                );
                let facts = lexical_relevant_facts(&all_facts, query, max);
                let canonical = self.canonical_personal_facts().await.unwrap_or_default();
                return Ok(prefer_canonical_facts(canonical, facts, query, max));
            }
        };

        let now = Utc::now();
        let query_lower = query.to_lowercase();
        let tokens = query_tokens(&query_lower);
        let indexed_scores = self
            .fact_embedding_scores(&query_vec, rows.len())
            .await
            .unwrap_or_default();
        let fts_fact_ids: std::collections::HashSet<i64> = self
            .search_memory_claims(
                query,
                None,
                ChannelVisibility::Internal,
                true,
                max.saturating_mul(4).max(16),
            )
            .await
            .unwrap_or_default()
            .into_iter()
            .filter_map(|claim| claim.source_fact_id)
            .collect();
        let graph_fact_ids = self
            .graph_fact_ids_for_query(query)
            .await
            .unwrap_or_default();

        // Score facts using stored embeddings, with a small recency boost for sorting.
        // IMPORTANT: the recency boost must not change which facts pass the semantic threshold.
        let fallback_scores = self
            .unindexed_fact_scores(&query_vec, all_facts.iter().map(|f| f.id), &indexed_scores)
            .await;
        let mut candidates: Vec<(usize, f32, f32, bool)> = Vec::with_capacity(rows.len());
        for (i, fact) in all_facts.iter().enumerate() {
            let freshness = fact_freshness_boost(now, fact.updated_at);

            let semantic = indexed_scores
                .get(&fact.id)
                .or_else(|| fallback_scores.get(&fact.id))
                .copied();
            let lexical = if fts_fact_ids.contains(&fact.id) {
                FACT_LEXICAL_MAX_SCORE
            } else {
                lexical_fallback_score(&query_lower, &tokens, fact)
            };
            if let Some(semantic) = semantic {
                if semantic > FACT_SEMANTIC_MIN_SCORE {
                    candidates.push((
                        i,
                        semantic,
                        hybrid_fact_score(
                            fact,
                            semantic,
                            lexical,
                            graph_fact_ids.contains(&fact.id),
                            freshness,
                        ),
                        true,
                    ));
                    continue;
                }
                // Below semantic threshold — try lexical as fallback for keyword matches
                let best = semantic.max(lexical);
                let is_semantic = best == semantic;
                candidates.push((
                    i,
                    best,
                    hybrid_fact_score(
                        fact,
                        semantic,
                        lexical,
                        graph_fact_ids.contains(&fact.id),
                        freshness,
                    ),
                    is_semantic,
                ));
                continue;
            }

            // Missing/invalid embedding: fall back to cheap lexical relevance so
            // freshly saved facts can still be retrieved during embedding backfill.
            candidates.push((
                i,
                lexical,
                hybrid_fact_score(
                    fact,
                    0.0,
                    lexical,
                    graph_fact_ids.contains(&fact.id),
                    freshness,
                ),
                false,
            ));
        }
        candidates.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));

        let mut relevant: Vec<Fact> = Vec::with_capacity(max.min(all_facts.len()));
        let mut seen_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
        for (i, base_score, _sort_score, is_semantic) in candidates.into_iter() {
            if relevant.len() >= max {
                break;
            }
            let min_score = if is_semantic {
                FACT_SEMANTIC_MIN_SCORE
            } else {
                FACT_LEXICAL_MIN_SCORE
            };
            if base_score > min_score {
                let fact = all_facts[i].clone();
                if seen_ids.insert(fact.id) {
                    relevant.push(fact);
                }
            }
        }

        let canonical = self.canonical_personal_facts().await.unwrap_or_default();
        Ok(prefer_canonical_facts(canonical, relevant, query, max))
    }

    async fn get_relevant_facts_for_channel(
        &self,
        query: &str,
        max: usize,
        channel_id: Option<&str>,
        visibility: ChannelVisibility,
        requester_is_owner: bool,
    ) -> anyhow::Result<Vec<Fact>> {
        // In DM/Internal contexts, use semantic relevance search so that only
        // facts related to the current query are injected into the prompt.
        // Previously this called get_facts(None) which returned ALL facts
        // without filtering, causing unrelated facts to bleed into context.
        //
        // SECURITY: only the OWNER gets the unfiltered graph in a DM. A non-owner
        // (allowlisted Guest) DMing the bot must NOT receive Private or
        // other-channel facts — fall through to the privacy filter below, same as
        // a group channel. Without this gate, a guest's prompt would be injected
        // with the owner's private memory.
        if requester_is_owner
            && matches!(
                visibility,
                ChannelVisibility::Private | ChannelVisibility::Internal
            )
        {
            return self.get_relevant_facts(query, max).await;
        }

        // PublicExternal: do NOT inject any stored facts (treat as untrusted).
        if matches!(visibility, ChannelVisibility::PublicExternal) {
            return Ok(vec![]);
        }

        // Public/PrivateGroup: global + same-channel facts (no private, no other-channel)
        let rows = sqlx::query(
            "SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt
             FROM facts WHERE superseded_at IS NULL ORDER BY updated_at DESC",
        )
        .fetch_all(&self.pool)
        .await?;

        // One visibility rule for every surface that shows a fact
        // (`memory_visible`): what the prompt is given here is what a
        // memory search would show this audience.
        let all_facts: Vec<Fact> = rows.iter().map(Self::row_to_fact).collect();
        let filtered_indices: Vec<usize> = all_facts
            .iter()
            .enumerate()
            .filter(|(_, f)| {
                super::memory_visible(
                    self.channels.as_ref(),
                    f.privacy,
                    f.channel_id.as_deref(),
                    channel_id,
                    visibility,
                    requester_is_owner,
                )
            })
            .map(|(i, _)| i)
            .collect();

        let filtered: Vec<Fact> = filtered_indices
            .iter()
            .map(|&i| all_facts[i].clone())
            .collect();

        if filtered.is_empty() || query.trim().is_empty() {
            let mut facts = filtered;
            facts.truncate(max);
            return Ok(facts);
        }

        // Apply semantic filtering using stored embeddings
        let query_vec = match self.embedding_service.embed(query.to_string()).await {
            Ok(v) => v,
            Err(_) => {
                let facts = lexical_relevant_facts(&filtered, query, max);
                return Ok(facts);
            }
        };

        let now = Utc::now();
        let query_lower = query.to_lowercase();
        let tokens = query_tokens(&query_lower);
        let indexed_scores = self
            .fact_embedding_scores(&query_vec, rows.len())
            .await
            .unwrap_or_default();
        let fts_fact_ids: std::collections::HashSet<i64> = self
            .search_memory_claims(
                query,
                channel_id,
                visibility,
                requester_is_owner,
                max.saturating_mul(4).max(16),
            )
            .await
            .unwrap_or_default()
            .into_iter()
            .filter_map(|claim| claim.source_fact_id)
            .collect();
        let graph_fact_ids = self
            .graph_fact_ids_for_query(query)
            .await
            .unwrap_or_default();

        let fallback_scores = self
            .unindexed_fact_scores(&query_vec, filtered.iter().map(|f| f.id), &indexed_scores)
            .await;
        let mut candidates: Vec<(usize, f32, f32, bool)> = Vec::with_capacity(filtered.len());
        for (fi, fact) in filtered.iter().enumerate() {
            let freshness = fact_freshness_boost(now, fact.updated_at);

            let semantic = indexed_scores
                .get(&fact.id)
                .or_else(|| fallback_scores.get(&fact.id))
                .copied();
            let lexical = if fts_fact_ids.contains(&fact.id) {
                FACT_LEXICAL_MAX_SCORE
            } else {
                lexical_fallback_score(&query_lower, &tokens, fact)
            };
            if let Some(semantic) = semantic {
                if semantic > FACT_SEMANTIC_MIN_SCORE {
                    candidates.push((
                        fi,
                        semantic,
                        hybrid_fact_score(
                            fact,
                            semantic,
                            lexical,
                            graph_fact_ids.contains(&fact.id),
                            freshness,
                        ),
                        true,
                    ));
                    continue;
                }
                // Below semantic threshold — try lexical as fallback for keyword matches
                let best = semantic.max(lexical);
                let is_semantic = best == semantic;
                candidates.push((
                    fi,
                    best,
                    hybrid_fact_score(
                        fact,
                        semantic,
                        lexical,
                        graph_fact_ids.contains(&fact.id),
                        freshness,
                    ),
                    is_semantic,
                ));
                continue;
            }

            candidates.push((
                fi,
                lexical,
                hybrid_fact_score(
                    fact,
                    0.0,
                    lexical,
                    graph_fact_ids.contains(&fact.id),
                    freshness,
                ),
                false,
            ));
        }
        candidates.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));

        let mut relevant: Vec<Fact> = Vec::with_capacity(max.min(filtered.len()));
        let mut seen_ids: std::collections::HashSet<i64> = std::collections::HashSet::new();
        for (fi, base_score, _sort_score, is_semantic) in candidates.into_iter() {
            if relevant.len() >= max {
                break;
            }
            let min_score = if is_semantic {
                FACT_SEMANTIC_MIN_SCORE
            } else {
                FACT_LEXICAL_MIN_SCORE
            };
            if base_score > min_score {
                let fact = filtered[fi].clone();
                if seen_ids.insert(fact.id) {
                    relevant.push(fact);
                }
            }
        }

        Ok(relevant)
    }

    async fn update_fact_privacy(&self, fact_id: i64, privacy: FactPrivacy) -> anyhow::Result<()> {
        sqlx::query("UPDATE facts SET privacy = ? WHERE id = ?")
            .bind(privacy.to_string())
            .bind(fact_id)
            .execute(&self.pool)
            .await?;
        if let Err(error) = self.project_fact_memory(fact_id).await {
            tracing::warn!(%error, fact_id, "Deferred fact privacy projection");
        }
        Ok(())
    }

    async fn delete_fact(&self, fact_id: i64) -> anyhow::Result<()> {
        // A canonical personal-memory record reaches the model under a
        // synthetic negative id; forgetting it retracts that record.
        if fact_id < 0 {
            self.retract_canonical_projection(fact_id, "owner_forget")
                .await?;
            return Ok(());
        }
        let now = Utc::now().to_rfc3339();
        let forgotten: Option<(String, String, String)> = sqlx::query_as(
            "SELECT LOWER(TRIM(category)), LOWER(TRIM(key)), value FROM facts
             WHERE id = ? AND superseded_at IS NULL",
        )
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?;
        sqlx::query(
            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted' WHERE id = ?",
        )
        .bind(&now)
        .bind(fact_id)
        .execute(&self.pool)
        .await?;
        if let Err(error) = self.project_fact_memory(fact_id).await {
            tracing::warn!(%error, fact_id, "Deferred deleted-fact projection");
        }
        if let Some((category, key, value)) = forgotten {
            self.supersede_copies(fact_id, &key, &value, SupersededReason::Deleted, 2)
                .await?;
            if is_owner_profile_category(&category) {
                self.retract_owner_profile_key(&key, "owner_forget").await?;
            }
        }
        Ok(())
    }

    async fn delete_fact_by_key(&self, category: &str, key: &str) -> anyhow::Result<bool> {
        let now = Utc::now().to_rfc3339();
        // Canonicalize: lowercase, trim, strip [brackets]
        let cat_clean = category.trim().to_lowercase();
        let key_clean = key.trim().to_lowercase();
        let deleted: Vec<(i64, String, String)> = sqlx::query_as(
            "SELECT id, key, value FROM facts WHERE LOWER(TRIM(category)) = ? AND LOWER(TRIM(key)) = ? AND superseded_at IS NULL",
        )
        .bind(&cat_clean)
        .bind(&key_clean)
        .fetch_all(&self.pool)
        .await?;
        let ids: Vec<i64> = deleted.iter().map(|(id, _, _)| *id).collect();
        let result = sqlx::query(
            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted' WHERE LOWER(TRIM(category)) = ? AND LOWER(TRIM(key)) = ? AND superseded_at IS NULL",
        )
        .bind(&now)
        .bind(&cat_clean)
        .bind(&key_clean)
        .execute(&self.pool)
        .await?;
        for id in ids {
            if let Err(error) = self.project_fact_memory(id).await {
                tracing::warn!(%error, fact_id = id, "Deferred deleted-fact projection");
            }
        }
        // The owner's profile also lives in the canonical store, which the
        // prompt renders as its own block: forgetting the legacy row alone
        // left the old value in front of the model.
        for (id, key, value) in &deleted {
            self.supersede_copies(*id, key, value, SupersededReason::Deleted, 2)
                .await?;
        }
        let canonical = is_owner_profile_category(&cat_clean)
            && self
                .retract_owner_profile_key(&key_clean, "owner_forget")
                .await?;
        Ok(result.rows_affected() > 0 || canonical)
    }

    async fn get_all_facts_with_provenance(&self) -> anyhow::Result<Vec<Fact>> {
        let rows = sqlx::query(
            "SELECT id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt
             FROM facts WHERE superseded_at IS NULL ORDER BY category, key"
        )
        .fetch_all(&self.pool)
        .await?;

        Ok(rows.iter().map(Self::row_to_fact).collect())
    }
}

/// Legacy categories whose keys describe the owner, as the canonical store
/// projects them (`user`) and as writers name them.
fn is_owner_profile_category(category: &str) -> bool {
    matches!(category, "user" | "personal" | "profile")
}