aidaemon-memory 0.29.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
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
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 {
    let confidence = match fact_source_rank(&fact.source) {
        2 => 1.0,
        1 => 0.85,
        _ => 0.65,
    };
    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,
        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 {
    let base = source.strip_prefix("canonical:").unwrap_or(source);
    matches!(base, "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 {
    let base = source.strip_prefix("canonical:").unwrap_or(source);
    if is_owner_authored_fact_source(base) {
        2
    } else if base == 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::canonicalize_fact_key;

fn prefer_canonical_facts(
    mut canonical: Vec<Fact>,
    legacy: Vec<Fact>,
    query: &str,
    max: usize,
) -> Vec<Fact> {
    // Collect shadowed owner families BEFORE query-filtering canonical facts so
    // an old-value-only query cannot leak a stale flat row after a canonical edit.
    let canonical_owner_keys: std::collections::HashSet<String> = canonical
        .iter()
        .filter(|fact| fact.category == "user")
        .map(|fact| crate::text::owner_projection_family(&fact.key))
        .collect();
    let has_relationships = canonical
        .iter()
        .any(|fact| fact.category == "relationships");
    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())
        });
    }
    canonical.extend(legacy.into_iter().filter(|fact| {
        let cat_lower = fact.category.trim().to_ascii_lowercase();
        let shadowed_owner = (is_owner_profile_category(&cat_lower)
            || (cat_lower == "preference" && crate::text::is_owner_profile_key(&fact.key)))
            && canonical_owner_keys.contains(&crate::text::owner_projection_family(&fact.key));
        !(shadowed_owner
            || 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 AND archived_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 archived_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
        }))
    }

    /// Record a durable tombstone for a deleted or folded fact so retention
    /// cleanup can purge old superseded payloads without allowing background
    /// extractors to resurrect forgotten knowledge.
    async fn record_tombstone(
        &self,
        category: &str,
        key: &str,
        value: &str,
        reason: SupersededReason,
        retired_at: &str,
    ) -> anyhow::Result<()> {
        insert_tombstone(&self.pool, category, key, value, reason, retired_at).await
    }

    async fn retired_knowledge(
        &self,
        category: &str,
        keys: &[&str],
        value: &str,
    ) -> anyhow::Result<Vec<RetiredKnowledge>> {
        let mut 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.archived_at IS NULL
                                AND a.category = f.category AND a.key = f.key)
             ORDER BY f.superseded_at DESC",
        )
        .fetch_all(&self.pool)
        .await?;
        let tombstones: Vec<(String, String, String, String, String)> = sqlx::query_as(
            "SELECT t.category, t.canonical_key, t.normalized_value, t.retired_at, t.reason
             FROM memory_fact_tombstones t
             WHERE NOT EXISTS (SELECT 1 FROM facts a WHERE a.superseded_at IS NULL AND a.archived_at IS NULL
                                AND LOWER(TRIM(a.category)) = LOWER(TRIM(t.category))
                                AND LOWER(TRIM(a.key)) = LOWER(TRIM(t.canonical_key)))
             ORDER BY t.retired_at DESC",
        )
        .fetch_all(&self.pool)
        .await
        .unwrap_or_default();
        for (t_cat, t_key, t_val, t_at, t_reason) in tombstones {
            let reason = if t_reason == "unknown" {
                None
            } else {
                Some(t_reason)
            };
            rows.push((t_cat, t_key, t_val, t_at, reason));
        }
        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, String)> = sqlx::query_as(
            "SELECT id, category, key, source FROM facts
             WHERE superseded_at IS NULL AND archived_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_cat, 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 reason == SupersededReason::Deleted {
                let _ = self
                    .record_tombstone(&other_cat, &other_key, value, reason, &now)
                    .await;
            }
            if let Err(error) = self.project_fact_memory(id).await {
                tracing::warn!(%error, fact_id = id, "Deferred superseded-copy projection");
            }
        }
        Ok(())
    }
}

/// Write a tombstone (see `SqliteMemory::record_tombstone`) on `executor`,
/// so a write transaction can retire a fact and its tombstone together.
async fn insert_tombstone<'e, E>(
    executor: E,
    category: &str,
    key: &str,
    value: &str,
    reason: SupersededReason,
    retired_at: &str,
) -> anyhow::Result<()>
where
    E: sqlx::Executor<'e, Database = sqlx::Sqlite>,
{
    let canonical_key = canonicalize_fact_key(key);
    if canonical_key.is_empty() {
        return Ok(());
    }
    let normalized_value = crate::text::normalize_fact_value(value);
    sqlx::query(
        "INSERT INTO memory_fact_tombstones
            (category, canonical_key, normalized_value, reason, retired_at)
         VALUES (?, ?, ?, ?, ?)
         ON CONFLICT(category, canonical_key, normalized_value, reason)
         DO UPDATE SET retired_at = MAX(retired_at, excluded.retired_at)",
    )
    .bind(category.trim().to_ascii_lowercase())
    .bind(&canonical_key)
    .bind(&normalized_value)
    .bind(reason.as_str())
    .bind(retired_at)
    .execute(executor)
    .await?;
    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| (crate::text::owner_projection_family(&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 cat_lower = fact.category.trim().to_ascii_lowercase();
            let is_owner_cat = is_owner_profile_category(&cat_lower)
                || (cat_lower == "preference" && crate::text::is_owner_profile_key(&fact.key));
            let covering = is_owner_cat
                .then(|| projection_by_key.get(&crate::text::owner_projection_family(&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<()> {
        let canonical = canonicalize_fact_key(key);
        // Only classify rows still awaiting post-run provenance (`source = 'agent'`),
        // or rows being upgraded to a strictly closer rank — never downgrade an
        // already-stamped `user_stated` or `owner_quoted` fact to `derived`.
        let new_rank = fact_source_rank(source);
        let rows: Vec<(i64, String)> = sqlx::query_as(
            "SELECT id, source FROM facts
             WHERE LOWER(TRIM(category)) = LOWER(TRIM(?))
               AND (key = ? OR key = ?)
               AND superseded_at IS NULL
               AND archived_at IS NULL",
        )
        .bind(category)
        .bind(key)
        .bind(&canonical)
        .fetch_all(&self.pool)
        .await?;
        for (id, existing_source) in rows {
            if existing_source != "agent" && fact_source_rank(&existing_source) >= new_rank {
                continue;
            }
            sqlx::query(
                "UPDATE facts
                 SET source = ?,
                     first_seen_at = COALESCE(?, first_seen_at),
                     source_excerpt = COALESCE(?, source_excerpt)
                 WHERE id = ?",
            )
            .bind(source)
            .bind(first_seen_at.map(|at| at.to_rfc3339()))
            .bind(source_excerpt)
            .bind(id)
            .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?;
        // Record durable tombstones for folded rows so retention cleanup cannot
        // later reopen them to background resurrection.
        for (folded_id, _) in &folded {
            if let Some(cand) = candidates.iter().find(|c| c.id == *folded_id) {
                let _ = self
                    .record_tombstone(
                        &cand.category,
                        &cand.key,
                        &cand.value,
                        SupersededReason::Folded,
                        &now,
                    )
                    .await;
            }
            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 AND archived_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_owned = category.trim().to_ascii_lowercase();
        let category_clean = category_owned.as_str();
        let key_clean = key.trim();
        let canonical_key = canonicalize_fact_key(key_clean);

        // Find existing current fact (not superseded, not archived).
        // 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 LOWER(TRIM(category)) = ? AND key = ? AND superseded_at IS NULL AND archived_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 LOWER(TRIM(category)) = ? AND key = ? AND superseded_at IS NULL AND archived_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 LOWER(TRIM(category)) = ? AND superseded_at IS NULL AND archived_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 LOWER(TRIM(category)) = ? AND superseded_at IS NULL AND archived_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);
        // If an archived row already holds this (category, key):
        // - An automated extractor never resurrects an archived fact.
        // - An explicit owner write supersedes the archived row so the new
        //   active value inserts cleanly under `idx_facts_active_unique`.
        if existing.is_none() {
            let archived_id: Option<i64> = sqlx::query_scalar(
                "SELECT id FROM facts
                 WHERE LOWER(TRIM(category)) = ? AND key IN (?, ?)
                   AND superseded_at IS NULL AND archived_at IS NOT NULL
                 LIMIT 1",
            )
            .bind(category_clean)
            .bind(key_clean)
            .bind(&key_for_write)
            .fetch_optional(&self.pool)
            .await?;
            if let Some(archived_id) = archived_id {
                if automated_source {
                    tracing::debug!(
                        category = category_clean,
                        key = key_clean,
                        source,
                        "Automated fact write skipped: an archived fact exists for this key"
                    );
                    return Ok(());
                }
                sqlx::query(
                    "UPDATE facts SET superseded_at = ?, superseded_reason = 'replaced'
                     WHERE id = ? AND superseded_at IS NULL",
                )
                .bind(&now)
                .bind(archived_id)
                .execute(&self.pool)
                .await?;
            }
        }
        // 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 visibility
            // classes (`fold_scope_key`): an owner DM's private fact and an
            // app conversation's are one audience, a group channel its own.
            if let Some(new_vec) = embedding_blob
                .as_deref()
                .and_then(|blob| self.embedding_service.decode(blob).ok())
            {
                const ACTIVE_WITH_VECTOR: &str =
                    "SELECT id, category, key, value, source, embedding FROM facts
                     WHERE superseded_at IS NULL AND archived_at IS NULL AND embedding IS NOT NULL";
                let candidates = match super::fact_folds::fold_scope_key(&privacy_str, channel_id)
                {
                    super::fact_folds::FoldScope::OwnerPrivate => {
                        sqlx::query(sqlx::AssertSqlSafe(format!(
                            "{ACTIVE_WITH_VECTOR} AND {OWNER_PRIVATE_SCOPE_SQL}"
                        )))
                        .fetch_all(&self.pool)
                        .await?
                    }
                    super::fact_folds::FoldScope::Global => {
                        sqlx::query(sqlx::AssertSqlSafe(format!(
                            "{ACTIVE_WITH_VECTOR} AND LOWER(COALESCE(privacy, 'global')) = 'global'"
                        )))
                        .fetch_all(&self.pool)
                        .await?
                    }
                    super::fact_folds::FoldScope::Channel(channel) => {
                        sqlx::query(sqlx::AssertSqlSafe(format!(
                            "{ACTIVE_WITH_VECTOR} AND LOWER(COALESCE(privacy, 'global')) = ? AND channel_id IS ?"
                        )))
                        .bind(privacy_str.to_ascii_lowercase())
                        .bind(channel)
                        .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. A lower-
                    // or equal-rank automated restatement does NOT bump
                    // `updated_at` so background repetition cannot fake
                    // freshness or push old facts to the top of the UI.
                    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?;
                    }
                    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 {
                    // Lower-rank automated restatement: backfill a missing
                    // embedding, but do NOT bump `updated_at` so background
                    // re-extraction does not artificially renew freshness.
                    sqlx::query("UPDATE facts SET embedding = COALESCE(embedding, ?) WHERE id = ?")
                        .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 matches!(source, "agent" | "user_stated") {
            let canonical_written = canonicalize_fact_key(&key_for_write);
            let others = sqlx::query(
                "SELECT id, key, value FROM facts
                         WHERE LOWER(TRIM(category)) = ? AND superseded_at IS NULL AND archived_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, non-archived) 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 LOWER(TRIM(category)) = LOWER(TRIM(?)) AND superseded_at IS NULL AND archived_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 AND archived_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 AND archived_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));

        // Overfetch, then drop paraphrases of a fact ranked above them, so
        // copies of one preference do not fill the slots of distinct facts.
        let overfetch = max.saturating_mul(RECALL_DIVERSITY_OVERFETCH);
        let mut relevant: Vec<Fact> = Vec::with_capacity(overfetch.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() >= overfetch {
                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 relevant = self.diverse_facts(relevant, max).await;

        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 AND archived_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 overfetch = max.saturating_mul(RECALL_DIVERSITY_OVERFETCH);
        let mut relevant: Vec<Fact> = Vec::with_capacity(overfetch.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() >= overfetch {
                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(self.diverse_facts(relevant, max).await)
    }

    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 and UI under a
        // synthetic negative id; forgetting it retracts that record AND retires
        // any shadowed flat owner-profile rows for the same canonical key so
        // they cannot resurrect on the next snapshot or recall.
        if fact_id < 0 {
            let projected = self
                .canonical_personal_facts()
                .await
                .unwrap_or_default()
                .into_iter()
                .find(|fact| fact.id == fact_id);
            let retracted = self
                .retract_canonical_projection(fact_id, "owner_forget")
                .await?;
            if retracted
                && let Some(fact) = projected
                && fact.category == "user"
            {
                let now = Utc::now().to_rfc3339();
                let target_family = crate::text::owner_projection_family(&fact.key);
                let _ = self
                    .record_tombstone(
                        "user",
                        &target_family,
                        &fact.value,
                        SupersededReason::Deleted,
                        &now,
                    )
                    .await;
                let flat_rows: Vec<(i64, String, String, String)> = sqlx::query_as(
                    "SELECT id, LOWER(TRIM(category)), LOWER(TRIM(key)), value FROM facts
                     WHERE superseded_at IS NULL
                       AND LOWER(TRIM(category)) IN ('user', 'personal', 'profile', 'preference')",
                )
                .fetch_all(&self.pool)
                .await?;
                for (flat_id, flat_cat, flat_key, flat_val) in flat_rows {
                    let is_shadowed_cat = is_owner_profile_category(&flat_cat)
                        || (flat_cat == "preference"
                            && crate::text::is_owner_profile_key(&flat_key));
                    if is_shadowed_cat
                        && crate::text::owner_projection_family(&flat_key) == target_family
                    {
                        sqlx::query(
                            "UPDATE facts SET superseded_at = ?, superseded_reason = 'deleted', archived_at = NULL WHERE id = ?",
                        )
                        .bind(&now)
                        .bind(flat_id)
                        .execute(&self.pool)
                        .await?;
                        if let Err(error) = self.project_fact_memory(flat_id).await {
                            tracing::warn!(%error, fact_id = flat_id, "Deferred shadowed-fact deletion projection");
                        }
                        let _ = self
                            .record_tombstone(
                                &flat_cat,
                                &flat_key,
                                &flat_val,
                                SupersededReason::Deleted,
                                &now,
                            )
                            .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', archived_at = NULL 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 {
            let _ = self
                .record_tombstone(&category, &key, &value, SupersededReason::Deleted, &now)
                .await;
            self.supersede_copies(fact_id, &key, &value, SupersededReason::Deleted, 2)
                .await?;
            if is_owner_profile_category(&category)
                || (category == "preference" && crate::text::is_owner_profile_key(&key))
            {
                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', archived_at = NULL 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 {
            let _ = self
                .record_tombstone(&cat_clean, key, value, SupersededReason::Deleted, &now)
                .await;
            self.supersede_copies(*id, key, value, SupersededReason::Deleted, 2)
                .await?;
        }
        let canonical = (is_owner_profile_category(&cat_clean)
            || (cat_clean == "preference" && crate::text::is_owner_profile_key(&key_clean)))
            && self
                .retract_owner_profile_key(&key_clean, "owner_forget")
                .await?;
        Ok(result.rows_affected() > 0 || canonical)
    }

    async fn update_fact_value(&self, fact_id: i64, value: &str) -> anyhow::Result<Option<Fact>> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Ok(None);
        }
        if fact_id < 0 {
            return self
                .update_canonical_projection(fact_id, trimmed, "user_stated")
                .await;
        }
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let row = sqlx::query(
            "SELECT category, key FROM facts WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?;
        let Some(row) = row else {
            return Ok(None);
        };
        let category: String = row.get("category");
        let key: String = row.get("key");
        let now = Utc::now().to_rfc3339();
        let fact_text = build_fact_embedding_text(&category, &key, trimmed);
        let embedding_blob = self
            .embedding_service
            .embed(fact_text)
            .await
            .ok()
            .map(|v| encode_embedding(&v));
        sqlx::query(
            "UPDATE facts
             SET value = ?, source = 'user_stated', updated_at = ?,
                 embedding = COALESCE(?, embedding)
             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(trimmed)
        .bind(&now)
        .bind(&embedding_blob)
        .bind(fact_id)
        .execute(&self.pool)
        .await?;
        if let Err(error) = self.project_fact_memory(fact_id).await {
            tracing::warn!(%error, fact_id, "Deferred edited-fact projection");
        }
        let updated = 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 id = ?",
        )
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?;
        Ok(updated.as_ref().map(Self::row_to_fact))
    }

    async fn archive_fact(&self, fact_id: i64) -> anyhow::Result<bool> {
        if fact_id < 0 {
            return Ok(false);
        }
        let now = Utc::now().to_rfc3339();
        let res = sqlx::query(
            "UPDATE facts SET archived_at = ?
             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(&now)
        .bind(fact_id)
        .execute(&self.pool)
        .await?;
        if res.rows_affected() > 0 {
            // Invalidate the archived fact's claim projection, embedding, and graph edges.
            if let Err(error) = self.project_fact_memory(fact_id).await {
                tracing::warn!(%error, fact_id, "Deferred archived-fact projection");
            }
            return Ok(true);
        }
        Ok(false)
    }

    async fn restore_fact(&self, fact_id: i64) -> anyhow::Result<Option<Fact>> {
        if fact_id < 0 {
            return Ok(None);
        }
        let now = Utc::now().to_rfc3339();
        let res = sqlx::query(
            "UPDATE facts SET archived_at = NULL, expires_at = NULL, updated_at = ?
             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NOT NULL",
        )
        .bind(&now)
        .bind(fact_id)
        .execute(&self.pool)
        .await?;
        if res.rows_affected() == 0 {
            return Ok(None);
        }
        if let Err(error) = self.project_fact_memory(fact_id).await {
            tracing::warn!(%error, fact_id, "Deferred restored-fact projection");
        }
        let restored = 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 id = ?",
        )
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?;
        Ok(restored.as_ref().map(Self::row_to_fact))
    }

    async fn get_archived_facts(&self, limit: usize) -> 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 AND archived_at IS NOT NULL
             ORDER BY archived_at DESC
             LIMIT ?",
        )
        .bind(limit.min(500) as i64)
        .fetch_all(&self.pool)
        .await?;
        Ok(rows.iter().map(Self::row_to_fact).collect())
    }

    async fn archive_expired_facts(&self, now: DateTime<Utc>) -> anyhow::Result<u64> {
        let now_str = now.to_rfc3339();
        let expired: Vec<i64> = sqlx::query_scalar(
            "SELECT id FROM facts
             WHERE superseded_at IS NULL AND archived_at IS NULL
               AND expires_at IS NOT NULL AND expires_at <= ?",
        )
        .bind(&now_str)
        .fetch_all(&self.pool)
        .await?;
        if expired.is_empty() {
            return Ok(0);
        }
        let mut count = 0u64;
        for id in expired {
            if self.archive_fact(id).await? {
                count += 1;
            }
        }
        if count > 0 {
            tracing::info!(count, "Archived expired facts");
        }
        Ok(count)
    }

    async fn detect_fact_overlaps(&self) -> anyhow::Result<std::collections::HashMap<i64, i64>> {
        let mut candidates = self.fold_candidates().await?;
        // Include canonical owner facts so flat duplicates (e.g. preference/address_as)
        // can be flagged against canonical user/preferred_name, and drop flat rows
        // already shadowed by canonical owner facts so overlap pointers always
        // reference visible items.
        let canonical = self.canonical_personal_facts().await.unwrap_or_default();
        let canonical_owner_keys: std::collections::HashSet<String> = canonical
            .iter()
            .filter(|f| f.category == "user")
            .map(|f| crate::text::owner_projection_family(&f.key))
            .collect();
        candidates.retain(|c| {
            let cat = c.category.trim().to_ascii_lowercase();
            let shadowed_owner = (is_owner_profile_category(&cat)
                || (cat == "preference" && crate::text::is_owner_profile_key(&c.key)))
                && canonical_owner_keys.contains(&crate::text::owner_projection_family(&c.key));
            !shadowed_owner
        });
        for fact in canonical.into_iter().filter(|f| f.category == "user") {
            candidates.push(super::fact_folds::FoldCandidate {
                id: fact.id,
                pinned: true,
                category: fact.category,
                key: fact.key,
                value: fact.value,
                source_rank: fact_source_rank(&fact.source),
                recall_count: fact.recall_count as i64,
                privacy: fact.privacy.to_string(),
                channel_id: fact.channel_id,
                vector: Vec::new(),
            });
        }
        let hashes: std::collections::HashMap<i64, String> = candidates
            .iter()
            .map(|c| (c.id, overlap_content_hash(&c.category, &c.key, &c.value)))
            .collect();
        let distinct = self
            .valid_distinct_pairs(&hashes)
            .await
            .unwrap_or_else(|error| {
                tracing::warn!(%error, "could not read overlap reviews");
                Default::default()
            });
        Ok(super::fact_folds::detect_overlaps_excluding(
            &mut candidates,
            &distinct,
        ))
    }

    async fn resolve_numeric_fact_conflicts(&self) -> anyhow::Result<usize> {
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let candidates = self.conflict_candidates().await?;
        let conflicts = super::fact_folds::plan_numeric_conflicts(&candidates);
        let retirements = super::fact_folds::numeric_conflict_retirements(&conflicts);
        if retirements.is_empty() {
            return Ok(0);
        }
        let by_id: std::collections::HashMap<i64, &super::fact_folds::ConflictCandidate> =
            candidates.iter().map(|c| (c.id, c)).collect();
        let now = Utc::now().to_rfc3339();
        let mut retired = Vec::new();
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        for (loser, winner) in &retirements {
            // Both still active: a write since the read may have changed them.
            let done = sqlx::query(
                "UPDATE facts SET superseded_at = ?, superseded_reason = ?, folded_into = ?
                 WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL
                   AND EXISTS (SELECT 1 FROM facts w WHERE w.id = ?
                               AND w.superseded_at IS NULL AND w.archived_at IS NULL)",
            )
            .bind(&now)
            .bind(SupersededReason::Replaced.as_str())
            .bind(winner)
            .bind(loser)
            .bind(winner)
            .execute(&mut *tx)
            .await?
            .rows_affected()
                > 0;
            if !done {
                continue;
            }
            if let Some(row) = by_id.get(loser) {
                insert_tombstone(
                    &mut *tx,
                    &row.category,
                    &row.key,
                    &row.value,
                    SupersededReason::Replaced,
                    &now,
                )
                .await?;
            }
            retired.push(*loser);
        }
        tx.commit().await?;
        for id in &retired {
            if let Err(error) = self.project_fact_memory(*id).await {
                tracing::warn!(%error, fact_id = id, "Deferred conflict-retired projection");
            }
        }
        if !retired.is_empty() {
            tracing::info!(
                retired = retired.len(),
                unresolved = conflicts
                    .iter()
                    .filter(|c| !matches!(
                        c.verdict,
                        super::fact_folds::ConflictVerdict::Resolved { .. }
                    ))
                    .count(),
                "Retired superseded numeric fact values"
            );
        }
        Ok(retired.len())
    }

    async fn archive_unused_automated_facts(
        &self,
        now: DateTime<Utc>,
        min_idle_days: i64,
    ) -> anyhow::Result<u64> {
        if min_idle_days <= 0 {
            return Ok(0);
        }
        let cutoff = (now - chrono::Duration::days(min_idle_days)).to_rfc3339();
        let identity = crate::full::recall::IDENTITY_CATEGORIES;
        let filter = format!(
            "superseded_at IS NULL AND archived_at IS NULL
               AND source IN ({sources})
               AND LOWER(TRIM(category)) NOT IN ({categories})
               AND COALESCE(recall_count, 0) = 0 AND last_recalled_at IS NULL
               AND updated_at < ?",
            sources = vec!["?"; UNUSED_ARCHIVABLE_SOURCES.len()].join(", "),
            categories = vec!["?"; identity.len()].join(", "),
        );
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let select = format!("SELECT id FROM facts WHERE {filter}");
        let mut query = sqlx::query_scalar::<_, i64>(sqlx::AssertSqlSafe(select));
        for value in UNUSED_ARCHIVABLE_SOURCES.iter().chain(identity) {
            query = query.bind(*value);
        }
        let ids: Vec<i64> = query.bind(&cutoff).fetch_all(&mut *tx).await?;
        if ids.is_empty() {
            return Ok(0);
        }
        let update = format!("UPDATE facts SET archived_at = ? WHERE {filter}");
        let mut query = sqlx::query(sqlx::AssertSqlSafe(update)).bind(now.to_rfc3339());
        for value in UNUSED_ARCHIVABLE_SOURCES.iter().chain(identity) {
            query = query.bind(*value);
        }
        let archived = query.bind(&cutoff).execute(&mut *tx).await?.rows_affected();
        tx.commit().await?;
        for id in ids {
            if let Err(error) = self.project_fact_memory(id).await {
                tracing::warn!(%error, fact_id = id, "Deferred unused-fact archive projection");
            }
        }
        if archived > 0 {
            tracing::info!(archived, min_idle_days, "Archived unused automated facts");
        }
        Ok(archived)
    }

    async fn fold_fact_into(&self, folded_id: i64, kept_id: i64) -> anyhow::Result<bool> {
        self.fold_fact_pair(folded_id, kept_id, true).await
    }

    async fn owner_fold_fact_into(&self, folded_id: i64, kept_id: i64) -> anyhow::Result<bool> {
        self.fold_fact_pair(folded_id, kept_id, false).await
    }

    async fn confirm_fact(&self, fact_id: i64) -> anyhow::Result<Option<Fact>> {
        if fact_id <= 0 {
            return Ok(None);
        }
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let exists: Option<i64> = sqlx::query_scalar(
            "SELECT id FROM facts
             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(fact_id)
        .fetch_optional(&mut *tx)
        .await?;
        if exists.is_none() {
            return Ok(None);
        }
        sqlx::query(
            "UPDATE facts SET source = 'user_stated', updated_at = ?
             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(Utc::now().to_rfc3339())
        .bind(fact_id)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        if let Err(error) = self.project_fact_memory(fact_id).await {
            tracing::warn!(%error, fact_id, "Deferred confirmed-fact projection");
        }
        self.get_fact_by_id(fact_id).await
    }

    async fn unfold_fact(&self, folded_id: i64) -> anyhow::Result<Option<Fact>> {
        if folded_id <= 0 {
            return Ok(None);
        }
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let row: Option<(String, String, String)> = sqlx::query_as(
            "SELECT category, key, value FROM facts
             WHERE id = ? AND superseded_at IS NOT NULL AND superseded_reason = ?",
        )
        .bind(folded_id)
        .bind(SupersededReason::Folded.as_str())
        .fetch_optional(&mut *tx)
        .await?;
        let Some((category, key, value)) = row else {
            return Ok(None);
        };
        // Another active row holds the key: restoring would make two.
        let occupied: Option<i64> = sqlx::query_scalar(
            "SELECT id FROM facts
             WHERE LOWER(TRIM(category)) = LOWER(TRIM(?)) AND LOWER(TRIM(key)) = LOWER(TRIM(?))
               AND superseded_at IS NULL LIMIT 1",
        )
        .bind(&category)
        .bind(&key)
        .fetch_optional(&mut *tx)
        .await?;
        if occupied.is_some() {
            return Ok(None);
        }
        sqlx::query(
            "UPDATE facts SET superseded_at = NULL, superseded_reason = NULL, folded_into = NULL
             WHERE id = ?",
        )
        .bind(folded_id)
        .execute(&mut *tx)
        .await?;
        sqlx::query(
            "DELETE FROM memory_fact_tombstones
             WHERE category = ? AND canonical_key = ? AND normalized_value = ? AND reason = ?",
        )
        .bind(category.trim().to_ascii_lowercase())
        .bind(canonicalize_fact_key(&key))
        .bind(crate::text::normalize_fact_value(&value))
        .bind(SupersededReason::Folded.as_str())
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        if let Err(error) = self.project_fact_memory(folded_id).await {
            tracing::warn!(%error, fact_id = folded_id, "Deferred unfolded-fact projection");
        }
        self.get_fact_by_id(folded_id).await
    }

    async fn refine_automated_fact_value(
        &self,
        fact_id: i64,
        new_value: &str,
    ) -> anyhow::Result<Option<Fact>> {
        let new_value = new_value.trim();
        if fact_id <= 0 || new_value.is_empty() {
            return Ok(None);
        }
        // Read metadata and embed BEFORE acquiring the upsert lock so slow
        // embedding never blocks concurrent writes; rank is re-verified inside
        // the BEGIN IMMEDIATE transaction below.
        let row: Option<(String, String, String)> = sqlx::query_as(
            "SELECT category, key, source FROM facts
             WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?;
        let Some((category, key, source)) = row else {
            return Ok(None);
        };
        // Only rank-0 automated facts may be rewritten: rank-1 owner_quoted
        // facts keep their verbatim owner-quoted wording and rank-2 facts are
        // owner-authored.
        if fact_source_rank(&source) > 0 {
            return Ok(None);
        }
        let embedding = self
            .embedding_service
            .embed(build_fact_embedding_text(&category, &key, new_value))
            .await
            .ok()
            .map(|vector| encode_embedding(&vector));
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        // The source may have been raised since the initial read.
        let source: Option<String> = sqlx::query_scalar(
            "SELECT source FROM facts WHERE id = ? AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(fact_id)
        .fetch_optional(&mut *tx)
        .await?;
        if source.as_deref().is_none_or(|s| fact_source_rank(s) > 0) {
            return Ok(None);
        }
        // A vector of the old value would no longer match: none is better.
        sqlx::query("UPDATE facts SET value = ?, embedding = ?, updated_at = ? WHERE id = ?")
            .bind(new_value)
            .bind(&embedding)
            .bind(Utc::now().to_rfc3339())
            .bind(fact_id)
            .execute(&mut *tx)
            .await?;
        tx.commit().await?;
        if let Err(error) = self.project_fact_memory(fact_id).await {
            tracing::warn!(%error, fact_id, "Deferred refined-fact projection");
        }
        self.get_fact_by_id(fact_id).await
    }

    async fn record_overlap_review(
        &self,
        fact_a_id: i64,
        fact_b_id: i64,
        verdict: crate::stores::OverlapReviewVerdict,
        reviewer: &str,
    ) -> anyhow::Result<()> {
        anyhow::ensure!(fact_a_id != fact_b_id, "an overlap review needs two facts");
        let (a, b) = super::fact_folds::overlap_pair(fact_a_id, fact_b_id);
        let (Some(hash_a), Some(hash_b)) = (
            self.fact_content_hash(a).await?,
            self.fact_content_hash(b).await?,
        ) else {
            anyhow::bail!("overlap review: fact {a} or {b} is not an active fact");
        };
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        sqlx::query(
            "INSERT INTO memory_overlap_reviews
                (fact_a_id, fact_b_id, hash_a, hash_b, verdict, reviewed_at, reviewer)
             VALUES (?, ?, ?, ?, ?, ?, ?)
             ON CONFLICT(fact_a_id, fact_b_id) DO UPDATE SET
                hash_a = excluded.hash_a, hash_b = excluded.hash_b,
                verdict = excluded.verdict, reviewed_at = excluded.reviewed_at,
                reviewer = excluded.reviewer",
        )
        .bind(a)
        .bind(b)
        .bind(&hash_a)
        .bind(&hash_b)
        .bind(verdict.as_str())
        .bind(Utc::now().to_rfc3339())
        .bind(reviewer)
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(())
    }

    async fn has_valid_overlap_review(
        &self,
        fact_a_id: i64,
        fact_b_id: i64,
    ) -> anyhow::Result<Option<crate::stores::OverlapReviewVerdict>> {
        let (a, b) = super::fact_folds::overlap_pair(fact_a_id, fact_b_id);
        let row: Option<(String, String, String)> = sqlx::query_as(
            "SELECT hash_a, hash_b, verdict FROM memory_overlap_reviews
             WHERE fact_a_id = ? AND fact_b_id = ?",
        )
        .bind(a)
        .bind(b)
        .fetch_optional(&self.pool)
        .await?;
        let Some((hash_a, hash_b, verdict)) = row else {
            return Ok(None);
        };
        let current_a = self.fact_content_hash(a).await?;
        let current_b = self.fact_content_hash(b).await?;
        if current_a.as_deref() != Some(hash_a.as_str())
            || current_b.as_deref() != Some(hash_b.as_str())
        {
            return Ok(None);
        }
        Ok(crate::stores::OverlapReviewVerdict::parse(&verdict))
    }

    async fn fact_exists(&self, fact_id: i64) -> anyhow::Result<bool> {
        if fact_id < 0 {
            return Ok(self.get_fact_by_id(fact_id).await?.is_some());
        }
        Ok(sqlx::query_scalar::<_, i64>(
            "SELECT 1 FROM facts WHERE id = ? AND superseded_at IS NULL",
        )
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?
        .is_some())
    }

    async fn get_fact_by_id(&self, fact_id: i64) -> anyhow::Result<Option<Fact>> {
        if fact_id < 0 {
            return Ok(self
                .canonical_personal_facts()
                .await?
                .into_iter()
                .find(|fact| fact.id == fact_id));
        }
        let row = sqlx::query(sqlx::AssertSqlSafe(format!(
            "SELECT {FACT_COLUMNS} FROM facts WHERE id = ? AND superseded_at IS NULL"
        )))
        .bind(fact_id)
        .fetch_optional(&self.pool)
        .await?;
        Ok(row.as_ref().map(Self::row_to_fact))
    }

    async fn job_last_run_at(&self, job_name: &str) -> anyhow::Result<Option<DateTime<Utc>>> {
        let at: Option<String> =
            sqlx::query_scalar("SELECT last_run_at FROM memory_job_watermarks WHERE job_name = ?")
                .bind(job_name)
                .fetch_optional(&self.pool)
                .await?;
        Ok(at.as_deref().and_then(crate::types::parse_ts))
    }

    async fn record_job_run_at(&self, job_name: &str, at: DateTime<Utc>) -> anyhow::Result<()> {
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        sqlx::query(
            "INSERT INTO memory_job_watermarks (job_name, last_run_at) VALUES (?, ?)
             ON CONFLICT(job_name) DO UPDATE SET last_run_at = excluded.last_run_at",
        )
        .bind(job_name)
        .bind(at.to_rfc3339())
        .execute(&mut *tx)
        .await?;
        tx.commit().await?;
        Ok(())
    }

    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 AND archived_at IS NULL ORDER BY category, key"
        )
        .fetch_all(&self.pool)
        .await?;

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

/// SQL for [`super::fact_folds::FoldScope::OwnerPrivate`] rows: private, or
/// a channel fact from an owner app conversation (`app:` prefix, compared
/// case-sensitively like `fold_scope_key`).
const OWNER_PRIVATE_SCOPE_SQL: &str = "(LOWER(COALESCE(privacy, 'global')) = 'private'
      OR (LOWER(COALESCE(privacy, 'global')) = 'channel' AND substr(channel_id, 1, 4) = 'app:'))";

/// Columns `SqliteMemory::row_to_fact` reads.
const FACT_COLUMNS: &str = "id, category, key, value, source, created_at, updated_at, superseded_at, recall_count, last_recalled_at, channel_id, privacy, first_seen_at, source_excerpt";

/// Sources of background extractors, whose facts nobody stated: the only
/// facts maintenance may archive for disuse. Owner-stated (`agent`,
/// `user_stated`...) and quoted (`owner_quoted`) facts are never listed.
const UNUSED_ARCHIVABLE_SOURCES: &[&str] = &[
    "consolidation",
    "inferred",
    "derived",
    "progressive",
    "task_learning",
];

/// Similarity at which a lower-ranked recall candidate in the same category
/// adds nothing beside a fact already picked: paraphrases of one preference
/// score alike and would otherwise fill neighbouring recall slots.
pub(crate) const RECALL_DIVERSITY_MAX_SIMILARITY: f32 = 0.88;

/// How many ranked candidates per recall slot the diversity pass looks at.
const RECALL_DIVERSITY_OVERFETCH: usize = 3;

/// Keep `ranked` items in order, skipping any whose vector is at least
/// [`RECALL_DIVERSITY_MAX_SIMILARITY`] similar to an item already kept in the
/// same category, until `max` are kept. Items without a vector are never
/// skipped. Each item is `(value, normalized category, vector)`.
pub(crate) fn select_diverse<T>(
    ranked: impl IntoIterator<Item = (T, String, Option<Vec<f32>>)>,
    max: usize,
) -> Vec<T> {
    let mut kept: Vec<(String, Option<Vec<f32>>)> = Vec::new();
    let mut out = Vec::new();
    for (item, category, vector) in ranked {
        if out.len() >= max {
            break;
        }
        let redundant = vector.as_ref().is_some_and(|vector| {
            kept.iter().any(|(other_category, other)| {
                *other_category == category
                    && other.as_ref().is_some_and(|other| {
                        other.len() == vector.len()
                            && cosine_similarity(vector, other) >= RECALL_DIVERSITY_MAX_SIMILARITY
                    })
            })
        });
        if redundant {
            continue;
        }
        kept.push((category, vector));
        out.push(item);
    }
    out
}

/// The content an overlap verdict is bound to: category and key as the
/// fact is filed, and its exact value.
pub(crate) fn overlap_content_hash(category: &str, key: &str, value: &str) -> String {
    crate::embedding_index::content_hash(&format!(
        "{}\u{1f}{}\u{1f}{}",
        category.trim().to_ascii_lowercase(),
        key.trim().to_ascii_lowercase(),
        value.trim()
    ))
}

impl SqliteMemory {
    /// Fold `folded_id` into `kept_id` inside `BEGIN IMMEDIATE`. When
    /// `enforce_automated_guards` is true, also enforces the background hygiene
    /// safety rails (never fold owner-stated facts, never fold higher rank into
    /// lower rank, never hide from an audience, never unpin identity facts).
    async fn fold_fact_pair(
        &self,
        folded_id: i64,
        kept_id: i64,
        enforce_rank_guards: bool,
    ) -> anyhow::Result<bool> {
        type FoldPairRow = (i64, String, String, String, String, String, Option<String>);
        if folded_id <= 0 || kept_id <= 0 || folded_id == kept_id {
            return Ok(false);
        }
        let _upsert_guard = self.fact_upsert_lock.lock().await;
        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
        let rows: Vec<FoldPairRow> = sqlx::query_as(
            "SELECT id, category, key, value, source, COALESCE(privacy, 'global'), channel_id
             FROM facts
             WHERE id IN (?, ?) AND superseded_at IS NULL AND archived_at IS NULL",
        )
        .bind(folded_id)
        .bind(kept_id)
        .fetch_all(&mut *tx)
        .await?;
        let (Some(folded), Some(kept)) = (
            rows.iter().find(|row| row.0 == folded_id),
            rows.iter().find(|row| row.0 == kept_id),
        ) else {
            return Ok(false);
        };
        let (folded_rank, kept_rank) = (fact_source_rank(&folded.4), fact_source_rank(&kept.4));
        if enforce_rank_guards && (folded_rank >= 2 || folded_rank > kept_rank) {
            return Ok(false);
        }
        // Scope and identity-pin guards apply to both automated and owner
        // merges so folding never silently hides a group-channel fact or
        // unpins an identity fact.
        let folded_scope = super::fact_folds::fold_scope_key(&folded.5, folded.6.as_deref());
        let kept_scope = super::fact_folds::fold_scope_key(&kept.5, kept.6.as_deref());
        if !kept_scope.can_keep(&folded_scope) {
            return Ok(false);
        }
        let pinned = |category: &str| {
            crate::full::recall::IDENTITY_CATEGORIES
                .contains(&category.trim().to_ascii_lowercase().as_str())
        };
        if pinned(&folded.1) && !pinned(&kept.1) {
            return Ok(false);
        }
        let now = Utc::now().to_rfc3339();
        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?;
        // An explicit owner merge confirms the surviving row as owner-verified
        // when it was automated, so owner-reviewed knowledge isn't archived
        // later by the unused-automated rule.
        if !enforce_rank_guards && kept_rank < 2 {
            sqlx::query(
                "UPDATE facts
                 SET recall_count = MAX(COALESCE(recall_count, 0),
                         (SELECT COALESCE(recall_count, 0) FROM facts WHERE id = ?)),
                     source = 'user_stated',
                     updated_at = ?
                 WHERE id = ?",
            )
            .bind(folded_id)
            .bind(&now)
            .bind(kept_id)
            .execute(&mut *tx)
            .await?;
        } else {
            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?;
        }
        insert_tombstone(
            &mut *tx,
            &folded.1,
            &folded.2,
            &folded.3,
            SupersededReason::Folded,
            &now,
        )
        .await?;
        sqlx::query("DELETE FROM memory_overlap_reviews WHERE fact_a_id = ? OR fact_b_id = ?")
            .bind(folded_id)
            .bind(folded_id)
            .execute(&mut *tx)
            .await?;
        tx.commit().await?;
        if let Err(error) = self.project_fact_memory(folded_id).await {
            tracing::warn!(%error, fact_id = folded_id, "Deferred folded-fact projection");
        }
        Ok(true)
    }

    /// Stored full-fact vectors of `ids`, read in chunks.
    async fn fact_vectors(&self, ids: &[i64]) -> std::collections::HashMap<i64, Vec<f32>> {
        let mut vectors = std::collections::HashMap::new();
        let ids: Vec<i64> = ids.iter().copied().filter(|id| *id > 0).collect();
        for chunk in ids.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 diversity");
                    return vectors;
                }
            };
            for row in rows {
                let blob: Vec<u8> = row.get("embedding");
                if let Ok(vector) = self.embedding_service.decode(&blob) {
                    vectors.insert(row.get("id"), vector);
                }
            }
        }
        vectors
    }

    /// The first `max` of `ranked` (best first) that are not paraphrases of
    /// a fact ranked above them ([`select_diverse`]).
    async fn diverse_facts(&self, ranked: Vec<Fact>, max: usize) -> Vec<Fact> {
        if ranked.len() <= 1 {
            return ranked.into_iter().take(max).collect();
        }
        let ids: Vec<i64> = ranked.iter().map(|fact| fact.id).collect();
        let mut vectors = self.fact_vectors(&ids).await;
        select_diverse(
            ranked.into_iter().map(|fact| {
                let category = fact.category.trim().to_ascii_lowercase();
                let vector = vectors.remove(&fact.id);
                (fact, category, vector)
            }),
            max,
        )
    }

    /// Every active fact with a vector, as the numeric-conflict planner
    /// reads it.
    pub async fn conflict_candidates(
        &self,
    ) -> anyhow::Result<Vec<super::fact_folds::ConflictCandidate>> {
        let rows = sqlx::query(
            "SELECT id, category, key, value, source, COALESCE(first_seen_at, updated_at) AS seen,
                    COALESCE(privacy, 'global') AS privacy, channel_id, embedding
             FROM facts
             WHERE superseded_at IS NULL AND archived_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 source: String = row.get("source");
                let seen: Option<String> = row.get("seen");
                Some(super::fact_folds::ConflictCandidate {
                    id: row.get("id"),
                    category: row.get("category"),
                    key: row.get("key"),
                    value: row.get("value"),
                    source_rank: fact_source_rank(&source),
                    seen: seen
                        .as_deref()
                        .and_then(super::fact_folds::parse_fact_timestamp),
                    privacy: row.get("privacy"),
                    channel_id: row.get("channel_id"),
                    vector,
                })
            })
            .collect())
    }

    /// The overlap-review content hash of a fact that is not retired: a
    /// flat row by positive id, a canonical projection by negative id.
    async fn fact_content_hash(&self, fact_id: i64) -> anyhow::Result<Option<String>> {
        Ok(self
            .get_fact_by_id(fact_id)
            .await?
            .map(|fact| overlap_content_hash(&fact.category, &fact.key, &fact.value)))
    }

    /// Pairs a reviewer judged distinct whose facts still hold the content
    /// they were judged on. `hashes` maps fact id to its current content
    /// hash; a pair with a side missing from it is not returned.
    async fn valid_distinct_pairs(
        &self,
        hashes: &std::collections::HashMap<i64, String>,
    ) -> anyhow::Result<std::collections::HashSet<(i64, i64)>> {
        let rows: Vec<(i64, i64, String, String)> = sqlx::query_as(
            "SELECT fact_a_id, fact_b_id, hash_a, hash_b FROM memory_overlap_reviews
             WHERE verdict = ?",
        )
        .bind(crate::stores::OverlapReviewVerdict::Distinct.as_str())
        .fetch_all(&self.pool)
        .await?;
        Ok(rows
            .into_iter()
            .filter(|(a, b, hash_a, hash_b)| {
                hashes.get(a) == Some(hash_a) && hashes.get(b) == Some(hash_b)
            })
            .map(|(a, b, _, _)| super::fact_folds::overlap_pair(a, b))
            .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")
}

#[cfg(test)]
mod hygiene_tests {
    use std::sync::Arc;

    use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};

    use super::super::{EMBEDDING_DIM, migrate};
    use super::*;
    use crate::HashEmbedder;
    use crate::stores::{DecayPolicy, OverlapReviewVerdict};

    async fn open() -> (SqliteMemory, tempfile::NamedTempFile) {
        let file = tempfile::NamedTempFile::new().unwrap();
        let options = SqliteConnectOptions::new()
            .filename(file.path())
            .synchronous(sqlx::sqlite::SqliteSynchronous::Off);
        let pool = SqlitePoolOptions::new()
            .max_connections(2)
            .connect_with(options)
            .await
            .unwrap();
        migrate(&pool).await.unwrap();
        let memory = SqliteMemory::new(pool, Arc::new(HashEmbedder::new(EMBEDDING_DIM)));
        (memory, file)
    }

    /// Unit vector along `axis`, tilted toward `axis + 1` so that its
    /// cosine with the plain axis is `cos`.
    fn tilted(axis: usize, cos: f32) -> Vec<f32> {
        let mut v = vec![0.0; EMBEDDING_DIM];
        v[axis] = cos;
        v[axis + 1] = (1.0 - cos * cos).sqrt();
        v
    }

    struct Row<'a> {
        category: &'a str,
        key: &'a str,
        value: &'a str,
        source: &'a str,
        privacy: &'a str,
        channel: Option<&'a str>,
        vector: Vec<f32>,
        recall: i64,
        age_days: i64,
    }

    impl<'a> Row<'a> {
        fn new(category: &'a str, key: &'a str, value: &'a str, vector: Vec<f32>) -> Self {
            Self {
                category,
                key,
                value,
                source: "consolidation",
                privacy: "private",
                channel: None,
                vector,
                recall: 0,
                age_days: 0,
            }
        }
    }

    /// A fact row written directly, with exactly the vector given.
    async fn insert(memory: &SqliteMemory, row: Row<'_>) -> i64 {
        let at = (Utc::now() - chrono::Duration::days(row.age_days)).to_rfc3339();
        sqlx::query(
            "INSERT INTO facts (category, key, value, source, created_at, updated_at, recall_count,
                                channel_id, privacy, embedding, first_seen_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(row.category)
        .bind(row.key)
        .bind(row.value)
        .bind(row.source)
        .bind(&at)
        .bind(&at)
        .bind(row.recall)
        .bind(row.channel)
        .bind(row.privacy)
        .bind(encode_embedding(&row.vector))
        .bind(&at)
        .execute(memory.pool())
        .await
        .unwrap()
        .last_insert_rowid()
    }

    async fn status(memory: &SqliteMemory, id: i64) -> (Option<String>, Option<i64>) {
        sqlx::query_as("SELECT superseded_reason, folded_into FROM facts WHERE id = ?")
            .bind(id)
            .fetch_one(memory.pool())
            .await
            .unwrap()
    }

    async fn tombstones(memory: &SqliteMemory, reason: &str) -> i64 {
        sqlx::query_scalar("SELECT COUNT(*) FROM memory_fact_tombstones WHERE reason = ?")
            .bind(reason)
            .fetch_one(memory.pool())
            .await
            .unwrap()
    }

    async fn active_count(memory: &SqliteMemory) -> usize {
        memory.get_facts(None).await.unwrap().len()
    }

    #[tokio::test]
    async fn app_conversation_facts_and_private_facts_fold_as_one_audience() {
        let (memory, _file) = open().await;
        let v = tilted(0, 1.0);
        let value = "short answers with code first";
        let a = insert(
            &memory,
            Row {
                privacy: "channel",
                channel: Some("app:synthetic-conv-1"),
                ..Row::new("preference", "reply_style", value, v.clone())
            },
        )
        .await;
        let b = insert(
            &memory,
            Row {
                privacy: "channel",
                channel: Some("app:synthetic-conv-2"),
                ..Row::new("preference", "answer_style", value, v.clone())
            },
        )
        .await;
        let c = insert(
            &memory,
            Row::new("preference", "response_format", value, v.clone()),
        )
        .await;
        // A group channel and a global copy never merge with the owner's.
        let group = insert(
            &memory,
            Row {
                privacy: "channel",
                channel: Some("slack:synthetic-team"),
                ..Row::new("preference", "team_reply_style", value, v.clone())
            },
        )
        .await;
        let global = insert(
            &memory,
            Row {
                privacy: "global",
                ..Row::new("preference", "global_reply_style", value, v.clone())
            },
        )
        .await;
        assert_eq!(memory.fold_restated_facts().await.unwrap(), 2);
        assert_eq!(status(&memory, a).await, (None, None));
        assert_eq!(status(&memory, b).await, (Some("folded".into()), Some(a)));
        assert_eq!(status(&memory, c).await, (Some("folded".into()), Some(a)));
        assert_eq!(status(&memory, group).await, (None, None));
        assert_eq!(status(&memory, global).await, (None, None));
    }

    #[tokio::test]
    async fn write_time_dedup_treats_app_conversations_as_the_owners_scope() {
        let (memory, _file) = open().await;
        let value = "prefers concise replies with the code first";
        memory
            .upsert_fact(
                "preference",
                "reply_style",
                value,
                "consolidation",
                Some("app:synthetic-conv-1"),
                FactPrivacy::Channel,
            )
            .await
            .unwrap();
        // The same value under a reworded key, from another app
        // conversation and from an owner DM: one fact.
        for (key, channel, privacy) in [
            (
                "reply_style_preference",
                Some("app:synthetic-conv-2"),
                FactPrivacy::Channel,
            ),
            ("preferred_reply_style", None, FactPrivacy::Private),
        ] {
            memory
                .upsert_fact("preference", key, value, "consolidation", channel, privacy)
                .await
                .unwrap();
        }
        assert_eq!(active_count(&memory).await, 1);
        // A group channel keeps its own copy.
        memory
            .upsert_fact(
                "preference",
                "reply_style_preference",
                value,
                "consolidation",
                Some("slack:synthetic-team"),
                FactPrivacy::Channel,
            )
            .await
            .unwrap();
        assert_eq!(active_count(&memory).await, 2);
    }

    #[tokio::test]
    async fn numeric_conflicts_retire_only_what_a_closer_or_newer_source_replaced() {
        let (memory, _file) = open().await;
        // Owner-stated beats inferred.
        let owner = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new("project", "api_port", "port 8080", tilted(0, 1.0))
            },
        )
        .await;
        let inferred = insert(
            &memory,
            Row::new("project", "default_api_port", "port 9090", tilted(0, 0.95)),
        )
        .await;
        // Two automated values of one attribute: the one seen later wins.
        let older = insert(
            &memory,
            Row {
                age_days: 30,
                ..Row::new("technical", "node_version", "Node 18", tilted(4, 1.0))
            },
        )
        .await;
        let newer = insert(
            &memory,
            Row::new(
                "technical",
                "current_node_version",
                "Node 20",
                tilted(4, 0.95),
            ),
        )
        .await;
        // Keys that may name two attributes: kept.
        let release = insert(
            &memory,
            Row::new("project", "release_version", "1.2", tilted(8, 1.0)),
        )
        .await;
        let build = insert(
            &memory,
            Row::new("project", "build_version", "3.4", tilted(8, 0.95)),
        )
        .await;
        // Two owner-stated values: only the owner can say.
        let stated_a = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new("project", "deadline_day", "day 12", tilted(12, 1.0))
            },
        )
        .await;
        let stated_b = insert(
            &memory,
            Row {
                source: "agent",
                ..Row::new("project", "deadline", "day 14", tilted(12, 0.95))
            },
        )
        .await;
        // Another scope never conflicts.
        let group = insert(
            &memory,
            Row {
                privacy: "channel",
                channel: Some("slack:synthetic-team"),
                ..Row::new("project", "api_port_value", "port 7070", tilted(0, 0.97))
            },
        )
        .await;

        assert_eq!(memory.resolve_numeric_fact_conflicts().await.unwrap(), 2);
        assert_eq!(
            status(&memory, inferred).await,
            (Some("replaced".into()), Some(owner))
        );
        assert_eq!(
            status(&memory, older).await,
            (Some("replaced".into()), Some(newer))
        );
        for id in [owner, newer, release, build, stated_a, stated_b, group] {
            assert_eq!(status(&memory, id).await, (None, None), "#{id}");
        }
        assert_eq!(tombstones(&memory, "replaced").await, 2);
        // Idempotent.
        assert_eq!(memory.resolve_numeric_fact_conflicts().await.unwrap(), 0);
    }

    #[tokio::test]
    async fn fold_and_unfold_round_trip() {
        let (memory, _file) = open().await;
        let kept = insert(
            &memory,
            Row {
                recall: 1,
                ..Row::new(
                    "preference",
                    "editor",
                    "Helix with relative line numbers",
                    tilted(0, 1.0),
                )
            },
        )
        .await;
        let folded = insert(
            &memory,
            Row {
                recall: 7,
                ..Row::new(
                    "preference",
                    "editor_setup",
                    "Uses Helix, relative numbers on",
                    tilted(0, 0.9),
                )
            },
        )
        .await;
        memory.project_fact_memory(folded).await.unwrap();
        let claim_open = |memory: &SqliteMemory| {
            let pool = memory.pool().clone();
            async move {
                sqlx::query_scalar::<_, Option<String>>(
                    "SELECT valid_to FROM memory_claims WHERE source_fact_id = ?",
                )
                .bind(folded)
                .fetch_one(&pool)
                .await
                .unwrap()
                .is_none()
            }
        };
        assert!(claim_open(&memory).await);

        assert!(memory.fold_fact_into(folded, kept).await.unwrap());
        assert_eq!(
            status(&memory, folded).await,
            (Some("folded".into()), Some(kept))
        );
        assert_eq!(
            memory
                .get_fact_by_id(kept)
                .await
                .unwrap()
                .unwrap()
                .recall_count,
            7
        );
        assert!(memory.get_fact_by_id(folded).await.unwrap().is_none());
        assert!(!memory.fact_exists(folded).await.unwrap());
        assert_eq!(tombstones(&memory, "folded").await, 1);
        assert!(!claim_open(&memory).await);
        // Folding twice does nothing.
        assert!(!memory.fold_fact_into(folded, kept).await.unwrap());

        let restored = memory.unfold_fact(folded).await.unwrap().unwrap();
        assert_eq!(restored.value, "Uses Helix, relative numbers on");
        assert_eq!(status(&memory, folded).await, (None, None));
        assert_eq!(tombstones(&memory, "folded").await, 0);
        assert!(claim_open(&memory).await);
        assert!(memory.fact_exists(folded).await.unwrap());
        // Unfolding an active fact does nothing.
        assert!(memory.unfold_fact(folded).await.unwrap().is_none());

        // A fact that took the key since blocks the unfold.
        assert!(memory.fold_fact_into(folded, kept).await.unwrap());
        insert(
            &memory,
            Row::new("preference", "editor_setup", "Zed", tilted(20, 1.0)),
        )
        .await;
        assert!(memory.unfold_fact(folded).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn fold_refuses_owner_words_farther_sources_and_narrower_scopes() {
        let (memory, _file) = open().await;
        let v = tilted(0, 1.0);
        let inferred = insert(&memory, Row::new("preference", "a", "x one", v.clone())).await;
        let owner = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new("preference", "b", "x two", v.clone())
            },
        )
        .await;
        let quoted = insert(
            &memory,
            Row {
                source: OWNER_QUOTED_SOURCE,
                ..Row::new("preference", "c", "x three", v.clone())
            },
        )
        .await;
        let global = insert(
            &memory,
            Row {
                privacy: "global",
                ..Row::new("preference", "d", "x four", v.clone())
            },
        )
        .await;
        let identity = insert(&memory, Row::new("user", "e", "x five", v.clone())).await;
        // Owner-stated is never folded away.
        assert!(!memory.fold_fact_into(owner, inferred).await.unwrap());
        // A quote is not folded into an inference.
        assert!(!memory.fold_fact_into(quoted, inferred).await.unwrap());
        // A global fact folded into a private one would hide it.
        assert!(!memory.fold_fact_into(global, inferred).await.unwrap());
        // An identity fact is not unpinned.
        assert!(!memory.fold_fact_into(identity, inferred).await.unwrap());
        assert!(!memory.fold_fact_into(inferred, inferred).await.unwrap());
        assert!(!memory.fold_fact_into(inferred, 999_999).await.unwrap());
        // A private inference folds into a global, owner-stated fact.
        assert!(memory.fold_fact_into(inferred, owner).await.unwrap());
        assert!(memory.fold_fact_into(quoted, owner).await.unwrap());
        assert!(!memory.fold_fact_into(global, owner).await.unwrap());
    }

    #[tokio::test]
    async fn refine_rewrites_automated_facts_only() {
        let (memory, _file) = open().await;
        let inferred = insert(
            &memory,
            Row::new("preference", "tone", "casual", tilted(0, 1.0)),
        )
        .await;
        let owner = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new("preference", "greeting", "hi", tilted(2, 1.0))
            },
        )
        .await;
        let blob = |id: i64| {
            let pool = memory.pool().clone();
            async move {
                sqlx::query_scalar::<_, Option<Vec<u8>>>("SELECT embedding FROM facts WHERE id = ?")
                    .bind(id)
                    .fetch_one(&pool)
                    .await
                    .unwrap()
            }
        };
        let before = blob(inferred).await;
        let refined = memory
            .refine_automated_fact_value(inferred, "  casual and brief  ")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(refined.value, "casual and brief");
        assert_eq!(refined.source, "consolidation");
        let after = blob(inferred).await;
        assert!(after.is_some() && after != before);
        let expected = HashEmbedder::new(EMBEDDING_DIM).embed_one(&build_fact_embedding_text(
            "preference",
            "tone",
            "casual and brief",
        ));
        assert_eq!(after, Some(encode_embedding(&expected)));

        assert!(
            memory
                .refine_automated_fact_value(owner, "hello")
                .await
                .unwrap()
                .is_none()
        );
        assert_eq!(
            memory.get_fact_by_id(owner).await.unwrap().unwrap().value,
            "hi"
        );
        assert!(
            memory
                .refine_automated_fact_value(inferred, "   ")
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn a_distinct_verdict_hides_the_pair_until_either_fact_changes() {
        let (memory, _file) = open().await;
        let value = "dark theme in every editor";
        let a = insert(
            &memory,
            Row::new("preference", "theme", value, tilted(0, 1.0)),
        )
        .await;
        let b = insert(
            &memory,
            Row {
                privacy: "global",
                ..Row::new("technical", "editor_theme", value, tilted(0, 0.97))
            },
        )
        .await;
        let paired = |overlaps: &std::collections::HashMap<i64, i64>| {
            overlaps.get(&a) == Some(&b) || overlaps.get(&b) == Some(&a)
        };
        assert!(paired(&memory.detect_fact_overlaps().await.unwrap()));
        assert_eq!(memory.has_valid_overlap_review(a, b).await.unwrap(), None);

        memory
            .record_overlap_review(b, a, OverlapReviewVerdict::Conflict, "test")
            .await
            .unwrap();
        // A conflict is still shown.
        assert!(paired(&memory.detect_fact_overlaps().await.unwrap()));
        memory
            .record_overlap_review(b, a, OverlapReviewVerdict::Distinct, "test")
            .await
            .unwrap();
        assert_eq!(
            memory.has_valid_overlap_review(a, b).await.unwrap(),
            Some(OverlapReviewVerdict::Distinct)
        );
        assert!(!paired(&memory.detect_fact_overlaps().await.unwrap()));

        // An edit voids the verdict and the pair is flagged again.
        sqlx::query("UPDATE facts SET value = value || '!' WHERE id = ?")
            .bind(b)
            .execute(memory.pool())
            .await
            .unwrap();
        assert_eq!(memory.has_valid_overlap_review(a, b).await.unwrap(), None);
        assert!(paired(&memory.detect_fact_overlaps().await.unwrap()));
        assert!(
            memory
                .record_overlap_review(a, 999_999, OverlapReviewVerdict::Distinct, "test")
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn unused_automated_facts_are_archived_and_nothing_else() {
        let (memory, _file) = open().await;
        let v = || tilted(0, 1.0);
        let idle = insert(
            &memory,
            Row {
                age_days: 90,
                ..Row::new("preference", "idle", "idle value", v())
            },
        )
        .await;
        let progressive = insert(
            &memory,
            Row {
                age_days: 90,
                source: "progressive",
                ..Row::new("technical", "idle_tool", "idle tool", v())
            },
        )
        .await;
        let mut kept = Vec::new();
        for row in [
            Row {
                age_days: 90,
                recall: 1,
                ..Row::new("preference", "recalled", "r", v())
            },
            Row {
                age_days: 90,
                source: "user_stated",
                ..Row::new("preference", "stated", "s", v())
            },
            Row {
                age_days: 90,
                source: OWNER_QUOTED_SOURCE,
                ..Row::new("preference", "quoted", "q", v())
            },
            Row {
                age_days: 90,
                ..Row::new("user", "hometown", "h", v())
            },
            Row {
                age_days: 10,
                ..Row::new("preference", "recent", "n", v())
            },
        ] {
            kept.push(insert(&memory, row).await);
        }
        let recalled_once = insert(
            &memory,
            Row {
                age_days: 90,
                ..Row::new("preference", "recalled_once", "o", v())
            },
        )
        .await;
        sqlx::query("UPDATE facts SET last_recalled_at = ? WHERE id = ?")
            .bind(Utc::now().to_rfc3339())
            .bind(recalled_once)
            .execute(memory.pool())
            .await
            .unwrap();
        kept.push(recalled_once);

        let now = Utc::now();
        assert_eq!(
            memory.archive_unused_automated_facts(now, 0).await.unwrap(),
            0
        );
        assert_eq!(
            memory
                .archive_unused_automated_facts(now, 60)
                .await
                .unwrap(),
            2
        );
        let archived: Vec<i64> = memory
            .get_archived_facts(10)
            .await
            .unwrap()
            .into_iter()
            .map(|f| f.id)
            .collect();
        assert!(archived.contains(&idle) && archived.contains(&progressive));
        for id in &kept {
            assert!(!archived.contains(id), "#{id} archived");
        }
        // Reversible.
        assert!(memory.restore_fact(idle).await.unwrap().is_some());
    }

    #[tokio::test]
    async fn decay_memory_runs_the_hygiene_steps() {
        let (memory, _file) = open().await;
        insert(
            &memory,
            Row {
                age_days: 90,
                ..Row::new("preference", "idle", "idle value", tilted(0, 1.0))
            },
        )
        .await;
        let old = insert(
            &memory,
            Row::new("technical", "node_version", "Node 18", tilted(4, 1.0)),
        )
        .await;
        insert(
            &memory,
            Row::new(
                "technical",
                "current_node_version",
                "Node 20",
                tilted(4, 0.95),
            ),
        )
        .await;
        crate::stores::decay_memory(&memory, &DecayPolicy::default())
            .await
            .unwrap();
        assert_eq!(memory.get_archived_facts(10).await.unwrap().len(), 1);
        assert_eq!(status(&memory, old).await.0.as_deref(), Some("replaced"));
    }

    #[tokio::test]
    async fn job_watermarks_round_trip() {
        let (memory, _file) = open().await;
        assert_eq!(memory.job_last_run_at("memory_decay").await.unwrap(), None);
        let first = Utc::now() - chrono::Duration::hours(30);
        memory
            .record_job_run_at("memory_decay", first)
            .await
            .unwrap();
        let read = memory
            .job_last_run_at("memory_decay")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(read.timestamp(), first.timestamp());
        let second = Utc::now();
        memory
            .record_job_run_at("memory_decay", second)
            .await
            .unwrap();
        let read = memory
            .job_last_run_at("memory_decay")
            .await
            .unwrap()
            .unwrap();
        assert_eq!(read.timestamp(), second.timestamp());
        assert_eq!(memory.job_last_run_at("other_job").await.unwrap(), None);
    }

    #[tokio::test]
    async fn fact_lookup_by_id_sees_archived_but_not_retired_facts() {
        let (memory, _file) = open().await;
        let id = insert(&memory, Row::new("project", "p", "v", tilted(0, 1.0))).await;
        assert!(memory.fact_exists(id).await.unwrap());
        assert!(memory.archive_fact(id).await.unwrap());
        assert!(memory.fact_exists(id).await.unwrap());
        assert_eq!(memory.get_fact_by_id(id).await.unwrap().unwrap().value, "v");
        memory.delete_fact(id).await.unwrap();
        assert!(!memory.fact_exists(id).await.unwrap());
        assert!(!memory.fact_exists(424_242).await.unwrap());
        assert!(!memory.fact_exists(-424_242).await.unwrap());
    }

    #[test]
    fn select_diverse_skips_paraphrases_within_a_category() {
        let ranked = vec![
            ("a", "preference".to_string(), Some(tilted(0, 1.0))),
            (
                "a-paraphrase",
                "preference".to_string(),
                Some(tilted(0, 0.95)),
            ),
            (
                "same-vector-other-category",
                "project".to_string(),
                Some(tilted(0, 1.0)),
            ),
            ("no-vector", "preference".to_string(), None),
            ("b", "preference".to_string(), Some(tilted(0, 0.6))),
        ];
        assert_eq!(
            select_diverse(ranked.clone(), 10),
            vec!["a", "same-vector-other-category", "no-vector", "b"]
        );
        assert_eq!(
            select_diverse(ranked, 2),
            vec!["a", "same-vector-other-category"]
        );
    }

    #[tokio::test]
    async fn a_paraphrase_does_not_crowd_a_distinct_fact_out_of_recall() {
        let (memory, _file) = open().await;
        let query = "what tone should replies use";
        let q = HashEmbedder::new(EMBEDDING_DIM).embed_one(query);
        // Two unit vectors orthogonal to q and to each other.
        let orthogonal = |seed: usize, against: &[&[f32]]| {
            let mut v = vec![0.0f32; EMBEDDING_DIM];
            v[seed] = 1.0;
            for other in against {
                let dot: f32 = v.iter().zip(other.iter()).map(|(x, y)| x * y).sum();
                v.iter_mut()
                    .zip(other.iter())
                    .for_each(|(x, y)| *x -= dot * y);
            }
            let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
            v.iter_mut().for_each(|x| *x /= norm);
            v
        };
        let u = orthogonal(3, &[&q]);
        let w = orthogonal(7, &[&q, &u]);
        let mix = |a: f32, x: &[f32], b: f32, y: &[f32]| -> Vec<f32> {
            x.iter().zip(y).map(|(x, y)| a * x + b * y).collect()
        };
        let top = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new("preference", "voice", "warm and direct", q.clone())
            },
        )
        .await;
        let paraphrase = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new(
                    "preference",
                    "voice_style",
                    "direct, warm voice",
                    mix(0.95, &q, 0.3122, &u),
                )
            },
        )
        .await;
        let distinct = insert(
            &memory,
            Row {
                source: "user_stated",
                ..Row::new(
                    "preference",
                    "length",
                    "under five sentences",
                    mix(0.6, &q, 0.8, &w),
                )
            },
        )
        .await;
        let ids: Vec<i64> = memory
            .get_relevant_facts(query, 2)
            .await
            .unwrap()
            .into_iter()
            .map(|f| f.id)
            .collect();
        assert!(ids.contains(&top) && ids.contains(&distinct), "{ids:?}");
        assert!(!ids.contains(&paraphrase));
        // With room for all three, the paraphrase is still left out: it
        // adds nothing beside the fact it restates.
        let ids: Vec<i64> = memory
            .get_relevant_facts_for_channel(query, 5, None, ChannelVisibility::Private, true)
            .await
            .unwrap()
            .into_iter()
            .map(|f| f.id)
            .collect();
        assert_eq!(ids.len(), 2, "{ids:?}");
    }

    #[tokio::test]
    async fn owner_fold_and_confirm_fact_work_for_explicit_triage() {
        let (memory, _file) = open().await;
        let kept = insert(
            &memory,
            Row {
                source: "user_stated",
                recall: 2,
                ..Row::new(
                    "preference",
                    "design_pref",
                    "Polished sites",
                    tilted(0, 1.0),
                )
            },
        )
        .await;
        let owner_dup = insert(
            &memory,
            Row {
                source: "user_stated",
                recall: 5,
                ..Row::new(
                    "preference",
                    "design_quality",
                    "Nice polished sites",
                    tilted(0, 0.88),
                )
            },
        )
        .await;
        // Automated fold refuses rank-2 owner facts, while explicit owner fold succeeds.
        assert!(!memory.fold_fact_into(owner_dup, kept).await.unwrap());
        assert!(memory.owner_fold_fact_into(owner_dup, kept).await.unwrap());
        assert_eq!(
            status(&memory, owner_dup).await,
            (Some("folded".into()), Some(kept))
        );
        // Owner fold still refuses narrowing a group-channel fact into private.
        let group_dup = insert(
            &memory,
            Row {
                privacy: "channel",
                channel: Some("slack:synthetic-team"),
                ..Row::new(
                    "preference",
                    "design_team",
                    "Team polished sites",
                    tilted(0, 0.88),
                )
            },
        )
        .await;
        assert!(!memory.owner_fold_fact_into(group_dup, kept).await.unwrap());

        let inferred = insert(
            &memory,
            Row {
                source: "inferred",
                ..Row::new("preference", "editor", "Uses Helix", tilted(4, 1.0))
            },
        )
        .await;
        let confirmed = memory
            .confirm_fact(inferred)
            .await
            .unwrap()
            .expect("confirmed fact");
        assert_eq!(confirmed.source, "user_stated");
        assert_eq!(confirmed.value, "Uses Helix");
        assert!(memory.confirm_fact(-10).await.unwrap().is_none());
    }
}