second-brain-core 0.13.5

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
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
use std::collections::HashMap;
use std::path::Path;

use anyhow::Result;
use chrono::{DateTime, Utc};
use rusqlite::{Connection, OptionalExtension, Transaction, params};
use serde::Serialize;
use uuid::Uuid;

use super::authored_order::{self, Stamp};
use super::clock::{self, is_new_layout};
use super::sync_dedup;
use super::{
    MEMORY_COLS, SqliteStore, embedding_to_blob, parse_dt, parse_relation_type, parse_uuid,
    relation_type_to_str, row_to_entity, row_to_memory, sync_op_to_str,
};
use crate::machine::MachineIdentity;
use crate::project_path;
use crate::schema::{
    CompactStats, Conversation, Distillation, Entity, IngestLogEntry, IngestRecord, Memory,
    Relation, RelationType, SyncEntry, SyncNodeType, SyncOp, SyncRecord, SyncState,
    distillable_source, explicit_sources_list,
};
use crate::store::{
    AmbiguousSlug, ApplyOutcome, ConsolidationStats, ExplicitRestoreStats, PendingDistillation,
    RefiledSlug, SkipReason, Store, StoreAdmin, StraySlugReport,
};

/// A raw the LLM has not seen and that recall can still surface. Archived
/// and superseded rows are excluded so a retired raw is never distilled
/// twice; explicit sources are excluded so a note someone wrote on purpose
/// is never replaced by a paraphrase.
pub(super) const UNCONSOLIDATED_PREDICATE: &str = concat!(
    distillable_source!("source"),
    " AND tier = 'hot' AND superseded_by IS NULL \
     AND id NOT IN (SELECT memory_id FROM distillation_log)"
);

/// A distillation_log row (distilled or skip marker alike) whose raw is
/// still competing with its distillate in recall. Distillates themselves
/// are excluded defensively: a log row keyed by one would otherwise retire
/// the very row consolidation produced. A raw whose distillate no longer
/// exists is excluded too: archiving it would take the last copy of that
/// knowledge out of recall (see `maintenance` for how the stale marker is
/// cleared instead).
const RETIRABLE_PREDICATE: &str = concat!(
    "m.tier = 'hot' AND m.superseded_by IS NULL AND ",
    distillable_source!("m.source"),
    " AND (dl.memory_id = dl.distilled_id \
          OR EXISTS (SELECT 1 FROM memories d WHERE d.id = dl.distilled_id))"
);

fn parse_record_data<T: serde::de::DeserializeOwned>(record: &SyncRecord, what: &str) -> Result<T> {
    let data = record
        .data
        .clone()
        .ok_or_else(|| anyhow::anyhow!("missing data for {what}"))?;
    Ok(serde_json::from_value(data)?)
}

/// A pre-sync peer serializes updated_at as the epoch sentinel; treat it as
/// created_at so LWW never loses to a real timestamp by accident.
fn normalize_incoming(memory: &mut Memory) {
    memory.archived_segment = None;
    if memory.updated_at == DateTime::UNIX_EPOCH {
        memory.updated_at = memory.created_at;
    }
}

/// A skip as `Tombstoned` or `StaleWrite` is not here: tombstones persist
/// and authored order does not depend on arrival, so every later copy is
/// skipped the same way. A legacy marker drop on an absent marker is, since
/// the marker may still arrive.
fn skip_depends_on_arrival_order(record: &SyncRecord, reason: SkipReason) -> bool {
    match reason {
        SkipReason::DanglingEndpoint => true,
        SkipReason::AlreadyPresent => {
            record.op == SyncOp::Delete && record.node_type == SyncNodeType::Distillation
        }
        _ => false,
    }
}

/// None when `incoming` is newer than the live row (or there is none);
/// otherwise why it is skipped.
fn lww_skip(stored: Option<&Stamp>, incoming: &Stamp) -> Option<SkipReason> {
    match stored {
        Some(stored) if stored == incoming => Some(SkipReason::AlreadyPresent),
        Some(stored) if stored > incoming => Some(SkipReason::StaleWrite),
        _ => None,
    }
}

/// What a marker create did to its memory's slot.
enum MarkerClaim {
    Landed {
        replaced: bool,
    },
    /// The newest create the slot has seen, refused by its own distillate's
    /// tombstone: it emptied the slot without landing.
    Emptied {
        removed: bool,
    },
    Skipped(SkipReason),
}

fn written(replaced: bool) -> ApplyOutcome {
    if replaced {
        ApplyOutcome::Updated
    } else {
        ApplyOutcome::Created
    }
}

impl SqliteStore {
    /// One record against one open transaction: the single implementation
    /// behind both apply_record and apply_batch, so per-record and batch
    /// application can never drift apart in conflict semantics.
    /// A new-layout key seen before is skipped ahead of any write, so a
    /// relayed copy cannot revert a newer record; a relation record is
    /// skipped the same way once a later record of its origin for the same
    /// node is logged. A distillation record never is: the marker slot takes
    /// every create it sees, so skipping one would make the slot's state
    /// depend on arrival order. A skip that depends on arrival order (a
    /// dangling endpoint, a legacy marker drop whose marker is absent) is not
    /// settled, because a later copy may apply once the missing row lands;
    /// every other key, applied or skipped, is kept in sync_dedup.
    pub(super) fn apply_on_tx(
        &self,
        tx: &Transaction<'_>,
        record: &SyncRecord,
    ) -> Result<ApplyOutcome> {
        let origin = record.origin_machine_id.as_str();
        let origin_seq = record.origin_seq as i64;
        clock::observe_authored(tx, record.timestamp.timestamp_micros())?;
        let new_layout = is_new_layout(origin, origin_seq);
        if new_layout && sync_dedup::seen(tx, origin, origin_seq)? {
            return Ok(ApplyOutcome::Skipped(SkipReason::AlreadyPresent));
        }
        let redacted = super::payload_redaction::redacted_record(record);
        let record = redacted.as_ref().unwrap_or(record);
        if !new_layout {
            return self.apply_unchecked(tx, record);
        }
        if record.node_type == SyncNodeType::Relation
            && sync_dedup::superseded(tx, record, origin_seq)?
        {
            if Self::record_superseded_tombstone(tx, record)? {
                self.log_applied(tx, record, SyncOp::Delete, origin, origin_seq)?;
            }
            sync_dedup::record(tx, origin, origin_seq)?;
            return Ok(ApplyOutcome::Skipped(SkipReason::StaleWrite));
        }
        let outcome = self.apply_unchecked(tx, record)?;
        let settled = match outcome {
            ApplyOutcome::Skipped(reason) => !skip_depends_on_arrival_order(record, reason),
            _ => true,
        };
        if settled {
            sync_dedup::record(tx, origin, origin_seq)?;
        }
        Ok(outcome)
    }

    fn apply_unchecked(&self, tx: &Transaction<'_>, record: &SyncRecord) -> Result<ApplyOutcome> {
        let origin = record.origin_machine_id.as_str();
        let origin_seq = record.origin_seq as i64;
        match (&record.op, &record.node_type) {
            (SyncOp::Create, SyncNodeType::Memory) => {
                let mut memory: Memory = parse_record_data(record, "memory create")?;
                normalize_incoming(&mut memory);
                if Self::tombstoned(tx, memory.id)?
                    || super::delete::in_deleted_session(tx, &memory)?
                {
                    return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
                }
                if Self::memory_exists(tx, memory.id)? {
                    Self::fill_session_at(tx, &memory)?;
                    return Ok(ApplyOutcome::Skipped(SkipReason::AlreadyPresent));
                }
                Self::insert_memory(tx, &memory)?;
                Self::append_outbox(tx, memory.id, "upsert")?;
                self.log_applied(tx, record, SyncOp::Create, origin, origin_seq)?;
                Ok(ApplyOutcome::Created)
            }
            (SyncOp::Update, SyncNodeType::Memory) => {
                let mut incoming: Memory = parse_record_data(record, "memory update")?;
                normalize_incoming(&mut incoming);
                match Self::existing_lww_key(tx, incoming.id)? {
                    None => {
                        if Self::tombstoned(tx, incoming.id)?
                            || super::delete::in_deleted_session(tx, &incoming)?
                        {
                            return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
                        }
                        Self::insert_memory(tx, &incoming)?;
                        Self::append_outbox(tx, incoming.id, "upsert")?;
                        self.log_applied(tx, record, SyncOp::Create, origin, origin_seq)?;
                        Ok(ApplyOutcome::Created)
                    }
                    Some((updated_at, access_count, machine_id)) => {
                        let incoming_wins = if incoming.updated_at != updated_at {
                            incoming.updated_at > updated_at
                        } else if incoming.access_count != access_count {
                            incoming.access_count > access_count
                        } else {
                            incoming.machine_id > machine_id
                        };
                        if !incoming_wins {
                            Self::fill_session_at(tx, &incoming)?;
                            return Ok(ApplyOutcome::Skipped(SkipReason::StaleWrite));
                        }
                        if incoming.session_at.is_none() {
                            incoming.session_at = Self::stored_session_at(tx, incoming.id)?;
                        }
                        Self::keep_cold_stub(tx, &mut incoming)?;
                        Self::insert_memory(tx, &incoming)?;
                        Self::append_outbox(tx, incoming.id, "upsert")?;
                        self.log_applied(tx, record, SyncOp::Update, origin, origin_seq)?;
                        Ok(ApplyOutcome::Updated)
                    }
                }
            }
            (SyncOp::Delete, SyncNodeType::Memory) => {
                // compact_sync_log frees up a peer's (origin_machine_id, origin_seq)
                // dedup key by deleting old log rows; without this check, a peer's
                // still-duplicated backlog re-imports as "new" and re-mints a fresh
                // local_seq row every time, undoing compaction and reinflating both
                // logs (the 2026-08-24 sync_log bloat incident).
                if Self::tombstone_row_exists(tx, &record.node_id)? {
                    return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
                }
                Self::upsert_tombstone(tx, &record.node_id, "memory", origin, record.timestamp)?;
                self.apply_memory_delete(tx, record)?;
                Ok(ApplyOutcome::Deleted)
            }
            (SyncOp::Create | SyncOp::Update, SyncNodeType::Conversation) => {
                let conversation: Conversation = parse_record_data(record, "conversation write")?;
                if authored_order::tombstone(tx, "conversation", &conversation.id.to_string())?
                    .is_some()
                {
                    return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
                }
                let incoming = authored_order::record_stamp(record, &conversation)?;
                let stored = authored_order::conversation_stamp(tx, conversation.id)?;
                if let Some(skip) = lww_skip(stored.as_ref(), &incoming) {
                    return Ok(ApplyOutcome::Skipped(skip));
                }
                Self::insert_conversation(tx, &conversation)?;
                authored_order::stamp_conversation(tx, conversation.id, &incoming)?;
                self.log_applied(tx, record, record.op, origin, origin_seq)?;
                Ok(written(stored.is_some()))
            }
            (SyncOp::Delete, SyncNodeType::Conversation) => {
                self.apply_permanent_delete(tx, record, "conversation", "conversations")
            }
            (SyncOp::Create | SyncOp::Update, SyncNodeType::Entity) => {
                let entity: Entity = parse_record_data(record, "entity write")?;
                if authored_order::tombstone(tx, "entity", &entity.id.to_string())?.is_some() {
                    return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
                }
                let incoming = authored_order::record_stamp(record, &entity)?;
                let stored = authored_order::entity_stamp(tx, entity.id)?;
                if let Some(skip) = lww_skip(stored.as_ref(), &incoming) {
                    return Ok(ApplyOutcome::Skipped(skip));
                }
                Self::insert_entity(tx, &entity)?;
                authored_order::stamp_entity(tx, entity.id, &incoming)?;
                self.log_applied(tx, record, record.op, origin, origin_seq)?;
                Ok(written(stored.is_some()))
            }
            (SyncOp::Delete, SyncNodeType::Entity) => {
                self.apply_permanent_delete(tx, record, "entity", "entities")
            }
            (SyncOp::Create, SyncNodeType::Distillation) => {
                let entry: Distillation = parse_record_data(record, "distillation create")?;
                let incoming = authored_order::record_stamp(record, &entry)?;
                // Deliberately not gated on the distilled memory existing yet. A
                // missing distillate is cosmetic and arrives over normal memory
                // sync; refusing the marker would make the peer redistill, which
                // is the exact waste this record exists to prevent.
                let claim = Self::claim_marker_slot(tx, &entry, &incoming)?;
                if let MarkerClaim::Skipped(skip) = claim {
                    return Ok(ApplyOutcome::Skipped(skip));
                }
                // An emptying create is logged too, so a store that syncs
                // only through this one replays the same slot change.
                self.log_applied(tx, record, SyncOp::Create, origin, origin_seq)?;
                Ok(match claim {
                    MarkerClaim::Landed { replaced } => written(replaced),
                    MarkerClaim::Emptied { removed: true } => ApplyOutcome::Deleted,
                    _ => ApplyOutcome::Skipped(SkipReason::Tombstoned),
                })
            }
            // A distillation is a one-shot fact, not a mutable row: the only
            // meaningful operation is asserting it happened.
            (SyncOp::Update, SyncNodeType::Distillation) => {
                Ok(ApplyOutcome::Skipped(SkipReason::Unsupported))
            }
            (SyncOp::Delete, SyncNodeType::Distillation) => {
                let dropped = record
                    .data
                    .as_ref()
                    .and_then(|d| serde_json::from_value::<Distillation>(d.clone()).ok());
                let Some(dropped) = dropped else {
                    return self.apply_legacy_marker_drop(tx, record);
                };
                let tombstone = authored_order::record_stamp(record, &dropped)?.tombstone();
                let key = authored_order::marker_key(dropped.memory_id, dropped.distilled_id);
                let kept = authored_order::record_tombstone(tx, "distillation", &key, &tombstone)?;
                let removed = match authored_order::marker_stamp(tx, dropped.memory_id)? {
                    Some((marker, row))
                        if marker.distilled_id == dropped.distilled_id && tombstone.beats(&row) =>
                    {
                        authored_order::empty_marker_slot(tx, dropped.memory_id, &row)?;
                        true
                    }
                    _ => false,
                };
                if !(kept || removed) {
                    return Ok(ApplyOutcome::Skipped(SkipReason::StaleWrite));
                }
                self.log_applied(tx, record, SyncOp::Delete, origin, origin_seq)?;
                Ok(ApplyOutcome::Deleted)
            }
            (SyncOp::Create, SyncNodeType::Relation) => {
                let relation: Relation = parse_record_data(record, "relation create")?;
                if !Self::relation_endpoints_exist(tx, &relation)? {
                    // An endpoint that has not arrived yet (or was deleted)
                    // skips the edge, matching the kuzu apply path where the
                    // edge insert itself failed.
                    return Ok(ApplyOutcome::Skipped(SkipReason::DanglingEndpoint));
                }
                let incoming = authored_order::record_stamp(record, &relation)?;
                let key = authored_order::relation_key(&relation);
                if !incoming.beats(authored_order::tombstone(tx, "relation", &key)?.as_ref()) {
                    return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
                }
                let stored = authored_order::relation_stamp(tx, &relation)?;
                if let Some(skip) = lww_skip(stored.as_ref(), &incoming) {
                    return Ok(ApplyOutcome::Skipped(skip));
                }
                Self::insert_relation(tx, &relation)?;
                authored_order::stamp_relation(tx, &relation, &incoming)?;
                self.log_applied(tx, record, SyncOp::Create, origin, origin_seq)?;
                Ok(written(stored.is_some()))
            }
            // Relations are immutable; an Update Relation record is invalid
            // and skipped rather than mislogged as a Create on relay.
            (SyncOp::Update, SyncNodeType::Relation) => {
                Ok(ApplyOutcome::Skipped(SkipReason::Unsupported))
            }
            (SyncOp::Delete, SyncNodeType::Relation) => {
                let Some(relation) = record
                    .data
                    .as_ref()
                    .and_then(|d| serde_json::from_value::<Relation>(d.clone()).ok())
                else {
                    // No deserializable relation data means nothing to delete
                    // or relay; skip rather than inflate the delete counter.
                    return Ok(ApplyOutcome::Skipped(SkipReason::Unsupported));
                };
                let tombstone = authored_order::record_stamp(record, &relation)?.tombstone();
                let key = authored_order::relation_key(&relation);
                let kept = authored_order::record_tombstone(tx, "relation", &key, &tombstone)?;
                let removed = match authored_order::relation_stamp(tx, &relation)? {
                    Some(row) if tombstone.beats(&row) => {
                        Self::remove_relation_row(tx, &relation)?;
                        true
                    }
                    _ => false,
                };
                if !(kept || removed) {
                    return Ok(ApplyOutcome::Skipped(SkipReason::StaleWrite));
                }
                self.log_applied(tx, record, SyncOp::Delete, origin, origin_seq)?;
                Ok(ApplyOutcome::Deleted)
            }
        }
    }

    /// Entities and conversations are never re-created under the same id,
    /// so a delete wins over every write and its tombstone is kept even
    /// when the row never arrived here.
    fn apply_permanent_delete(
        &self,
        tx: &Transaction<'_>,
        record: &SyncRecord,
        node_type: &str,
        table: &str,
    ) -> Result<ApplyOutcome> {
        let tombstone = authored_order::Tombstone {
            deleted_at: record.timestamp.timestamp_micros(),
            origin: authored_order::updated_by(record),
        };
        let kept = authored_order::record_tombstone(tx, node_type, &record.node_id, &tombstone)?;
        if node_type == "conversation" {
            super::delete::erase_conversation_traces(tx, &record.node_id)?;
        }
        let removed = tx.execute(
            &format!("DELETE FROM {table} WHERE id = ?1"),
            params![record.node_id],
        )?;
        if removed > 0 {
            tx.execute(
                "DELETE FROM relations WHERE to_id = ?1",
                params![record.node_id],
            )?;
        }
        if !kept && removed == 0 {
            return Ok(ApplyOutcome::Skipped(SkipReason::Tombstoned));
        }
        if node_type == "conversation" {
            self.cascade_conversation_delete(tx, &record.node_id)?;
            super::delete::request_purge(tx)?;
        }
        let origin = record.origin_machine_id.as_str();
        self.log_applied(tx, record, SyncOp::Delete, origin, record.origin_seq as i64)?;
        Ok(ApplyOutcome::Deleted)
    }

    /// A drop logged before authored time names no distillate, so it gets no
    /// tombstone and removes whatever marker the memory has; the removed
    /// marker's stamp stays as the slot floor.
    fn apply_legacy_marker_drop(
        &self,
        tx: &Transaction<'_>,
        record: &SyncRecord,
    ) -> Result<ApplyOutcome> {
        let Ok(memory_id) = Uuid::parse_str(&record.node_id) else {
            return Ok(ApplyOutcome::Skipped(SkipReason::AlreadyPresent));
        };
        let Some((_, row)) = authored_order::marker_stamp(tx, memory_id)? else {
            return Ok(ApplyOutcome::Skipped(SkipReason::AlreadyPresent));
        };
        authored_order::empty_marker_slot(tx, memory_id, &row)?;
        let origin = record.origin_machine_id.as_str();
        self.log_applied(tx, record, SyncOp::Delete, origin, record.origin_seq as i64)?;
        Ok(ApplyOutcome::Deleted)
    }

    /// The slot holds the newest marker create it has seen. A newest create
    /// whose own distillate is tombstoned empties the slot instead of
    /// landing, and an empty slot keeps that create's stamp, so an older
    /// create for another distillate stays out whichever order they arrive
    /// in.
    fn claim_marker_slot(
        tx: &Transaction<'_>,
        entry: &Distillation,
        incoming: &Stamp,
    ) -> Result<MarkerClaim> {
        let stored = authored_order::marker_stamp(tx, entry.memory_id)?;
        let row = stored.as_ref().map(|(_, s)| s);
        let floor = authored_order::marker_slot_floor(tx, entry.memory_id)?;
        let newest = row.is_none_or(|row| incoming > row) && incoming.beats(floor.as_ref());
        let key = authored_order::marker_key(entry.memory_id, entry.distilled_id);
        if !incoming.beats(authored_order::tombstone(tx, "distillation", &key)?.as_ref()) {
            if !newest {
                return Ok(MarkerClaim::Skipped(SkipReason::Tombstoned));
            }
            let removed = authored_order::empty_marker_slot(tx, entry.memory_id, incoming)?;
            return Ok(MarkerClaim::Emptied { removed });
        }
        if !newest {
            return Ok(MarkerClaim::Skipped(
                lww_skip(row, incoming).unwrap_or(SkipReason::StaleWrite),
            ));
        }
        Self::insert_distillation(tx, entry)?;
        authored_order::stamp_marker(tx, entry.memory_id, incoming)?;
        authored_order::clear_marker_slot_floor(tx, entry.memory_id)?;
        Ok(MarkerClaim::Landed {
            replaced: stored.is_some(),
        })
    }

    /// A relation delete skipped as superseded still leaves its tombstone,
    /// so every store holds the same tombstones whichever copy it saw first.
    /// True when the tombstone was raised, so the delete is logged and relayed.
    fn record_superseded_tombstone(tx: &Transaction<'_>, record: &SyncRecord) -> Result<bool> {
        let relation = record
            .data
            .as_ref()
            .and_then(|d| serde_json::from_value::<Relation>(d.clone()).ok());
        let (SyncOp::Delete, Some(relation)) = (record.op, relation) else {
            return Ok(false);
        };
        let tombstone = authored_order::record_stamp(record, &relation)?.tombstone();
        let key = authored_order::relation_key(&relation);
        authored_order::record_tombstone(tx, "relation", &key, &tombstone)
    }

    fn remove_relation_row(tx: &Transaction<'_>, relation: &Relation) -> Result<usize> {
        Ok(tx.execute(
            "DELETE FROM relations WHERE from_id = ?1 AND to_id = ?2 AND relation_type = ?3",
            params![
                relation.from_id.to_string(),
                relation.to_id.to_string(),
                relation_type_to_str(relation.relation_type),
            ],
        )?)
    }

    /// Removes a tombstoned memory with its edges and logs the delete under
    /// the record's key; the caller has written the tombstone.
    pub(super) fn apply_memory_delete(
        &self,
        tx: &Transaction<'_>,
        record: &SyncRecord,
    ) -> Result<()> {
        let cold: bool = tx.query_row(
            "SELECT EXISTS (SELECT 1 FROM memories WHERE id = ?1 AND archived_segment IS NOT NULL)",
            params![record.node_id],
            |r| r.get(0),
        )?;
        super::blocklist::block_row(tx, &record.node_id, Some(&self.machine_id))?;
        tx.execute(
            "DELETE FROM memories WHERE id = ?1",
            params![record.node_id],
        )?;
        super::delete::erase_memory_traces(tx, &record.node_id)?;
        if cold {
            super::delete::request_purge(tx)?;
        }
        if let Ok(id) = Uuid::parse_str(&record.node_id) {
            Self::append_outbox(tx, id, "delete")?;
        }
        self.log_applied(
            tx,
            record,
            SyncOp::Delete,
            &record.origin_machine_id,
            record.origin_seq as i64,
        )
    }

    fn log_applied(
        &self,
        tx: &Transaction<'_>,
        record: &SyncRecord,
        op: SyncOp,
        origin: &str,
        origin_seq: i64,
    ) -> Result<()> {
        let data = record
            .data
            .as_ref()
            .map(serde_json::to_string)
            .transpose()?;
        self.append_sync_log(
            tx,
            op,
            record.node_type,
            &record.node_id,
            data.as_deref(),
            Some((origin, origin_seq, record.timestamp)),
        )
    }

    /// Logs a row that predates the sync log as a local create and stamps
    /// the row with the same authored time, so it and every peer that
    /// applies the record order later writes alike.
    fn backfill_create<T: Serialize>(
        &self,
        node_type: SyncNodeType,
        node_id: &str,
        value: &T,
        stamp_row: impl Fn(&Transaction<'_>, &Stamp) -> Result<()>,
    ) -> Result<()> {
        self.with_txn(|tx| {
            let authored = self.authored_now(tx)?;
            let stamp = Stamp::of(authored.timestamp_micros(), &self.machine_id, value)?;
            stamp_row(tx, &stamp)?;
            let data = authored_order::data_with_updated_by(value, &self.machine_id)?;
            self.append_local_log_at(
                tx,
                SyncOp::Create,
                node_type,
                node_id,
                Some(&data),
                authored,
            )
        })
    }

    pub(super) fn memory_exists(tx: &Transaction<'_>, id: Uuid) -> Result<bool> {
        Self::row_exists(tx, "memories", &id.to_string())
    }

    fn row_exists(tx: &Transaction<'_>, table: &str, id: &str) -> Result<bool> {
        let hit: Option<i64> = tx
            .query_row(
                &format!("SELECT 1 FROM {table} WHERE id = ?1"),
                params![id],
                |r| r.get(0),
            )
            .optional()?;
        Ok(hit.is_some())
    }

    fn existing_lww_key(
        tx: &Transaction<'_>,
        id: Uuid,
    ) -> Result<Option<(DateTime<Utc>, u32, String)>> {
        tx.query_row(
            "SELECT updated_at, access_count, machine_id FROM memories WHERE id = ?1",
            params![id.to_string()],
            |r| {
                Ok((
                    parse_dt(&r.get::<_, String>(0)?)?,
                    r.get::<_, i64>(1)? as u32,
                    r.get::<_, String>(2)?,
                ))
            },
        )
        .optional()
        .map_err(Into::into)
    }

    fn stored_session_at(tx: &Transaction<'_>, id: Uuid) -> Result<Option<DateTime<Utc>>> {
        let stored: Option<Option<String>> = tx
            .query_row(
                "SELECT session_at FROM memories WHERE id = ?1",
                params![id.to_string()],
                |r| r.get(0),
            )
            .optional()?;
        Ok(stored.flatten().map(|s| parse_dt(&s)).transpose()?)
    }

    /// session_at merges apart from last-write-wins: a record that loses LWW
    /// still fills a date the stored row lacks. Nothing else in the row
    /// changes, so a date backfill that never bumped updated_at cannot undo
    /// a newer edit, and the fill is neither relogged nor reindexed.
    fn fill_session_at(tx: &Transaction<'_>, incoming: &Memory) -> Result<()> {
        if let Some(at) = incoming.session_at {
            tx.execute(
                "UPDATE memories SET session_at = ?2 WHERE id = ?1 AND session_at IS NULL",
                params![incoming.id.to_string(), at.to_rfc3339()],
            )?;
        }
        Ok(())
    }

    fn insert_conversation(tx: &Transaction<'_>, conversation: &Conversation) -> Result<()> {
        tx.execute(
            "INSERT OR REPLACE INTO conversations (id, source, machine_id, started_at, project_path) \
             VALUES (?1,?2,?3,?4,?5)",
            params![
                conversation.id.to_string(),
                conversation.source,
                conversation.machine_id,
                conversation.started_at.to_rfc3339(),
                conversation.project_path,
            ],
        )?;
        Ok(())
    }

    fn insert_entity(tx: &Transaction<'_>, entity: &Entity) -> Result<()> {
        let embedding = if entity.embedding.is_empty() {
            None
        } else {
            Some(embedding_to_blob(&entity.embedding))
        };
        tx.execute(
            "INSERT OR REPLACE INTO entities (id, name, entity_type, embedding, aliases) \
             VALUES (?1,?2,?3,?4,?5)",
            params![
                entity.id.to_string(),
                entity.name,
                entity.entity_type,
                embedding,
                serde_json::to_string(&entity.aliases)?,
            ],
        )?;
        Ok(())
    }

    fn insert_relation(tx: &Transaction<'_>, relation: &Relation) -> Result<()> {
        tx.execute(
            "INSERT INTO relations (from_id, to_id, relation_type, strength, context, created_at) \
             VALUES (?1,?2,?3,?4,?5,?6) \
             ON CONFLICT(from_id, to_id, relation_type) DO UPDATE SET \
             strength = excluded.strength, context = excluded.context",
            params![
                relation.from_id.to_string(),
                relation.to_id.to_string(),
                relation_type_to_str(relation.relation_type),
                relation.strength as f64,
                relation.context,
                Utc::now().to_rfc3339(),
            ],
        )?;
        Ok(())
    }

    fn relation_endpoints_exist(tx: &Transaction<'_>, relation: &Relation) -> Result<bool> {
        if !Self::memory_exists(tx, relation.from_id)? {
            return Ok(false);
        }
        let target_table = match relation.relation_type {
            RelationType::Mentions => "entities",
            RelationType::DerivedFrom => "conversations",
            _ => "memories",
        };
        Self::row_exists(tx, target_table, &relation.to_id.to_string())
    }

    fn sync_entries(&self, after_seq: u64, limit: Option<usize>) -> Result<Vec<SyncEntry>> {
        sync_entries_on(&self.reader(), after_seq, limit)
    }
}

pub(super) fn sync_entries_on(
    conn: &Connection,
    after_seq: u64,
    limit: Option<usize>,
) -> Result<Vec<SyncEntry>> {
    let limit_clause = match limit {
        Some(n) => format!(" LIMIT {n}"),
        None => String::new(),
    };
    let mut stmt = conn.prepare(&format!(
        "SELECT id, local_seq, origin_machine_id, origin_seq, op, node_type, node_id, \
         timestamp, data FROM sync_log WHERE local_seq > ?1 ORDER BY local_seq{limit_clause}"
    ))?;
    let rows = stmt.query_map(params![after_seq as i64], row_to_sync_entry)?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

pub(super) fn row_to_sync_entry(r: &rusqlite::Row<'_>) -> rusqlite::Result<SyncEntry> {
    let op = match r.get::<_, String>(4)?.as_str() {
        "update" => SyncOp::Update,
        "delete" => SyncOp::Delete,
        _ => SyncOp::Create,
    };
    let node_type = match r.get::<_, String>(5)?.as_str() {
        "entity" => SyncNodeType::Entity,
        "conversation" => SyncNodeType::Conversation,
        "relation" => SyncNodeType::Relation,
        "distillation" => SyncNodeType::Distillation,
        _ => SyncNodeType::Memory,
    };
    Ok(SyncEntry {
        id: r.get(0)?,
        local_seq: r.get(1)?,
        origin_machine_id: r.get(2)?,
        origin_seq: r.get(3)?,
        op,
        node_type,
        node_id: r.get(6)?,
        timestamp: parse_dt(&r.get::<_, String>(7)?)?,
        data: r.get::<_, Option<String>>(8)?.filter(|d| !d.is_empty()),
    })
}

impl StoreAdmin for SqliteStore {
    fn session_deleted(&self, path: &str) -> Result<bool> {
        SqliteStore::session_deleted(self, path)
    }

    fn register_machine(&self, identity: &MachineIdentity) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "INSERT INTO machines (id, name) VALUES (?1, ?2) \
             ON CONFLICT(id) DO UPDATE SET name = excluded.name",
            params![identity.id, identity.name],
        )?;
        let backfilled = conn.execute(
            "UPDATE memories SET machine_id = ?1 WHERE machine_id = ''",
            params![identity.id],
        )?;
        if backfilled > 0 {
            tracing::info!("backfilled machine_id on {backfilled} existing memories");
        }
        Ok(())
    }

    fn get_all_machines(&self) -> Result<HashMap<String, String>> {
        let conn = self.reader();
        let mut stmt = conn.prepare("SELECT id, COALESCE(name, '') FROM machines")?;
        let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
        Ok(rows.collect::<rusqlite::Result<HashMap<_, _>>>()?)
    }

    fn diagnostic(&self) -> Result<String> {
        let conn = self.reader();
        let total: i64 = conn.query_row("SELECT COUNT(*) FROM memories", [], |r| r.get(0))?;
        let with_emb: i64 = conn.query_row(
            "SELECT COUNT(*) FROM memories WHERE embedding IS NOT NULL",
            [],
            |r| r.get(0),
        )?;
        let max_seq: i64 = conn.query_row(
            "SELECT COALESCE(MAX(local_seq), 0) FROM sync_log",
            [],
            |r| r.get(0),
        )?;
        Ok(format!(
            "backend: sqlite\ntotal memories: {total}\nwith embeddings: {with_emb}\nmax sync seq: {max_seq}"
        ))
    }

    fn find_or_create_entity(&self, name: &str, entity_type: &str) -> Result<Entity> {
        if let Some(existing) = self.find_entity_by_name(name)? {
            return Ok(existing);
        }
        let entity = Entity::new(name.to_string(), entity_type.to_string());
        self.store_entity(&entity)?;
        Ok(entity)
    }

    fn memory_content_exists(&self, content_prefix: &str) -> Result<bool> {
        SqliteStore::memory_content_exists(self, content_prefix)
    }

    fn store_memory_if_absent(&self, memory: &Memory) -> Result<bool> {
        self.with_txn(|tx| {
            if Self::memory_exists(tx, memory.id)? {
                return Ok(false);
            }
            self.store_memory_on_tx(tx, memory)
        })
    }

    fn ingest_memory_if_absent(&self, memory: &Memory) -> Result<bool> {
        SqliteStore::ingest_memory_if_absent(self, memory)
    }

    fn ingest_blocked(&self, memory: &Memory) -> Result<bool> {
        SqliteStore::ingest_blocked(self, memory)
    }

    fn store_conversation_if_absent(&self, conversation: &Conversation) -> Result<bool> {
        self.with_txn(|tx| {
            let id = conversation.id.to_string();
            if Self::row_exists(tx, "conversations", &id)?
                || authored_order::tombstone(tx, "conversation", &id)?.is_some()
            {
                return Ok(false);
            }
            let authored = self.authored_now(tx)?;
            let data = authored_order::data_with_updated_by(conversation, &self.machine_id)?;
            Self::insert_conversation(tx, conversation)?;
            let stamp = Stamp::of(authored.timestamp_micros(), &self.machine_id, conversation)?;
            authored_order::stamp_conversation(tx, conversation.id, &stamp)?;
            self.append_local_log_at(
                tx,
                SyncOp::Create,
                SyncNodeType::Conversation,
                &id,
                Some(&data),
                authored,
            )?;
            Ok(true)
        })
    }

    fn memory_id_taken(&self, id: Uuid) -> Result<bool> {
        let conn = self.reader();
        let hit: Option<i64> = conn
            .query_row(
                "SELECT 1 FROM memories WHERE id = ?1 \
                 UNION ALL SELECT 1 FROM tombstones WHERE node_id = ?1 LIMIT 1",
                params![id.to_string()],
                |r| r.get(0),
            )
            .optional()?;
        Ok(hit.is_some())
    }

    fn is_file_changed(&self, file_path: &str, file_hash: &str) -> Result<bool> {
        let conn = self.reader();
        let stored: Option<String> = conn
            .query_row(
                "SELECT file_hash FROM ingest_log WHERE file_path = ?1",
                params![file_path],
                |r| r.get(0),
            )
            .optional()?;
        Ok(match stored {
            Some(hash) => hash != file_hash,
            None => true,
        })
    }

    fn mark_ingested(
        &self,
        file_path: &str,
        file_hash: &str,
        memory_count: usize,
        source: &str,
    ) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "INSERT INTO ingest_log (file_path, file_hash, ingested_at, memory_count, source) \
             VALUES (?1,?2,?3,?4,?5) \
             ON CONFLICT(file_path) DO UPDATE SET file_hash = excluded.file_hash, \
             ingested_at = excluded.ingested_at, memory_count = excluded.memory_count, \
             source = excluded.source, content_hash = NULL",
            params![
                file_path,
                file_hash,
                Utc::now().to_rfc3339(),
                memory_count as i64,
                source,
            ],
        )?;
        Ok(())
    }

    fn ingested_file_count(&self) -> Result<usize> {
        let conn = self.reader();
        let count: i64 = conn.query_row("SELECT COUNT(*) FROM ingest_log", [], |r| r.get(0))?;
        Ok(count as usize)
    }

    fn clear_ingest_log(&self) -> Result<usize> {
        let conn = self.conn();
        let count = conn.execute("DELETE FROM ingest_log", [])?;
        Ok(count)
    }

    fn ingest_log_entry(&self, file_path: &str) -> Result<Option<IngestLogEntry>> {
        let conn = self.reader();
        conn.query_row(
            &format!("SELECT {INGEST_LOG_COLS} FROM ingest_log WHERE file_path = ?1"),
            params![file_path],
            row_to_ingest_log_entry,
        )
        .optional()
        .map_err(Into::into)
    }

    fn ingested_session(
        &self,
        session_key: &str,
        content_hash: &str,
    ) -> Result<Option<IngestLogEntry>> {
        let conn = self.reader();
        conn.query_row(
            &format!(
                "SELECT {INGEST_LOG_COLS} FROM ingest_log \
                 WHERE session_key = ?1 AND content_hash = ?2 \
                 ORDER BY legacy_ids DESC LIMIT 1"
            ),
            params![session_key, content_hash],
            row_to_ingest_log_entry,
        )
        .optional()
        .map_err(Into::into)
    }

    fn legacy_ingest_entries_with_stem(&self, stem: &str) -> Result<Vec<IngestLogEntry>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {INGEST_LOG_COLS} FROM ingest_log \
             WHERE legacy_ids = 1 AND content_hash IS NULL AND instr(file_path, ?1) > 0"
        ))?;
        let rows = stmt
            .query_map(params![stem], row_to_ingest_log_entry)?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        Ok(rows
            .into_iter()
            .filter(|e| {
                Path::new(&e.file_path)
                    .file_stem()
                    .is_some_and(|s| s.to_string_lossy() == stem)
            })
            .collect())
    }

    fn upgrade_ingest_hash(
        &self,
        file_path: &str,
        content_hash: &str,
        session_key: Option<&str>,
    ) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "UPDATE ingest_log SET file_hash = ?2, content_hash = ?2, session_key = ?3 \
             WHERE file_path = ?1",
            params![file_path, content_hash, session_key],
        )?;
        Ok(())
    }

    fn record_ingested(&self, record: &IngestRecord<'_>) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "INSERT INTO ingest_log (file_path, file_hash, ingested_at, memory_count, source, \
             session_key, content_hash, legacy_ids) VALUES (?1,?2,?3,?4,?5,?6,?2,?7) \
             ON CONFLICT(file_path) DO UPDATE SET file_hash = excluded.file_hash, \
             content_hash = excluded.content_hash, session_key = excluded.session_key, \
             ingested_at = excluded.ingested_at, memory_count = excluded.memory_count, \
             source = excluded.source, legacy_ids = MAX(legacy_ids, excluded.legacy_ids)",
            params![
                record.file_path,
                record.content_hash,
                Utc::now().to_rfc3339(),
                record.memory_count as i64,
                record.source,
                record.session_key,
                record.legacy_ids,
            ],
        )?;
        Ok(())
    }

    fn clear_reparseable_ingest_log(&self) -> Result<usize> {
        let conn = self.conn();
        let count = conn.execute("DELETE FROM ingest_log WHERE legacy_ids = 0", [])?;
        Ok(count)
    }

    fn delete_memories_by_source(&self, source: &str) -> Result<usize> {
        self.purge_memories_where("source = ?1", source)
    }

    fn delete_memories_by_source_id(&self, source_id: &str) -> Result<usize> {
        self.purge_memories_where("source_id = ?1", source_id)
    }

    fn rebuild_vector_index(&self) -> Result<()> {
        // The store itself keeps no vector index (vector_search brute-forces
        // over stored embeddings); the index layer owns usearch/tantivy and
        // rebuilds from the store, so there is nothing to rebuild here.
        Ok(())
    }

    fn backfill_project_paths(&self) -> Result<u64> {
        // source_id runs first: it is populated on every ingested row, unlike
        // the derived_from relation the fallback below depends on, so it
        // covers the corpus the relation-based pass never reaches.
        let from_source_id = self.backfill_project_paths_from_source_id()?;

        let from_relations: Vec<(Uuid, String)> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT m.id, (SELECT c.project_path FROM conversations c \
                   JOIN relations r ON r.to_id = c.id \
                   WHERE r.from_id = m.id AND r.relation_type = 'derived_from' \
                     AND c.project_path IS NOT NULL AND c.project_path <> '' \
                   LIMIT 1) \
                 FROM memories m WHERE (m.project_path IS NULL OR m.project_path = '')",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok((
                    parse_uuid(&r.get::<_, String>(0)?)?,
                    r.get::<_, Option<String>>(1)?,
                ))
            })?;
            rows.filter_map(|row| match row {
                Ok((id, Some(project))) => Some(Ok((id, project))),
                Ok((_, None)) => None,
                Err(e) => Some(Err(e)),
            })
            .collect::<rusqlite::Result<Vec<_>>>()?
        };
        Ok(from_source_id + self.refile_all(&from_relations)?)
    }

    fn backfill_sync_log(&self) -> Result<u64> {
        // Give every row that predates the sync log a Create entry so a fresh peer
        // can be seeded from this store's full history. All four node types matter:
        // an unlogged entity or conversation is an endpoint a peer never receives,
        // and every relation pointing at it is then skipped on import as dangling.
        let mut logged = 0u64;

        let memory_ids: Vec<Uuid> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT id FROM memories WHERE id NOT IN ( \
                   SELECT node_id FROM sync_log WHERE node_type = 'memory')",
            )?;
            let rows = stmt.query_map([], |r| parse_uuid(&r.get::<_, String>(0)?))?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        for id in memory_ids {
            let Some(memory) = self.get_memory_with_embedding(id)? else {
                continue;
            };
            self.with_txn(|tx| {
                let data = serde_json::to_string(&*self.sync_form(tx, &memory)?).ok();
                self.append_sync_log(
                    tx,
                    SyncOp::Create,
                    SyncNodeType::Memory,
                    &id.to_string(),
                    data.as_deref(),
                    None,
                )
            })?;
            logged += 1;
        }

        let conversations: Vec<Conversation> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT id, source, machine_id, started_at, project_path FROM conversations \
                 WHERE id NOT IN ( \
                   SELECT node_id FROM sync_log WHERE node_type = 'conversation')",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok(Conversation {
                    id: parse_uuid(&r.get::<_, String>(0)?)?,
                    source: r.get(1)?,
                    machine_id: r.get(2)?,
                    started_at: parse_dt(&r.get::<_, String>(3)?)?,
                    project_path: r.get(4)?,
                })
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        for conversation in conversations {
            self.backfill_create(
                SyncNodeType::Conversation,
                &conversation.id.to_string(),
                &conversation,
                |tx, stamp| authored_order::stamp_conversation(tx, conversation.id, stamp),
            )?;
            logged += 1;
        }

        let entities: Vec<Entity> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT id, name, entity_type, embedding, aliases FROM entities \
                 WHERE id NOT IN ( \
                   SELECT node_id FROM sync_log WHERE node_type = 'entity')",
            )?;
            let rows = stmt.query_map([], row_to_entity)?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        for entity in entities {
            self.backfill_create(
                SyncNodeType::Entity,
                &entity.id.to_string(),
                &entity,
                |tx, stamp| authored_order::stamp_entity(tx, entity.id, stamp),
            )?;
            logged += 1;
        }

        // Relations are keyed by the composite the writer uses, not a uuid, so the
        // "already logged" check has to rebuild that same key.
        let relations: Vec<Relation> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT from_id, to_id, relation_type, strength, context FROM relations \
                 WHERE from_id || ':' || to_id || ':' || relation_type NOT IN ( \
                   SELECT node_id FROM sync_log WHERE node_type = 'relation')",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok(Relation {
                    from_id: parse_uuid(&r.get::<_, String>(0)?)?,
                    to_id: parse_uuid(&r.get::<_, String>(1)?)?,
                    relation_type: parse_relation_type(&r.get::<_, String>(2)?)?,
                    strength: r.get::<_, f64>(3)? as f32,
                    context: r.get(4)?,
                })
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        for relation in relations {
            let node_id = format!(
                "{}:{}:{}",
                relation.from_id,
                relation.to_id,
                relation_type_to_str(relation.relation_type)
            );
            self.backfill_create(SyncNodeType::Relation, &node_id, &relation, |tx, stamp| {
                authored_order::stamp_relation(tx, &relation, stamp)
            })?;
            logged += 1;
        }

        let distillations: Vec<Distillation> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT memory_id, distilled_id, distilled_at, model, status \
                 FROM distillation_log WHERE memory_id NOT IN ( \
                   SELECT node_id FROM sync_log WHERE node_type = 'distillation')",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok(Distillation {
                    memory_id: parse_uuid(&r.get::<_, String>(0)?)?,
                    distilled_id: r
                        .get::<_, Option<String>>(1)?
                        .map(|v| parse_uuid(&v))
                        .transpose()?,
                    distilled_at: r
                        .get::<_, Option<String>>(2)?
                        .map(|v| parse_dt(&v))
                        .transpose()?,
                    model: r.get(3)?,
                    status: r.get(4)?,
                })
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        for entry in distillations {
            self.backfill_create(
                SyncNodeType::Distillation,
                &entry.memory_id.to_string(),
                &entry,
                |tx, stamp| authored_order::stamp_marker(tx, entry.memory_id, stamp),
            )?;
            logged += 1;
        }

        Ok(logged)
    }

    fn backfill_tombstones(&self) -> Result<u64> {
        // The mirror of backfill_sync_log: a deletion that left a tombstone but no
        // Delete entry can never be pushed, so the memory stays alive on every peer
        // and keeps surfacing in their recall. Origin is this machine because this
        // store is the one asserting the deletion, which also keeps the generated
        // "{origin}:{seq}" log id from colliding with a remote machine's entries.
        let node_ids: Vec<String> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT node_id FROM tombstones WHERE node_type = 'memory' \
                   AND node_id NOT IN ( \
                     SELECT node_id FROM sync_log \
                     WHERE node_type = 'memory' AND op = 'delete')",
            )?;
            let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };

        let mut logged = 0u64;
        for node_id in node_ids {
            self.with_txn(|tx| {
                self.append_sync_log(
                    tx,
                    SyncOp::Delete,
                    SyncNodeType::Memory,
                    &node_id,
                    None,
                    None,
                )
            })?;
            logged += 1;
        }
        Ok(logged)
    }

    fn prune_dangling_relations(&self) -> Result<u64> {
        // The relations table has no foreign keys, so store_relation accepts an edge
        // whose endpoints were never written or have since been deleted. The sync
        // importer does validate, so these rows can never replicate and read as a
        // permanent replication gap. Mirrors relation_endpoints_exist exactly.
        let dangling: Vec<Relation> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT from_id, to_id, relation_type, strength, context FROM relations \
                 WHERE from_id NOT IN (SELECT id FROM memories) \
                    OR (relation_type = 'mentions' \
                        AND to_id NOT IN (SELECT id FROM entities)) \
                    OR (relation_type = 'derived_from' \
                        AND to_id NOT IN (SELECT id FROM conversations)) \
                    OR (relation_type NOT IN ('mentions', 'derived_from') \
                        AND to_id NOT IN (SELECT id FROM memories))",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok(Relation {
                    from_id: parse_uuid(&r.get::<_, String>(0)?)?,
                    to_id: parse_uuid(&r.get::<_, String>(1)?)?,
                    relation_type: parse_relation_type(&r.get::<_, String>(2)?)?,
                    strength: r.get::<_, f64>(3)? as f32,
                    context: r.get(4)?,
                })
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };

        let mut pruned = 0u64;
        for relation in dangling {
            if self.with_txn(|tx| self.delete_relation_on_tx(tx, &relation))? {
                pruned += 1;
            }
        }
        Ok(pruned)
    }

    fn compact_sync_log(&self, ops: &[SyncOp], dry_run: bool) -> Result<CompactStats> {
        if ops.is_empty() {
            return Ok(CompactStats::default());
        }
        let op_strs: Vec<&'static str> = ops.iter().map(|op| sync_op_to_str(*op)).collect();
        let in_list = op_strs.iter().map(|_| "?").collect::<Vec<_>>().join(",");

        let mut conn = self.conn();
        conn.execute_batch("PRAGMA cache_size = -262144;")?;
        // Without this, the GROUP BY and the join back onto sync_log both
        // fall back to a full-table sort/scan: on a 30M+ row bloated log
        // that is tens of GB of disk I/O per invocation, observed live on
        // the Pi. Built once, reused by every future compact call and by
        // ordinary sync writes that filter on node_id already.
        conn.execute_batch(
            "CREATE INDEX IF NOT EXISTS idx_sync_log_type_id_op_seq \
             ON sync_log(node_type, node_id, op, local_seq);",
        )?;

        let max_before: i64 = conn.query_row(
            "SELECT COALESCE(MAX(local_seq), 0) FROM sync_log",
            [],
            |r| r.get(0),
        )?;

        conn.execute_batch("DROP TABLE IF EXISTS compact_victims;")?;
        conn.execute(
            &format!(
                "CREATE TEMP TABLE compact_victims AS \
                 SELECT s.local_seq, s.node_type, s.node_id, s.op \
                 FROM sync_log s \
                 JOIN (SELECT node_type, node_id, op, MAX(local_seq) AS keep_seq \
                       FROM sync_log \
                       WHERE op IN ({in_list}) \
                       GROUP BY node_type, node_id, op) k \
                   ON s.node_type = k.node_type AND s.node_id = k.node_id AND s.op = k.op \
                 WHERE s.op IN ({in_list}) AND s.local_seq < k.keep_seq"
            ),
            rusqlite::params_from_iter(op_strs.iter().chain(op_strs.iter())),
        )?;
        conn.execute_batch("CREATE INDEX idx_compact_victims_seq ON compact_victims(local_seq);")?;

        // Groups with a real duplicate, not the victim row count: every
        // victim group has at least one surviving (kept) row that never
        // appears here, so distinct groups among the victims is exactly the
        // count of node_type/node_id/op triples that had more than one row.
        let groups_with_duplicates: i64 = conn.query_row(
            "SELECT COUNT(*) FROM (SELECT DISTINCT node_type, node_id, op FROM compact_victims)",
            [],
            |r| r.get(0),
        )?;
        let victim_count: i64 =
            conn.query_row("SELECT COUNT(*) FROM compact_victims", [], |r| r.get(0))?;

        let mut rows_deleted: i64 = 0;
        if !dry_run {
            let mut cursor: i64 = 0;
            loop {
                let chunk: Vec<i64> = {
                    let mut stmt = conn.prepare(
                        "SELECT local_seq FROM compact_victims WHERE local_seq > ?1 \
                         ORDER BY local_seq LIMIT 20000",
                    )?;
                    let rows = stmt.query_map(params![cursor], |r| r.get::<_, i64>(0))?;
                    rows.collect::<rusqlite::Result<Vec<_>>>()?
                };
                if chunk.is_empty() {
                    break;
                }
                cursor = *chunk.last().expect("just checked non-empty");
                let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(",");
                let tx = conn.transaction()?;
                sync_dedup::keep_keys_of(&tx, &chunk)?;
                let n = tx.execute(
                    &format!("DELETE FROM sync_log WHERE local_seq IN ({placeholders})"),
                    rusqlite::params_from_iter(chunk.iter()),
                )?;
                tx.commit()?;
                rows_deleted += n as i64;
            }
        }

        conn.execute_batch("DROP TABLE IF EXISTS compact_victims;")?;

        let max_after: i64 = conn.query_row(
            "SELECT COALESCE(MAX(local_seq), 0) FROM sync_log",
            [],
            |r| r.get(0),
        )?;
        Ok(CompactStats {
            groups_with_duplicates: groups_with_duplicates as u64,
            rows_deleted: if dry_run {
                victim_count as u64
            } else {
                rows_deleted as u64
            },
            max_local_seq_before: max_before as u64,
            max_local_seq_after: max_after as u64,
        })
    }

    fn memories_by_project_path(&self, project_path: &str) -> Result<Vec<Memory>> {
        // LIMIT 20 is part of the contract: callers feed this straight into a
        // context pack and rely on the store bounding it.
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS} FROM memories \
             WHERE project_path = ?1 AND tier = 'hot' AND superseded_by IS NULL \
             ORDER BY created_at DESC LIMIT 20"
        ))?;
        let rows = stmt.query_map(params![project_path], |r| row_to_memory(r, false))?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn distinct_project_paths(&self) -> Result<Vec<(String, u64)>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(
            "SELECT project_path, COUNT(*) FROM memories \
             WHERE project_path IS NOT NULL AND project_path <> '' \
               AND tier = 'hot' AND superseded_by IS NULL \
             GROUP BY project_path ORDER BY COUNT(*) DESC",
        )?;
        let rows = stmt.query_map([], |r| {
            let count: i64 = r.get(1)?;
            Ok((r.get::<_, String>(0)?, count as u64))
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn all_memories_with_embeddings(&self) -> Result<Vec<Memory>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!("SELECT {MEMORY_COLS}, embedding FROM memories"))?;
        let rows = stmt.query_map([], |r| row_to_memory(r, true))?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn consolidation_stats(&self) -> Result<ConsolidationStats> {
        let conn = self.reader();
        let count = |sql: &str| -> Result<u64> {
            let n: i64 = conn.query_row(sql, [], |r| r.get(0))?;
            Ok(n as u64)
        };
        Ok(ConsolidationStats {
            distilled_live: count(
                "SELECT COUNT(*) FROM memories WHERE source = 'consolidation' \
                 AND tier = 'hot' AND superseded_by IS NULL",
            )?,
            raw_pending: count(&format!(
                "SELECT COUNT(*) FROM memories WHERE {UNCONSOLIDATED_PREDICATE}"
            ))?,
            raw_retired: count(
                "SELECT COUNT(*) FROM distillation_log dl JOIN memories m ON m.id = dl.memory_id \
                 WHERE m.tier = 'archived'",
            )?,
            raw_retire_pending: count(&format!(
                "SELECT COUNT(*) FROM distillation_log dl JOIN memories m ON m.id = dl.memory_id \
                 WHERE {RETIRABLE_PREDICATE}"
            ))?,
        })
    }

    fn unconsolidated_memories(&self, limit: usize) -> Result<Vec<Memory>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS} FROM memories WHERE {UNCONSOLIDATED_PREDICATE} \
             ORDER BY source_id, created_at LIMIT ?1"
        ))?;
        let rows = stmt.query_map(params![limit as i64], |r| row_to_memory(r, false))?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn mark_consolidated(&self, raw_id: Uuid, distilled_id: Uuid, model: &str) -> Result<()> {
        self.with_txn(|tx| self.mark_consolidated_on_tx(tx, raw_id, distilled_id, model))
    }

    fn retire_consolidated_raws(&self) -> Result<usize> {
        const BATCH: usize = 500;
        let ids: Vec<Uuid> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(&format!(
                "SELECT m.id FROM distillation_log dl JOIN memories m ON m.id = dl.memory_id \
                 WHERE {RETIRABLE_PREDICATE} ORDER BY m.created_at"
            ))?;
            let rows = stmt.query_map([], |r| parse_uuid(&r.get::<_, String>(0)?))?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        let mut retired = 0usize;
        for chunk in ids.chunks(BATCH) {
            retired += self.with_txn(|tx| {
                let mut n = 0usize;
                for id in chunk {
                    if self.archive_on_tx(tx, *id)? {
                        n += 1;
                    }
                }
                Ok(n)
            })?;
        }
        Ok(retired)
    }

    fn memories_created_between(
        &self,
        start: &DateTime<Utc>,
        end: &DateTime<Utc>,
    ) -> Result<Vec<Memory>> {
        let conn = self.reader();
        let mut stmt = conn.prepare(&format!(
            "SELECT {MEMORY_COLS} FROM memories WHERE created_at >= ?1 AND created_at < ?2 \
             ORDER BY created_at ASC"
        ))?;
        let rows = stmt.query_map(params![start.to_rfc3339(), end.to_rfc3339()], |r| {
            row_to_memory(r, false)
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn sync_log_since(&self, after_seq: u64) -> Result<Vec<SyncEntry>> {
        self.sync_entries(after_seq, None)
    }

    fn sync_log_page(&self, after_seq: u64, limit: Option<usize>) -> Result<Vec<SyncEntry>> {
        self.sync_entries(after_seq, limit)
    }

    fn sync_log_export_page(&self, after_seq: u64, limit: Option<usize>) -> Result<Vec<SyncEntry>> {
        self.sync_log_page_above_floor(after_seq, limit)
    }

    fn max_sync_seq(&self) -> Result<u64> {
        SqliteStore::max_sync_seq(self)
    }

    fn get_sync_state(&self, peer_id: &str) -> Result<Option<SyncState>> {
        let conn = self.reader();
        conn.query_row(
            "SELECT peer_id, last_seq, last_sync_at FROM sync_state WHERE peer_id = ?1",
            params![peer_id],
            |r| {
                Ok(SyncState {
                    peer_id: r.get(0)?,
                    last_seq: r.get::<_, i64>(1)? as u64,
                    last_sync_at: parse_dt(&r.get::<_, String>(2)?)?,
                })
            },
        )
        .optional()
        .map_err(Into::into)
    }

    fn set_sync_state(&self, state: &SyncState) -> Result<()> {
        let conn = self.conn();
        conn.execute(
            "INSERT OR REPLACE INTO sync_state (peer_id, last_seq, last_sync_at) VALUES (?1,?2,?3)",
            params![
                state.peer_id,
                state.last_seq as i64,
                state.last_sync_at.to_rfc3339(),
            ],
        )?;
        Ok(())
    }

    fn get_all_sync_states(&self) -> Result<Vec<SyncState>> {
        let conn = self.reader();
        let mut stmt = conn.prepare("SELECT peer_id, last_seq, last_sync_at FROM sync_state")?;
        let rows = stmt.query_map([], |r| {
            Ok(SyncState {
                peer_id: r.get(0)?,
                last_seq: r.get::<_, i64>(1)? as u64,
                last_sync_at: parse_dt(&r.get::<_, String>(2)?)?,
            })
        })?;
        Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
    }

    fn tombstone_exists(&self, id: Uuid) -> Result<bool> {
        SqliteStore::tombstone_exists(self, id)
    }

    fn apply_record(&self, record: &SyncRecord) -> Result<ApplyOutcome> {
        self.with_txn(|tx| self.apply_on_tx(tx, record))
    }

    fn apply_batch(&self, records: &[SyncRecord]) -> Result<Vec<ApplyOutcome>> {
        self.with_txn(|tx| {
            let mut outcomes = Vec::with_capacity(records.len());
            for record in records {
                outcomes.push(self.apply_on_tx(tx, record)?);
            }
            Ok(outcomes)
        })
    }
}

impl SqliteStore {
    pub fn pending_distillation(&self) -> Result<PendingDistillation> {
        let conn = self.reader();
        let (count, oldest): (i64, Option<String>) = conn.query_row(
            &format!(
                "SELECT COUNT(*), MIN(created_at) FROM memories WHERE {UNCONSOLIDATED_PREDICATE}"
            ),
            [],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )?;
        Ok(PendingDistillation {
            count: count as u64,
            oldest_created_at: oldest.as_deref().map(parse_dt).transpose()?,
        })
    }
}

impl SqliteStore {
    /// Derives `project_path` from `source_id` with the rule ingest applies
    /// (`adapters::project_slug`): the directory directly under the
    /// `projects` root, so a nested subagent transcript lands on its project
    /// rather than on `subagents`. A path with no `projects` root is left
    /// untagged. Every row is replicated and re-indexed like any refile.
    fn backfill_project_paths_from_source_id(&self) -> Result<u64> {
        let untagged: Vec<(Uuid, String)> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(
                "SELECT id, source_id FROM memories \
                 WHERE (project_path IS NULL OR project_path = '') \
                   AND source_id LIKE '/%'",
            )?;
            let rows = stmt.query_map([], |r| {
                Ok((parse_uuid(&r.get::<_, String>(0)?)?, r.get::<_, String>(1)?))
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        let derived: Vec<(Uuid, String)> = untagged
            .into_iter()
            .filter_map(|(id, source_id)| {
                project_path::from_transcript(&source_id).map(|slug| (id, slug))
            })
            .collect();
        self.refile_all(&derived)
    }

    /// `refile_on_tx` over many rows in bounded transactions, so a large
    /// backfill neither holds the writer lock for its whole run nor skips
    /// the sync log and outbox the way a bare UPDATE would.
    fn refile_all(&self, rows: &[(Uuid, String)]) -> Result<u64> {
        const BATCH: usize = 500;
        let mut changed = 0u64;
        for chunk in rows.chunks(BATCH) {
            changed += self.with_txn(|tx| {
                let mut n = 0u64;
                for (id, project) in chunk {
                    if self.refile_on_tx(tx, *id, project)? {
                        n += 1;
                    }
                }
                Ok(n)
            })?;
        }
        Ok(changed)
    }

    /// Undoes what consolidation did to explicit memories before
    /// `EXPLICIT_SOURCES` was excluded from it: every archived explicit raw
    /// returns to the hot tier and the indexes, every marker on an explicit
    /// raw is dropped so no later pass retires it again, and a distillate
    /// whose raws were all explicit is superseded by the oldest of them,
    /// since nothing it summarised is missing from recall any more. A
    /// distillate that also stands in for transcript raws stays live.
    /// Every change replicates the way consolidation's own writes do.
    pub fn restore_explicit_memories(&self) -> Result<ExplicitRestoreStats> {
        const BATCH: usize = 500;
        let marked: Vec<(Uuid, Uuid)> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(concat!(
                "SELECT dl.memory_id, dl.distilled_id FROM distillation_log dl \
                 JOIN memories m ON m.id = dl.memory_id WHERE m.source IN (",
                explicit_sources_list!(),
                ") ORDER BY m.created_at, m.id"
            ))?;
            let rows = stmt.query_map([], |r| {
                Ok((
                    parse_uuid(&r.get::<_, String>(0)?)?,
                    parse_uuid(&r.get::<_, String>(1)?)?,
                ))
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };

        // Decided before any marker is dropped, because the rule is about
        // the distillate's full set of raws and dropping rows would hide it.
        let mut all_explicit: Vec<(Uuid, Uuid)> = Vec::new();
        {
            let conn = self.reader();
            let mut seen = std::collections::HashSet::new();
            for (raw_id, distilled_id) in &marked {
                if raw_id == distilled_id || !seen.insert(*distilled_id) {
                    continue;
                }
                let other: i64 = conn.query_row(
                    concat!(
                        "SELECT COUNT(*) FROM distillation_log dl \
                         JOIN memories m ON m.id = dl.memory_id \
                         WHERE dl.distilled_id = ?1 AND m.source NOT IN (",
                        explicit_sources_list!(),
                        ")"
                    ),
                    params![distilled_id.to_string()],
                    |r| r.get(0),
                )?;
                if other == 0 {
                    all_explicit.push((*distilled_id, *raw_id));
                }
            }
        }

        let mut stats = ExplicitRestoreStats::default();
        for chunk in marked.chunks(BATCH) {
            let (restored, dropped) = self.with_txn(|tx| {
                let mut restored = 0u64;
                let mut dropped = 0u64;
                for (raw_id, _) in chunk {
                    if self.unarchive_on_tx(tx, *raw_id)? {
                        restored += 1;
                    }
                    if self.drop_marker_on_tx(tx, *raw_id)? {
                        dropped += 1;
                    }
                }
                Ok((restored, dropped))
            })?;
            stats.raws_restored += restored;
            stats.markers_dropped += dropped;
        }
        for chunk in all_explicit.chunks(BATCH) {
            stats.distillates_superseded += self.with_txn(|tx| {
                let mut n = 0u64;
                for (distilled_id, by) in chunk {
                    if self.supersede_on_tx(tx, *distilled_id, *by)? {
                        n += 1;
                    }
                }
                Ok(n)
            })?;
        }
        Ok(stats)
    }

    /// Inverse of `archive_on_tx` for a locally archived row: the content
    /// and embedding are still there, so flipping the tier and queueing an
    /// upsert puts it back in both indexes. A row archived to a segment has
    /// only a stub left and cannot be restored this way.
    fn unarchive_on_tx(&self, tx: &Transaction<'_>, memory_id: Uuid) -> Result<bool> {
        let changed = tx.execute(
            "UPDATE memories SET tier = 'hot', updated_at = ?2 \
             WHERE id = ?1 AND tier = 'archived' AND archived_segment IS NULL \
               AND retired_reason IS NULL",
            params![memory_id.to_string(), Utc::now().to_rfc3339()],
        )?;
        if changed == 0 {
            return Ok(false);
        }
        Self::append_outbox(tx, memory_id, "upsert")?;
        if let Some(memory) = Self::memory_on_tx(tx, memory_id)? {
            self.log_memory_update(tx, &memory)?;
        }
        Ok(true)
    }

    /// The drop names the distillate it removes, so it cannot remove a
    /// newer marker a peer re-distilled into another one.
    pub(crate) fn drop_marker_on_tx(&self, tx: &Transaction<'_>, raw_id: Uuid) -> Result<bool> {
        let Some((marker, row)) = authored_order::marker_stamp(tx, raw_id)? else {
            return Ok(false);
        };
        authored_order::empty_marker_slot(tx, raw_id, &row)?;
        let authored = self.authored_now(tx)?;
        let stamp = Stamp::of(authored.timestamp_micros(), &self.machine_id, &marker)?;
        let key = authored_order::marker_key(raw_id, marker.distilled_id);
        authored_order::record_tombstone(tx, "distillation", &key, &stamp.tombstone())?;
        let data = authored_order::data_with_updated_by(&marker, &self.machine_id)?;
        self.append_local_log_at(
            tx,
            SyncOp::Delete,
            SyncNodeType::Distillation,
            &raw_id.to_string(),
            Some(&data),
            authored,
        )?;
        Ok(true)
    }

    pub(crate) fn mark_consolidated_on_tx(
        &self,
        tx: &Transaction<'_>,
        raw_id: Uuid,
        distilled_id: Uuid,
        model: &str,
    ) -> Result<()> {
        self.mark_distillation_on_tx(tx, raw_id, distilled_id, model, "legacy")
    }

    pub(super) fn mark_distillation_on_tx(
        &self,
        tx: &Transaction<'_>,
        raw_id: Uuid,
        distilled_id: Uuid,
        model: &str,
        status: &str,
    ) -> Result<()> {
        let authored = self.authored_now(tx)?;
        let entry = Distillation {
            memory_id: raw_id,
            distilled_id: Some(distilled_id),
            distilled_at: DateTime::from_timestamp_micros(clock::wall_now(self.clock.as_ref())?),
            model: Some(model.to_string()),
            status: status.to_string(),
        };
        let stamp = Stamp::of(authored.timestamp_micros(), &self.machine_id, &entry)?;
        if let MarkerClaim::Skipped(_) = Self::claim_marker_slot(tx, &entry, &stamp)? {
            return Ok(());
        }
        let data = authored_order::data_with_updated_by(&entry, &self.machine_id)?;
        // Logged so peers learn the memory is spoken for. Unlogged, every
        // machine redistills the same corpus against one shared GPU.
        self.append_local_log_at(
            tx,
            SyncOp::Create,
            SyncNodeType::Distillation,
            &raw_id.to_string(),
            Some(&data),
            authored,
        )
    }

    /// Re-files memories that an older adapter filed under the directory
    /// holding the transcript file (`subagents`, `agent-transcripts`) rather
    /// than the project directory under the `projects` root. Raws re-file
    /// from their own `source_id`; a distillate re-files to the project most
    /// of its raws now carry, because a consolidation batch is grouped by
    /// conversation and one project is the only value that fits a row with a
    /// single `project_path`, or to the project in its own `source_id` when
    /// no raw is left to vote. Every changed row is replicated as an Update
    /// and queued for the indexes, exactly as `update_memory` does.
    pub fn refile_nested_transcript_projects(&self) -> Result<u64> {
        const NESTED: &str = "('subagents', 'agent-transcripts')";

        let raws: Vec<(Uuid, String)> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(&format!(
                "SELECT id, source_id FROM memories \
                 WHERE project_path IN {NESTED} AND source <> 'consolidation'"
            ))?;
            let rows = stmt.query_map([], |r| {
                Ok((parse_uuid(&r.get::<_, String>(0)?)?, r.get::<_, String>(1)?))
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        let raws: Vec<(Uuid, String)> = raws
            .into_iter()
            .filter_map(|(id, source_id)| {
                project_path::from_transcript(&source_id).map(|s| (id, s))
            })
            .collect();
        let mut changed = self.refile_all(&raws)?;

        let distillates: Vec<(Uuid, Option<String>, String)> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(&format!(
                "SELECT d.id, \
                   (SELECT r.project_path FROM distillation_log dl \
                      JOIN memories r ON r.id = dl.memory_id \
                    WHERE dl.distilled_id = d.id AND dl.memory_id <> dl.distilled_id \
                      AND r.project_path IS NOT NULL AND r.project_path NOT IN {NESTED} \
                    GROUP BY r.project_path ORDER BY COUNT(*) DESC, r.project_path LIMIT 1), \
                   d.source_id \
                 FROM memories d \
                 WHERE d.source = 'consolidation' AND d.project_path IN {NESTED}"
            ))?;
            let rows = stmt.query_map([], |r| {
                Ok((
                    parse_uuid(&r.get::<_, String>(0)?)?,
                    r.get::<_, Option<String>>(1)?,
                    r.get::<_, String>(2)?,
                ))
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };
        // A distillate whose raws were purged still names its conversation
        // directory in `source_id`, so that is the fallback.
        let distillates: Vec<(Uuid, String)> = distillates
            .into_iter()
            .filter_map(|(id, slug, source_id)| {
                slug.or_else(|| project_path::from_transcript(&source_id))
                    .map(|s| (id, s))
            })
            .collect();
        changed += self.refile_all(&distillates)?;
        Ok(changed)
    }

    /// Re-files explicit memories that an earlier `remember` filed under the
    /// bare directory name it was given (`wardrobe`) instead of the slug
    /// ingest stores for that directory (`-mnt-data-wardrobe`). A bare name
    /// resolves to the stored slugs ending in `-<name>`, with `name` encoded
    /// the way Claude Code encodes a path; the two spellings Claude Code and
    /// Cursor give one directory (with and without the leading `-`) count as
    /// one project. A name matching more than one project is reported, never
    /// guessed, and transcript rows under a bare slug are left alone because
    /// an adapter filed them there on purpose.
    pub fn refile_stray_project_slugs(&self) -> Result<StraySlugReport> {
        let slugs: Vec<(String, u64, bool, bool)> = {
            let conn = self.reader();
            let mut stmt = conn.prepare(concat!(
                "SELECT project_path, \
                   SUM(tier = 'hot' AND superseded_by IS NULL), \
                   MAX(source IN (",
                explicit_sources_list!(),
                ")), MAX(",
                distillable_source!("source"),
                ") FROM memories \
                 WHERE project_path IS NOT NULL AND project_path <> '' \
                 GROUP BY project_path ORDER BY project_path"
            ))?;
            let rows = stmt.query_map([], |r| {
                Ok((
                    r.get::<_, String>(0)?,
                    r.get::<_, i64>(1)? as u64,
                    r.get::<_, i64>(2)? != 0,
                    r.get::<_, i64>(3)? != 0,
                ))
            })?;
            rows.collect::<rusqlite::Result<Vec<_>>>()?
        };

        let mut report = StraySlugReport::default();
        for (stray, _, has_explicit, has_transcripts) in &slugs {
            if !has_explicit || stray.starts_with('-') || stray.contains('/') {
                continue;
            }
            let suffix = format!("-{}", project_path::encode(stray));
            let mut projects: Vec<Vec<(&String, u64)>> = Vec::new();
            for (slug, live, _, _) in &slugs {
                if slug == stray || !slug.ends_with(&suffix) {
                    continue;
                }
                let bare = slug.trim_start_matches('-');
                match projects
                    .iter_mut()
                    .find(|p| p[0].0.trim_start_matches('-') == bare)
                {
                    Some(project) => project.push((slug, *live)),
                    None => projects.push(vec![(slug, *live)]),
                }
            }
            let target = match projects.as_slice() {
                // A Cursor slug has no leading `-` and so looks like a bare
                // name; its transcripts show it is a project, not a stray.
                [] => {
                    if !has_transcripts {
                        report.unresolved.push(stray.clone());
                    }
                    continue;
                }
                [spellings] => spellings
                    .iter()
                    .max_by_key(|(slug, live)| (*live, slug.starts_with('-')))
                    .map(|(slug, _)| (*slug).clone())
                    .expect("a project group is never empty"),
                _ => {
                    report.ambiguous.push(AmbiguousSlug {
                        slug: stray.clone(),
                        candidates: projects
                            .iter()
                            .flat_map(|p| p.iter().map(|(slug, _)| (*slug).clone()))
                            .collect(),
                    });
                    continue;
                }
            };

            let ids: Vec<Uuid> = {
                let conn = self.reader();
                let mut stmt = conn.prepare(concat!(
                    "SELECT id FROM memories WHERE project_path = ?1 AND source IN (",
                    explicit_sources_list!(),
                    ")"
                ))?;
                let rows =
                    stmt.query_map(params![stray], |r| parse_uuid(&r.get::<_, String>(0)?))?;
                rows.collect::<rusqlite::Result<Vec<_>>>()?
            };
            let rows: Vec<(Uuid, String)> =
                ids.into_iter().map(|id| (id, target.clone())).collect();
            let moved = self.refile_all(&rows)?;
            if moved > 0 {
                report.memories_refiled += moved;
                report.refiled.push(RefiledSlug {
                    from: stray.clone(),
                    to: target,
                    memories: moved,
                });
            }
        }
        Ok(report)
    }

    /// Moves one memory to `project_path`, replicated and re-indexed as
    /// every refile is. False when it was already filed there or is absent.
    pub fn refile_memory(&self, id: Uuid, project_path: &str) -> Result<bool> {
        self.with_txn(|tx| self.refile_on_tx(tx, id, project_path))
    }

    fn refile_on_tx(&self, tx: &Transaction<'_>, id: Uuid, project_path: &str) -> Result<bool> {
        let changed = tx.execute(
            "UPDATE memories SET project_path = ?2, updated_at = ?3 \
             WHERE id = ?1 AND project_path IS NOT ?2",
            params![id.to_string(), project_path, Utc::now().to_rfc3339()],
        )?;
        if changed == 0 {
            return Ok(false);
        }
        Self::append_outbox(tx, id, "upsert")?;
        if let Some(memory) = Self::memory_on_tx(tx, id)? {
            self.log_memory_update(tx, &memory)?;
        }
        Ok(true)
    }

    /// Local maintenance purge (re-ingest path): no tombstones and no sync-log
    /// entries, matching the kuzu behavior, so a re-ingest of the same source
    /// can store fresh rows; outbox rows still evict the old ids from the
    /// indexes. Adapters mint new v4 ids on re-ingest, so nothing collides.
    fn purge_memories_where(&self, predicate: &str, value: &str) -> Result<usize> {
        self.with_txn(|tx| {
            let ids: Vec<String> = {
                let mut stmt = tx.prepare(&format!("SELECT id FROM memories WHERE {predicate}"))?;
                let rows = stmt.query_map(params![value], |r| r.get::<_, String>(0))?;
                rows.collect::<rusqlite::Result<Vec<_>>>()?
            };
            for id in &ids {
                tx.execute(
                    "DELETE FROM relations WHERE from_id = ?1 OR to_id = ?1",
                    params![id],
                )?;
                if let Ok(uuid) = Uuid::parse_str(id) {
                    Self::append_outbox(tx, uuid, "delete")?;
                }
                // The watcher purges a file's memories on every re-ingest. Without a
                // tombstone and a logged delete the removal never reaches a peer, and
                // the peer's surviving copy is pushed straight back on the next sync.
                let authored = self.authored_now(tx)?;
                Self::upsert_tombstone(tx, id, "memory", &self.machine_id, authored)?;
                self.append_local_log_at(
                    tx,
                    SyncOp::Delete,
                    SyncNodeType::Memory,
                    id,
                    None,
                    authored,
                )?;
            }
            tx.execute(
                &format!("DELETE FROM memories WHERE {predicate}"),
                params![value],
            )?;
            Ok(ids.len())
        })
    }
}

const INGEST_LOG_COLS: &str = "file_path, file_hash, content_hash, session_key, legacy_ids";

fn row_to_ingest_log_entry(r: &rusqlite::Row<'_>) -> rusqlite::Result<IngestLogEntry> {
    Ok(IngestLogEntry {
        file_path: r.get(0)?,
        file_hash: r.get(1)?,
        content_hash: r.get(2)?,
        session_key: r.get(3)?,
        legacy_ids: r.get::<_, i64>(4)? != 0,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{MemoryType, Tier};
    use crate::sqlite_store::TRAVERSE_MAX_RESULTS;

    fn store() -> SqliteStore {
        SqliteStore::in_memory("machine-a".to_string()).unwrap()
    }

    fn memory(content: &str) -> Memory {
        Memory::new(
            content.to_string(),
            MemoryType::Semantic,
            "test".to_string(),
            String::new(),
        )
    }

    fn record(
        op: SyncOp,
        node_type: SyncNodeType,
        node_id: String,
        data: Option<serde_json::Value>,
    ) -> SyncRecord {
        SyncRecord {
            local_seq: 1,
            origin_machine_id: "machine-b".to_string(),
            origin_seq: 1,
            op,
            node_type,
            node_id,
            timestamp: Utc::now(),
            data,
        }
    }

    fn deletes_for(s: &SqliteStore, id: Uuid) -> usize {
        s.sync_log_since(0)
            .unwrap()
            .into_iter()
            .filter(|e| e.op == SyncOp::Delete && e.node_id == id.to_string())
            .count()
    }

    fn outbox_rows(s: &SqliteStore) -> i64 {
        s.reader()
            .query_row("SELECT COUNT(*) FROM index_outbox", [], |r| r.get(0))
            .unwrap()
    }

    fn orphan_tombstone(s: &SqliteStore, id: Uuid) {
        s.with_txn(|tx| {
            SqliteStore::upsert_tombstone(tx, &id.to_string(), "memory", "machine-a", Utc::now())
        })
        .unwrap();
    }

    #[test]
    fn skip_reasons_distinguish_convergence_from_data_loss() {
        let s = store();
        let m = memory("already here");
        s.store_memory(&m).unwrap();
        let dup = record(
            SyncOp::Create,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&m).unwrap()),
        );
        assert_eq!(
            s.apply_record(&dup).unwrap(),
            ApplyOutcome::Skipped(SkipReason::AlreadyPresent),
            "a re-sent record the store already has is routine convergence"
        );

        let ghost = Relation {
            from_id: Uuid::new_v4(),
            to_id: Uuid::new_v4(),
            relation_type: RelationType::Mentions,
            strength: 1.0,
            context: None,
        };
        let edge = record(
            SyncOp::Create,
            SyncNodeType::Relation,
            format!("{}:{}:mentions", ghost.from_id, ghost.to_id),
            Some(serde_json::to_value(&ghost).unwrap()),
        );
        assert_eq!(
            s.apply_record(&edge).unwrap(),
            ApplyOutcome::Skipped(SkipReason::DanglingEndpoint),
            "an edge that can never resolve must be distinguishable from convergence"
        );
    }

    #[test]
    fn unconsolidated_memories_orders_by_source_id_then_created_at() {
        let s = store();
        let mk = |content: &str, source_id: &str, created_at: chrono::DateTime<Utc>| {
            let mut m = memory(content);
            m.source_id = source_id.to_string();
            m.created_at = created_at;
            m
        };
        let base = Utc::now();
        // Stored out of order so a naive fetch (no ORDER BY) would not
        // happen to come back grouped; the assertion below only holds if
        // the query itself sorts.
        let b_second = mk("b turn 2", "conv-b", base + chrono::Duration::seconds(10));
        let a_second = mk("a turn 2", "conv-a", base + chrono::Duration::seconds(10));
        let b_first = mk("b turn 1", "conv-b", base);
        let a_first = mk("a turn 1", "conv-a", base);
        for m in [&b_second, &a_second, &b_first, &a_first] {
            s.store_memory(m).unwrap();
        }

        let fetched = s.unconsolidated_memories(100).unwrap();
        let order: Vec<&str> = fetched.iter().map(|m| m.content.as_str()).collect();

        assert_eq!(
            order,
            vec!["a turn 1", "a turn 2", "b turn 1", "b turn 2"],
            "fetch must group by source_id and order each group by created_at"
        );
    }

    #[test]
    fn consolidation_state_replicates_so_a_peer_does_not_redistill() {
        let source = store();
        let raw = memory("raw memory to distill");
        source.store_memory(&raw).unwrap();
        let distilled = memory("distilled summary");
        source.store_memory(&distilled).unwrap();

        let peer = SqliteStore::in_memory("machine-peer".to_string()).unwrap();
        peer.store_memory(&raw).unwrap();
        let pending = |st: &SqliteStore| {
            st.unconsolidated_memories(100)
                .unwrap()
                .iter()
                .any(|m| m.id == raw.id)
        };
        assert!(
            pending(&peer),
            "precondition: the peer still sees the raw memory as work to do"
        );

        source
            .mark_consolidated(raw.id, distilled.id, "gemma4-e2b")
            .unwrap();
        assert!(!pending(&source));

        for entry in source.sync_log_since(0).unwrap() {
            if entry.node_type != SyncNodeType::Distillation {
                continue;
            }
            let data = entry
                .data
                .as_ref()
                .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok());
            let rec = record(entry.op, entry.node_type, entry.node_id.clone(), data);
            peer.apply_record(&rec).unwrap();
        }

        assert!(
            !pending(&peer),
            "the peer must learn the memory was already distilled, or it burns GPU redoing it"
        );
        // The distillate itself has not arrived: the raw must neither be
        // retired (it is the only copy of that knowledge here) nor have its
        // marker treated as orphaned (nothing was deleted, it is in flight).
        assert_eq!(peer.consolidation_stats().unwrap().raw_retire_pending, 0);
        assert_eq!(
            peer.integrity_report(None)
                .unwrap()
                .orphaned_distillation_markers,
            0
        );
        peer.store_memory(&distilled).unwrap();
        assert_eq!(peer.consolidation_stats().unwrap().raw_retire_pending, 1);
    }

    #[test]
    fn replaying_a_distillation_record_is_idempotent() {
        let s = store();
        let raw = memory("raw");
        s.store_memory(&raw).unwrap();
        let dist = memory("distilled");
        s.store_memory(&dist).unwrap();
        s.mark_consolidated(raw.id, dist.id, "gemma4-e2b").unwrap();

        let entry = s
            .sync_log_since(0)
            .unwrap()
            .into_iter()
            .find(|e| e.node_type == SyncNodeType::Distillation)
            .expect("mark_consolidated must log a distillation record");
        let data = entry
            .data
            .as_ref()
            .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok());
        let rec = SyncRecord {
            timestamp: entry.timestamp,
            ..record(
                SyncOp::Create,
                SyncNodeType::Distillation,
                entry.node_id,
                data,
            )
        };

        assert_eq!(
            s.apply_record(&rec).unwrap(),
            ApplyOutcome::Skipped(SkipReason::AlreadyPresent)
        );
        assert_eq!(s.consolidation_stats().unwrap().raw_retire_pending, 1);
    }

    #[test]
    fn retire_is_idempotent_and_logs_one_update_per_raw() {
        let s = store();
        let raw = memory("raw memory to distill");
        s.store_memory(&raw).unwrap();
        let dist = memory("distilled summary");
        s.store_memory(&dist).unwrap();
        s.mark_consolidated(raw.id, dist.id, "gemma4-e2b").unwrap();

        assert_eq!(s.retire_consolidated_raws().unwrap(), 1);
        assert_eq!(
            s.get_memory(raw.id).unwrap().unwrap().tier,
            crate::schema::Tier::Archived
        );
        assert_eq!(deletes_for(&s, raw.id), 0, "retirement never deletes");
        let log_after_first = s.sync_log_since(0).unwrap().len();
        let outbox_after_first = outbox_rows(&s);

        assert_eq!(
            s.retire_consolidated_raws().unwrap(),
            0,
            "a second pass has no hot raws left to retire"
        );
        assert_eq!(
            s.sync_log_since(0).unwrap().len(),
            log_after_first,
            "re-running retire must not re-log an update"
        );
        assert_eq!(
            outbox_rows(&s),
            outbox_after_first,
            "re-running retire must not re-queue index work"
        );
    }

    #[test]
    fn deleting_an_already_deleted_memory_records_nothing_new() {
        let s = store();
        let m = memory("deleted once, asked for twice");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();

        let log_len = s.sync_log_since(0).unwrap().len();
        let outbox = outbox_rows(&s);

        s.delete_memory(m.id).unwrap();

        assert_eq!(
            s.sync_log_since(0).unwrap().len(),
            log_len,
            "the deletion is already asserted to peers; repeating it adds no information"
        );
        assert_eq!(outbox_rows(&s), outbox);
        assert!(
            s.tombstone_exists(m.id).unwrap(),
            "the tombstone must survive the repeat delete"
        );
    }

    #[test]
    fn deleting_a_memory_this_machine_never_had_records_nothing() {
        let s = store();
        let absent = Uuid::new_v4();
        let outbox = outbox_rows(&s);

        assert!(!s.remove_memory(absent).unwrap());

        assert!(
            !s.tombstone_exists(absent).unwrap(),
            "nothing was removed, so there is nothing to tombstone or tell peers"
        );
        assert_eq!(deletes_for(&s, absent), 0);
        assert_eq!(outbox_rows(&s), outbox);
    }

    #[test]
    fn remove_memory_reports_whether_a_row_existed() {
        let s = store();
        let m = memory("held here");
        s.store_memory(&m).unwrap();

        assert!(s.remove_memory(m.id).unwrap());
        assert!(s.tombstone_exists(m.id).unwrap());
        assert_eq!(deletes_for(&s, m.id), 1);

        assert!(!s.remove_memory(m.id).unwrap());
        assert_eq!(deletes_for(&s, m.id), 1);
    }

    #[test]
    fn backfill_covers_distillation_rows_written_before_they_were_syncable() {
        let s = store();
        let raw = memory("raw");
        s.store_memory(&raw).unwrap();
        let dist = memory("distilled");
        s.store_memory(&dist).unwrap();
        s.mark_consolidated(raw.id, dist.id, "gemma4-e2b").unwrap();

        s.with_txn(|tx| {
            tx.execute("DELETE FROM sync_log", [])?;
            Ok(())
        })
        .unwrap();

        s.backfill_sync_log().unwrap();
        let distillations = s
            .sync_log_since(0)
            .unwrap()
            .into_iter()
            .filter(|e| e.node_type == SyncNodeType::Distillation)
            .count();
        assert_eq!(
            distillations, 1,
            "the 3577 rows already on disk must become syncable, not stay stranded"
        );
    }

    #[test]
    fn distinct_project_paths_counts_live_memories_per_project() {
        let s = store();
        let mut a1 = memory("a1");
        a1.project_path = Some("project-a".to_string());
        s.store_memory(&a1).unwrap();
        let mut a2 = memory("a2");
        a2.project_path = Some("project-a".to_string());
        s.store_memory(&a2).unwrap();
        let mut b1 = memory("b1");
        b1.project_path = Some("project-b".to_string());
        s.store_memory(&b1).unwrap();
        s.store_memory(&memory("no project")).unwrap();
        let mut archived = memory("a3, consolidated away");
        archived.project_path = Some("project-a".to_string());
        archived.tier = Tier::Archived;
        s.store_memory(&archived).unwrap();
        let mut superseded = memory("b2, superseded");
        superseded.project_path = Some("project-b".to_string());
        superseded.superseded_by = Some(b1.id);
        s.store_memory(&superseded).unwrap();
        let mut only_archived = memory("c1, nothing live left");
        only_archived.project_path = Some("project-c".to_string());
        only_archived.tier = Tier::Archived;
        s.store_memory(&only_archived).unwrap();

        let mut counts = s.distinct_project_paths().unwrap();
        counts.sort_by(|a, b| a.0.cmp(&b.0));

        assert_eq!(
            counts,
            vec![("project-a".to_string(), 2), ("project-b".to_string(), 1),]
        );
    }

    #[test]
    fn a_source_scope_admits_distillates_of_that_source() {
        let s = store();
        let raw = explicit("cursor transcript chunk about wombats", "cursor");
        let mut distillate = explicit("wombats, distilled", "consolidation");
        distillate.embedding = vec![1.0; 4];
        let mut other = explicit("wombats from another source", "claude-code");
        other.embedding = vec![1.0; 4];
        for m in [&raw, &distillate, &other] {
            s.store_memory(m).unwrap();
        }
        s.mark_consolidated(raw.id, distillate.id, "model").unwrap();

        assert!(s.source_admits(&distillate, "cursor").unwrap());
        assert!(!s.source_admits(&other, "cursor").unwrap());
        assert!(!s.source_admits(&distillate, "claude-code").unwrap());

        assert_eq!(s.scoped_count(Some("cursor"), None, None).unwrap(), 2);
        let kept = s
            .retain_in_scope(
                &[raw.id, distillate.id, other.id],
                Some("cursor"),
                None,
                None,
            )
            .unwrap();
        assert!(kept.contains(&distillate.id) && kept.contains(&raw.id));
        assert!(!kept.contains(&other.id));

        let text: Vec<Uuid> = s
            .scoped_text_search("wombats", Some("cursor"), None, None, 10)
            .unwrap()
            .into_iter()
            .map(|m| m.id)
            .collect();
        assert!(text.contains(&distillate.id) && !text.contains(&other.id));

        let dense: Vec<Uuid> = s
            .filtered_vector_search(&[1.0; 4], Some("cursor"), None, None, 10)
            .unwrap()
            .into_iter()
            .map(|(m, _)| m.id)
            .collect();
        assert_eq!(dense, vec![distillate.id]);
    }

    #[test]
    fn record_accesses_bumps_counts_without_touching_confidence() {
        let s = store();
        let mut a = memory("read twice");
        a.confidence = 0.5;
        let b = memory("read once");
        let untouched = memory("never read");
        for m in [&a, &b, &untouched] {
            s.store_memory(m).unwrap();
        }
        let log_len = s.sync_log_since(0).unwrap().len();
        let before = Utc::now();

        s.record_accesses(&[a.id, b.id]).unwrap();
        s.record_accesses(&[a.id, Uuid::new_v4()]).unwrap();

        let a = s.get_memory(a.id).unwrap().unwrap();
        assert_eq!(a.access_count, 2);
        assert_eq!(a.confidence, 0.5);
        assert!(a.last_accessed >= before);
        let b = s.get_memory(b.id).unwrap().unwrap();
        assert_eq!(b.access_count, 1);
        let untouched = s.get_memory(untouched.id).unwrap().unwrap();
        assert_eq!(untouched.access_count, 0);
        assert_eq!(
            s.sync_log_since(0).unwrap().len(),
            log_len,
            "access counts are local statistics, never synced"
        );
    }

    fn in_project(content: &str, project: &str, created: DateTime<Utc>) -> Memory {
        let mut m = memory(content);
        m.project_path = Some(project.to_string());
        m.created_at = created;
        m
    }

    #[test]
    fn memories_by_project_path_returns_live_rows_newest_first() {
        let s = store();
        let t0 = Utc::now() - chrono::Duration::days(3);
        let old = in_project("old", "loom", t0);
        let new = in_project("new", "loom", t0 + chrono::Duration::days(1));
        let mut archived = in_project("archived", "loom", t0 + chrono::Duration::days(2));
        archived.tier = Tier::Archived;
        let mut superseded = in_project("superseded", "loom", t0 + chrono::Duration::days(2));
        superseded.superseded_by = Some(new.id);
        let elsewhere = in_project("elsewhere", "other", t0 + chrono::Duration::days(2));
        for m in [&old, &new, &archived, &superseded, &elsewhere] {
            s.store_memory(m).unwrap();
        }

        let ids: Vec<Uuid> = s
            .memories_by_project_path("loom")
            .unwrap()
            .into_iter()
            .map(|m| m.id)
            .collect();
        assert_eq!(ids, vec![new.id, old.id]);
    }

    #[test]
    fn memories_by_project_path_keeps_the_twenty_row_bound() {
        let s = store();
        let t0 = Utc::now() - chrono::Duration::days(1);
        for i in 0..25 {
            s.store_memory(&in_project(
                &format!("row {i}"),
                "loom",
                t0 + chrono::Duration::minutes(i),
            ))
            .unwrap();
        }
        let rows = s.memories_by_project_path("loom").unwrap();
        assert_eq!(rows.len(), 20);
        assert_eq!(rows[0].content, "row 24");
    }

    fn mentions(memory_id: Uuid, entity_id: Uuid) -> Relation {
        Relation {
            from_id: memory_id,
            to_id: entity_id,
            relation_type: RelationType::Mentions,
            strength: 1.0,
            context: None,
        }
    }

    #[test]
    fn traverse_reaches_live_memories_through_shared_entities_conversations_and_edges() {
        let s = store();
        let entity = Entity::new("wombat".to_string(), "animal".to_string());
        s.store_entity(&entity).unwrap();
        let conversation = Uuid::new_v4();

        let mut start = memory("start");
        start.conversation_id = Some(conversation);
        let via_entity = memory("shares the wombat entity");
        let mut via_conversation = memory("same conversation");
        via_conversation.conversation_id = Some(conversation);
        let via_reverse_edge = memory("relates_to start, edge pointing at start");
        let mut archived_peer = memory("archived, shares the entity");
        archived_peer.tier = Tier::Archived;
        let mut superseded_peer = memory("superseded, same conversation");
        superseded_peer.conversation_id = Some(conversation);
        superseded_peer.superseded_by = Some(start.id);
        let unrelated = memory("nothing in common");
        for m in [
            &start,
            &via_entity,
            &via_conversation,
            &via_reverse_edge,
            &archived_peer,
            &superseded_peer,
            &unrelated,
        ] {
            s.store_memory(m).unwrap();
        }
        s.store_relation(&mentions(start.id, entity.id)).unwrap();
        s.store_relation(&mentions(via_entity.id, entity.id))
            .unwrap();
        s.store_relation(&mentions(archived_peer.id, entity.id))
            .unwrap();
        s.store_relation(&Relation {
            from_id: via_reverse_edge.id,
            to_id: start.id,
            relation_type: RelationType::RelatesTo,
            strength: 1.0,
            context: None,
        })
        .unwrap();

        let mut got: Vec<Uuid> = s
            .traverse(start.id, 1)
            .unwrap()
            .into_iter()
            .map(|(m, _)| m.id)
            .collect();
        got.sort();
        let mut want = vec![via_entity.id, via_conversation.id, via_reverse_edge.id];
        want.sort();
        assert_eq!(got, want);
    }

    #[test]
    fn traverse_depth_bounds_how_far_a_shared_entity_carries() {
        let s = store();
        let near = Entity::new("near".to_string(), "thing".to_string());
        let far = Entity::new("far".to_string(), "thing".to_string());
        s.store_entity(&near).unwrap();
        s.store_entity(&far).unwrap();
        let start = memory("start");
        let hop = memory("one hop away");
        let two_hops = memory("two hops away");
        for m in [&start, &hop, &two_hops] {
            s.store_memory(m).unwrap();
        }
        s.store_relation(&mentions(start.id, near.id)).unwrap();
        s.store_relation(&mentions(hop.id, near.id)).unwrap();
        s.store_relation(&mentions(hop.id, far.id)).unwrap();
        s.store_relation(&mentions(two_hops.id, far.id)).unwrap();

        let ids = |depth: u32| -> Vec<Uuid> {
            let mut v: Vec<Uuid> = s
                .traverse(start.id, depth)
                .unwrap()
                .into_iter()
                .map(|(m, _)| m.id)
                .collect();
            v.sort();
            v
        };
        assert_eq!(ids(1), vec![hop.id]);
        let mut want = vec![hop.id, two_hops.id];
        want.sort();
        assert_eq!(ids(2), want);
        assert!(!ids(2).contains(&start.id));
    }

    #[test]
    fn traverse_result_count_is_bounded() {
        let s = store();
        let hub = Entity::new("hub".to_string(), "thing".to_string());
        s.store_entity(&hub).unwrap();
        let start = memory("start");
        s.store_memory(&start).unwrap();
        s.store_relation(&mentions(start.id, hub.id)).unwrap();
        for i in 0..(TRAVERSE_MAX_RESULTS + 10) {
            let m = memory(&format!("peer {i}"));
            s.store_memory(&m).unwrap();
            s.store_relation(&mentions(m.id, hub.id)).unwrap();
        }
        assert_eq!(s.traverse(start.id, 1).unwrap().len(), TRAVERSE_MAX_RESULTS);
    }

    #[test]
    fn scoped_text_search_returns_the_newest_matches_first() {
        let s = store();
        let t0 = Utc::now() - chrono::Duration::days(3);
        let oldest = in_project("wombat sighting one", "zoo", t0);
        let middle = in_project("wombat sighting two", "zoo", t0 + chrono::Duration::days(1));
        let newest = in_project(
            "wombat sighting three",
            "zoo",
            t0 + chrono::Duration::days(2),
        );
        for m in [&oldest, &middle, &newest] {
            s.store_memory(m).unwrap();
        }

        let ids: Vec<Uuid> = s
            .scoped_text_search("wombat", None, None, Some("zoo"), 2)
            .unwrap()
            .into_iter()
            .map(|m| m.id)
            .collect();
        assert_eq!(ids, vec![newest.id, middle.id]);
    }

    fn explicit(content: &str, source: &str) -> Memory {
        let mut m = memory(content);
        m.source = source.to_string();
        m
    }

    #[test]
    fn explicit_memories_are_neither_distilled_nor_retired() {
        let s = store();
        let remembered = explicit("remembered on purpose", "mcp-direct");
        let via_api = explicit("posted to /v1/remember", "api");
        let memory_file = explicit("from a claude memory file", "claude-memory");
        let from_cli = explicit("sb remember from a terminal", "cli");
        let transcript = explicit("a transcript chunk", "claude-code");
        for m in [&remembered, &via_api, &memory_file, &from_cli, &transcript] {
            s.store_memory(m).unwrap();
        }

        let pending: Vec<Uuid> = s
            .unconsolidated_memories(10)
            .unwrap()
            .into_iter()
            .map(|m| m.id)
            .collect();
        assert_eq!(pending, vec![transcript.id]);
        assert_eq!(s.consolidation_stats().unwrap().raw_pending, 1);

        let dist = explicit("a paraphrase", "consolidation");
        s.store_memory(&dist).unwrap();
        s.mark_consolidated(remembered.id, dist.id, "model")
            .unwrap();
        s.mark_consolidated(transcript.id, dist.id, "model")
            .unwrap();
        assert_eq!(s.consolidation_stats().unwrap().raw_retire_pending, 1);
        assert_eq!(s.retire_consolidated_raws().unwrap(), 1);
        assert_eq!(
            s.get_memory(remembered.id).unwrap().unwrap().tier,
            crate::schema::Tier::Hot,
            "a marker on an explicit memory must never retire it"
        );
        assert_eq!(
            s.get_memory(transcript.id).unwrap().unwrap().tier,
            crate::schema::Tier::Archived
        );
    }

    #[test]
    fn the_undistillable_source_sql_list_matches_the_rust_lists() {
        let sql = crate::schema::distillable_source!("source");
        let lists = [
            crate::schema::EXPLICIT_SOURCES,
            crate::schema::DOCUMENT_SOURCES,
        ];
        for source in lists.concat() {
            assert!(sql.contains(&format!("'{source}'")), "{sql}");
        }
        assert_eq!(
            sql.matches('\'').count() / 2,
            lists.concat().len() + 1,
            "the SQL list holds exactly the explicit and document sources plus 'consolidation'"
        );
    }

    fn filed(content: &str, source: &str, project: &str) -> Memory {
        explicit(content, source).with_project_path(Some(project.to_string()))
    }

    #[test]
    fn stray_short_slugs_move_to_the_one_project_they_name() {
        let s = store();
        let rows = [
            filed("wardrobe transcript", "claude-code", "-mnt-data-wardrobe"),
            filed("wardrobe remembered", "mcp-direct", "wardrobe"),
            filed(
                "accounting transcript",
                "claude-code",
                "home-anish-alayacare-services-api-accounting",
            ),
            filed("accounting remembered", "api", "api-accounting"),
            filed("loom transcript", "claude-code", "-mnt-data-loom"),
            filed("loom via cursor", "cursor", "mnt-data-loom"),
            filed("loom remembered", "mcp-direct", "loom"),
            filed("harness transcript", "claude-code", "-mnt-data-harness"),
            filed(
                "my-harness transcript",
                "claude-code",
                "-mnt-data-my-harness",
            ),
            filed("harness remembered", "mcp-direct", "harness"),
            filed("probe remembered", "mcp-direct", "tmp-skillprobe-1"),
            filed("a transcript under a bare slug", "cursor", "wardrobe"),
        ];
        for m in &rows {
            s.store_memory(m).unwrap();
        }
        let project = |m: &Memory| s.get_memory(m.id).unwrap().unwrap().project_path.unwrap();
        let log_before = s.max_sync_seq().unwrap();

        let report = s.refile_stray_project_slugs().unwrap();
        assert_eq!(project(&rows[1]), "-mnt-data-wardrobe");
        assert_eq!(
            project(&rows[3]),
            "home-anish-alayacare-services-api-accounting"
        );
        assert_eq!(
            project(&rows[6]),
            "-mnt-data-loom",
            "two spellings of one directory are one project, not an ambiguity"
        );
        assert_eq!(
            project(&rows[9]),
            "harness",
            "an ambiguous name is not guessed"
        );
        assert_eq!(project(&rows[10]), "tmp-skillprobe-1");
        assert_eq!(
            project(&rows[11]),
            "wardrobe",
            "only explicit memories were filed by the unresolved remember"
        );
        assert_eq!(report.memories_refiled, 3);
        let ambiguous: Vec<&str> = report.ambiguous.iter().map(|a| a.slug.as_str()).collect();
        assert_eq!(ambiguous, vec!["harness"]);
        assert_eq!(
            report.ambiguous[0].candidates,
            vec![
                "-mnt-data-harness".to_string(),
                "-mnt-data-my-harness".to_string()
            ]
        );
        assert_eq!(s.sync_log_since(log_before).unwrap().len(), 3);

        assert_eq!(report.unresolved, vec!["tmp-skillprobe-1".to_string()]);

        let again = s.refile_stray_project_slugs().unwrap();
        assert_eq!(again.memories_refiled, 0);
        assert_eq!(
            again.unresolved,
            vec!["tmp-skillprobe-1".to_string()],
            "a transcript project that received refiled memories is not itself a stray"
        );
        assert_eq!(s.sync_log_since(log_before).unwrap().len(), 3);
    }

    #[test]
    fn restore_explicit_memories_leaves_a_forgotten_memory_retired() {
        let s = store();
        let forgotten = explicit("explicit, then forgotten", "mcp-direct");
        let distillate = explicit("distilled from the forgotten one", "consolidation");
        s.store_memory(&forgotten).unwrap();
        s.store_memory(&distillate).unwrap();
        s.mark_consolidated(forgotten.id, distillate.id, "model")
            .unwrap();
        s.retire_memory(forgotten.id, "wrong").unwrap();

        let stats = s.restore_explicit_memories().unwrap();
        assert_eq!(stats.raws_restored, 0);
        assert_eq!(
            s.get_memory(forgotten.id).unwrap().unwrap().tier,
            crate::schema::Tier::Archived
        );
    }

    #[test]
    fn restore_explicit_memories_returns_them_to_recall_and_supersedes_their_distillates() {
        let s = store();
        let e1 = explicit("explicit, archived", "mcp-direct");
        let e2 = explicit("explicit, marked but still hot", "claude-memory");
        let e3 = explicit(
            "explicit, archived, shares a distillate with a transcript",
            "api",
        );
        let raw = explicit("transcript chunk", "claude-code");
        let all_explicit = explicit("distilled from e1 and e2 only", "consolidation");
        let mixed = explicit("distilled from e3 and a transcript", "consolidation");
        for m in [&e1, &e2, &e3, &raw, &all_explicit, &mixed] {
            s.store_memory(m).unwrap();
        }
        for (r, d) in [
            (&e1, &all_explicit),
            (&e2, &all_explicit),
            (&e3, &mixed),
            (&raw, &mixed),
        ] {
            s.mark_consolidated(r.id, d.id, "model").unwrap();
        }
        for id in [e1.id, e3.id, raw.id] {
            s.archive_memory(id).unwrap();
        }
        let log_before = s.sync_log_since(0).unwrap().len();
        let outbox_before = outbox_rows(&s);

        let stats = s.restore_explicit_memories().unwrap();
        assert_eq!(
            stats.raws_restored, 2,
            "e1 and e3 were archived; e2 was still hot"
        );
        assert_eq!(stats.markers_dropped, 3);
        assert_eq!(stats.distillates_superseded, 1);

        for id in [e1.id, e2.id, e3.id] {
            let m = s.get_memory(id).unwrap().unwrap();
            assert_eq!(m.tier, crate::schema::Tier::Hot);
            assert!(m.superseded_by.is_none());
        }
        let marked: i64 = s
            .reader()
            .query_row(
                "SELECT COUNT(*) FROM distillation_log WHERE memory_id IN (?1, ?2, ?3)",
                params![e1.id.to_string(), e2.id.to_string(), e3.id.to_string()],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(marked, 0, "a restored memory must not be retired again");
        assert_eq!(
            s.get_memory(raw.id).unwrap().unwrap().tier,
            crate::schema::Tier::Archived,
            "a transcript raw stays retired"
        );

        let all_explicit_after = s.get_memory(all_explicit.id).unwrap().unwrap();
        assert!(
            [Some(e1.id), Some(e2.id)].contains(&all_explicit_after.superseded_by),
            "a distillate made only of explicit memories yields to one of them"
        );
        assert!(
            s.get_memory(mixed.id)
                .unwrap()
                .unwrap()
                .superseded_by
                .is_none(),
            "a distillate still standing in for a transcript raw stays live"
        );

        let new_entries: Vec<SyncEntry> = s.sync_log_since(log_before as u64).unwrap();
        let updates: Vec<String> = new_entries
            .iter()
            .filter(|e| e.op == SyncOp::Update && e.node_type == SyncNodeType::Memory)
            .map(|e| e.node_id.clone())
            .collect();
        for id in [e1.id, e3.id, all_explicit.id] {
            assert!(updates.contains(&id.to_string()), "{id} must replicate");
        }
        let marker_deletes = new_entries
            .iter()
            .filter(|e| e.op == SyncOp::Delete && e.node_type == SyncNodeType::Distillation)
            .count();
        assert_eq!(marker_deletes, 3, "peers must forget the markers too");
        assert_eq!(
            outbox_rows(&s) - outbox_before,
            3,
            "restored rows and the superseded distillate re-enter the indexes"
        );

        let again = s.restore_explicit_memories().unwrap();
        assert_eq!(
            (
                again.raws_restored,
                again.markers_dropped,
                again.distillates_superseded
            ),
            (0, 0, 0)
        );
    }

    #[test]
    fn refile_nested_transcript_projects_moves_raws_and_their_distillates() {
        let s = store();
        let raw = |content: &str, source_id: &str, project: &str| {
            let mut m = memory(content);
            m.source = "claude-code".to_string();
            m.source_id = source_id.to_string();
            m.project_path = Some(project.to_string());
            s.store_memory(&m).unwrap();
            m
        };
        let loom = "/home/u/.claude/projects/-mnt-data-loom/sess/subagents/agent-1.jsonl";
        let kiln = "/home/u/.claude/projects/-mnt-data-kiln/sess/subagents/agent-2.jsonl";
        let sub_a = raw("loom subagent a", loom, "subagents");
        let sub_b = raw("loom subagent b", loom, "subagents");
        let sub_c = raw("kiln subagent", kiln, "subagents");
        let cursor = raw(
            "cursor agent transcript",
            "/home/u/.cursor/projects/mnt-data-harness/agent-transcripts/s1/s1.jsonl",
            "agent-transcripts",
        );
        let rootless = raw(
            "no projects root in its path",
            "/srv/dump/agent-3.jsonl",
            "subagents",
        );
        let filed = raw("already filed", loom, "-mnt-data-loom");

        let mut dist = memory("distilled from two loom raws and one kiln raw");
        dist.source = "consolidation".to_string();
        dist.project_path = Some("subagents".to_string());
        s.store_memory(&dist).unwrap();
        for r in [&sub_a, &sub_b, &sub_c] {
            s.mark_consolidated(r.id, dist.id, "model").unwrap();
        }

        let log_before = s.sync_log_since(0).unwrap().len();
        let outbox_before = outbox_rows(&s);

        assert_eq!(s.refile_nested_transcript_projects().unwrap(), 5);

        let project = |id: Uuid| s.get_memory(id).unwrap().unwrap().project_path;
        for id in [sub_a.id, sub_b.id, filed.id] {
            assert_eq!(project(id).as_deref(), Some("-mnt-data-loom"));
        }
        assert_eq!(project(sub_c.id).as_deref(), Some("-mnt-data-kiln"));
        assert_eq!(project(cursor.id).as_deref(), Some("mnt-data-harness"));
        assert_eq!(
            project(dist.id).as_deref(),
            Some("-mnt-data-loom"),
            "a distillate follows the majority project of its raws"
        );
        assert_eq!(
            project(rootless.id).as_deref(),
            Some("subagents"),
            "a path without a projects root cannot be re-filed"
        );

        let updates = s
            .sync_log_since(log_before as u64)
            .unwrap()
            .into_iter()
            .filter(|e| e.op == SyncOp::Update)
            .count();
        assert_eq!(updates, 5, "every re-filed row is replicated as an update");
        assert_eq!(outbox_rows(&s) - outbox_before, 5);

        assert_eq!(s.refile_nested_transcript_projects().unwrap(), 0);
    }

    #[test]
    fn refile_nested_transcript_projects_files_an_orphaned_distillate_by_its_source_id() {
        let s = store();
        let distillate = |content: &str, source_id: &str| {
            let mut m = memory(content);
            m.source = "consolidation".to_string();
            m.source_id = source_id.to_string();
            m.project_path = Some("subagents".to_string());
            s.store_memory(&m).unwrap();
            m
        };
        let orphan = distillate(
            "its raws were purged",
            "/home/u/.claude/projects/-mnt-data-loom/sess/",
        );
        let raw = {
            let mut m = memory("a raw that is later purged");
            m.source = "claude-code".to_string();
            m.project_path = Some("-mnt-data-kiln".to_string());
            s.store_memory(&m).unwrap();
            m
        };
        let purged = distillate(
            "distilled from a raw that is gone",
            "/home/u/.claude/projects/-mnt-data-kiln/sess/",
        );
        s.mark_consolidated(raw.id, purged.id, "model").unwrap();
        s.delete_memory(raw.id).unwrap();
        let rootless = distillate("no projects root", "/srv/dump/");

        assert_eq!(s.refile_nested_transcript_projects().unwrap(), 2);
        let project = |id: Uuid| s.get_memory(id).unwrap().unwrap().project_path;
        assert_eq!(project(orphan.id).as_deref(), Some("-mnt-data-loom"));
        assert_eq!(project(purged.id).as_deref(), Some("-mnt-data-kiln"));
        assert_eq!(project(rootless.id).as_deref(), Some("subagents"));
        assert_eq!(s.refile_nested_transcript_projects().unwrap(), 0);
    }

    #[test]
    fn backfill_project_paths_files_by_the_project_directory_and_replicates() {
        let s = store();
        let mut with_path = memory("has a path-shaped source_id");
        with_path.source_id = "/home/user/.claude/projects/-my-project/abc.jsonl".to_string();
        s.store_memory(&with_path).unwrap();

        let mut already_tagged = memory("already has a project_path");
        already_tagged.source_id = "/home/user/.claude/projects/-my-project/def.jsonl".to_string();
        already_tagged.project_path = Some("keep-me".to_string());
        s.store_memory(&already_tagged).unwrap();

        let unrooted = memory("source_id is not path-shaped");
        s.store_memory(&unrooted).unwrap();

        let mut nested = memory("a subagent transcript chunk");
        nested.source_id =
            "/home/user/.claude/projects/-my-project/abc/subagents/agent-1.jsonl".to_string();
        s.store_memory(&nested).unwrap();

        let log_before = s.max_sync_seq().unwrap();
        let outbox_before = outbox_rows(&s);
        let changed = s.backfill_project_paths().unwrap();

        assert_eq!(changed, 2, "only the untagged, path-shaped rows backfill");
        assert_eq!(
            s.get_memory(nested.id).unwrap().unwrap().project_path,
            Some("-my-project".to_string()),
            "a nested transcript is filed under the project directory, not `subagents`"
        );
        assert_eq!(
            s.sync_log_since(log_before).unwrap().len(),
            2,
            "every backfilled row is replicated"
        );
        assert_eq!(outbox_rows(&s) - outbox_before, 2);
        assert_eq!(s.backfill_project_paths().unwrap(), 0);
        assert_eq!(
            s.get_memory(with_path.id).unwrap().unwrap().project_path,
            Some("-my-project".to_string())
        );
        assert_eq!(
            s.get_memory(already_tagged.id)
                .unwrap()
                .unwrap()
                .project_path,
            Some("keep-me".to_string()),
            "an existing project_path must not be overwritten"
        );
        assert_eq!(
            s.get_memory(unrooted.id).unwrap().unwrap().project_path,
            None
        );
    }

    #[test]
    fn prune_dangling_relations_drops_only_unresolvable_edges() {
        let s = store();
        let m = memory("live endpoint");
        s.store_memory(&m).unwrap();
        let ent = Entity {
            id: Uuid::new_v4(),
            name: "kuzu".to_string(),
            entity_type: "tool".to_string(),
            embedding: vec![],
            aliases: vec![],
        };
        s.store_entity(&ent).unwrap();

        s.store_relation(&Relation {
            from_id: m.id,
            to_id: ent.id,
            relation_type: RelationType::Mentions,
            strength: 1.0,
            context: None,
        })
        .unwrap();
        // from_id points at a memory that no longer exists anywhere, the shape the
        // importer refuses and the local store has no foreign key to prevent.
        s.store_relation(&Relation {
            from_id: Uuid::new_v4(),
            to_id: ent.id,
            relation_type: RelationType::Mentions,
            strength: 1.0,
            context: None,
        })
        .unwrap();
        assert_eq!(s.all_relations().unwrap().len(), 2);

        assert_eq!(s.prune_dangling_relations().unwrap(), 1);

        let left = s.all_relations().unwrap();
        assert_eq!(left.len(), 1);
        assert_eq!(left[0].from_id, m.id, "the valid edge must survive");

        assert_eq!(
            s.prune_dangling_relations().unwrap(),
            0,
            "prune must be idempotent"
        );
    }

    #[test]
    fn pruned_relation_deletion_reaches_a_peer() {
        let s = store();
        let ent = Entity {
            id: Uuid::new_v4(),
            name: "kuzu".to_string(),
            entity_type: "tool".to_string(),
            embedding: vec![],
            aliases: vec![],
        };
        s.store_entity(&ent).unwrap();
        let ghost = Uuid::new_v4();
        let dangling = Relation {
            from_id: ghost,
            to_id: ent.id,
            relation_type: RelationType::Mentions,
            strength: 1.0,
            context: None,
        };
        s.store_relation(&dangling).unwrap();

        // A peer that still holds the edge because its endpoint was alive there.
        let peer = SqliteStore::in_memory("machine-peer".to_string()).unwrap();
        let mut ghost_memory = memory("endpoint alive on the peer");
        ghost_memory.id = ghost;
        peer.store_memory(&ghost_memory).unwrap();
        peer.store_entity(&ent).unwrap();
        peer.store_relation(&dangling).unwrap();
        assert_eq!(peer.all_relations().unwrap().len(), 1);

        let before = s.sync_log_since(0).unwrap().len() as u64;
        s.prune_dangling_relations().unwrap();

        for entry in s.sync_log_since(before).unwrap() {
            if entry.op != SyncOp::Delete || entry.node_type != SyncNodeType::Relation {
                continue;
            }
            let data = entry
                .data
                .as_ref()
                .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok());
            let rec = record(
                SyncOp::Delete,
                SyncNodeType::Relation,
                entry.node_id.clone(),
                data,
            );
            peer.apply_record(&rec).unwrap();
        }

        assert_eq!(
            peer.all_relations().unwrap().len(),
            0,
            "the prune must propagate, not just clean the local store"
        );
    }

    #[test]
    fn backfill_stamps_each_row_with_the_create_it_logs() {
        let s = store();
        let (m, raw, dist) = (memory("endpoint"), memory("raw"), memory("distilled"));
        for memory in [&m, &raw, &dist] {
            s.store_memory(memory).unwrap();
        }
        let conv = Conversation {
            id: Uuid::new_v4(),
            source: "claude-code".to_string(),
            machine_id: "machine-a".to_string(),
            started_at: Utc::now(),
            project_path: None,
        };
        s.store_conversation(&conv).unwrap();
        s.store_entity(&Entity::new("kuzu".to_string(), "tool".to_string()))
            .unwrap();
        s.store_relation(&Relation {
            from_id: m.id,
            to_id: conv.id,
            relation_type: RelationType::DerivedFrom,
            strength: 1.0,
            context: None,
        })
        .unwrap();
        s.mark_consolidated(raw.id, dist.id, "model").unwrap();
        s.with_txn(|tx| {
            tx.execute_batch(
                "DELETE FROM sync_log;
                 UPDATE entities SET updated_at = 0, updated_by = '';
                 UPDATE conversations SET updated_at = 0, updated_by = '';
                 UPDATE relations SET updated_at = 0, updated_by = '';
                 UPDATE distillation_log SET updated_at = 0, updated_by = '';",
            )?;
            Ok(())
        })
        .unwrap();

        s.backfill_sync_log().unwrap();

        let stamp_sql = |node_type: SyncNodeType| match node_type {
            SyncNodeType::Entity => "SELECT updated_at, updated_by FROM entities WHERE id = ?1",
            SyncNodeType::Conversation => {
                "SELECT updated_at, updated_by FROM conversations WHERE id = ?1"
            }
            SyncNodeType::Relation => {
                "SELECT updated_at, updated_by FROM relations \
                 WHERE from_id || ':' || to_id || ':' || relation_type = ?1"
            }
            SyncNodeType::Distillation => {
                "SELECT updated_at, updated_by FROM distillation_log WHERE memory_id = ?1"
            }
            SyncNodeType::Memory => unreachable!(),
        };
        let entries: Vec<_> = s
            .sync_log_since(0)
            .unwrap()
            .into_iter()
            .filter(|e| e.node_type != SyncNodeType::Memory)
            .collect();
        assert_eq!(entries.len(), 4);
        for entry in entries {
            let data: serde_json::Value =
                serde_json::from_str(entry.data.as_deref().unwrap()).unwrap();
            let row: (i64, String) = s
                .reader()
                .query_row(stamp_sql(entry.node_type), params![entry.node_id], |r| {
                    Ok((r.get(0)?, r.get(1)?))
                })
                .unwrap();
            assert_eq!(
                row,
                (
                    entry.timestamp.timestamp_micros(),
                    data["updated_by"].as_str().unwrap().to_string()
                ),
                "{:?} row stamp",
                entry.node_type
            );
        }
    }

    #[test]
    fn backfill_covers_entities_conversations_and_relations_not_just_memories() {
        let s = store();
        let m = memory("endpoint memory");
        s.store_memory(&m).unwrap();
        let conv = Conversation {
            id: Uuid::new_v4(),
            source: "claude-code".to_string(),
            machine_id: "machine-a".to_string(),
            started_at: Utc::now(),
            project_path: Some("/tmp/p".to_string()),
        };
        s.store_conversation(&conv).unwrap();
        let ent = Entity {
            id: Uuid::new_v4(),
            name: "kuzu".to_string(),
            entity_type: "tool".to_string(),
            embedding: vec![],
            aliases: vec![],
        };
        s.store_entity(&ent).unwrap();
        s.store_relation(&Relation {
            from_id: m.id,
            to_id: conv.id,
            relation_type: RelationType::DerivedFrom,
            strength: 1.0,
            context: None,
        })
        .unwrap();

        // Strip the log to simulate rows that predate it, the state the kuzu-era
        // migration left behind for entities and conversations.
        s.with_txn(|tx| {
            tx.execute("DELETE FROM sync_log", [])?;
            Ok(())
        })
        .unwrap();
        assert_eq!(s.sync_log_since(0).unwrap().len(), 0);

        assert_eq!(s.backfill_sync_log().unwrap(), 4);

        let by_type = |nt: SyncNodeType| {
            s.sync_log_since(0)
                .unwrap()
                .into_iter()
                .filter(|e| e.node_type == nt)
                .count()
        };
        assert_eq!(by_type(SyncNodeType::Memory), 1);
        assert_eq!(by_type(SyncNodeType::Conversation), 1);
        assert_eq!(by_type(SyncNodeType::Entity), 1);
        assert_eq!(by_type(SyncNodeType::Relation), 1);

        assert_eq!(
            s.backfill_sync_log().unwrap(),
            0,
            "backfill must be idempotent across every node type"
        );
    }

    #[test]
    fn backfilled_relation_applies_on_a_peer_once_its_endpoints_exist() {
        let s = store();
        let m = memory("endpoint memory");
        s.store_memory(&m).unwrap();
        let conv = Conversation {
            id: Uuid::new_v4(),
            source: "claude-code".to_string(),
            machine_id: "machine-a".to_string(),
            started_at: Utc::now(),
            project_path: None,
        };
        s.store_conversation(&conv).unwrap();
        s.store_relation(&Relation {
            from_id: m.id,
            to_id: conv.id,
            relation_type: RelationType::DerivedFrom,
            strength: 1.0,
            context: None,
        })
        .unwrap();
        s.with_txn(|tx| {
            tx.execute("DELETE FROM sync_log", [])?;
            Ok(())
        })
        .unwrap();
        s.backfill_sync_log().unwrap();

        let peer = SqliteStore::in_memory("machine-peer".to_string()).unwrap();
        for entry in s.sync_log_since(0).unwrap() {
            let data = entry
                .data
                .as_ref()
                .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok());
            let rec = record(entry.op, entry.node_type, entry.node_id.clone(), data);
            peer.apply_record(&rec).unwrap();
        }

        assert_eq!(
            peer.all_relations().unwrap().len(),
            1,
            "a backfilled relation must apply once its endpoints have been backfilled too"
        );
    }

    #[test]
    fn purging_by_source_id_tombstones_and_logs_each_delete() {
        let s = store();
        let mut m = memory("ingested from a file that later changed");
        m.source_id = "/tmp/transcript.jsonl".to_string();
        s.store_memory(&m).unwrap();

        assert_eq!(
            s.delete_memories_by_source_id("/tmp/transcript.jsonl")
                .unwrap(),
            1
        );

        let deletes: Vec<_> = s
            .sync_log_since(0)
            .unwrap()
            .into_iter()
            .filter(|e| e.op == SyncOp::Delete)
            .collect();
        assert_eq!(
            deletes.len(),
            1,
            "a purge must log the delete or it can never reach a peer"
        );
        assert_eq!(deletes[0].node_id, m.id.to_string());

        assert_eq!(
            s.backfill_tombstones().unwrap(),
            0,
            "the purge must also leave a tombstone, or the peer copy is resurrected"
        );
    }

    #[test]
    fn purged_memory_is_deleted_on_a_peer_rather_than_resurrected() {
        let source = store();
        let mut m = memory("superseded by a newer version of the file");
        m.source_id = "/tmp/transcript.jsonl".to_string();
        source.store_memory(&m).unwrap();

        let peer = SqliteStore::in_memory("machine-peer".to_string()).unwrap();
        peer.store_memory(&m).unwrap();

        source
            .delete_memories_by_source_id("/tmp/transcript.jsonl")
            .unwrap();

        for entry in source.sync_log_since(0).unwrap() {
            if entry.op != SyncOp::Delete {
                continue;
            }
            let rec = record(
                SyncOp::Delete,
                SyncNodeType::Memory,
                entry.node_id.clone(),
                None,
            );
            peer.apply_record(&rec).unwrap();
        }

        assert!(
            peer.get_memory(m.id).unwrap().is_none(),
            "the peer must drop its copy of a purged memory"
        );

        let recreate = record(
            SyncOp::Create,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&m).unwrap()),
        );
        peer.apply_record(&recreate).unwrap();
        assert!(
            peer.get_memory(m.id).unwrap().is_none(),
            "the tombstone must stop the purged memory coming back on the next sync"
        );
    }

    #[test]
    fn backfill_tombstones_emits_a_delete_for_every_orphaned_tombstone() {
        let s = store();
        let m = memory("deleted without a logged delete");
        s.store_memory(&m).unwrap();
        s.with_txn(|tx| {
            tx.execute(
                "DELETE FROM memories WHERE id = ?1",
                params![m.id.to_string()],
            )?;
            Ok(())
        })
        .unwrap();
        orphan_tombstone(&s, m.id);

        let deletes = |s: &SqliteStore| {
            s.sync_log_since(0)
                .unwrap()
                .into_iter()
                .filter(|e| e.op == SyncOp::Delete)
                .collect::<Vec<_>>()
        };
        assert!(
            deletes(&s).is_empty(),
            "precondition: tombstone has no delete entry"
        );

        assert_eq!(s.backfill_tombstones().unwrap(), 1);
        let got = deletes(&s);
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].node_id, m.id.to_string());
        assert_eq!(got[0].node_type, SyncNodeType::Memory);

        assert_eq!(
            s.backfill_tombstones().unwrap(),
            0,
            "must be idempotent, not re-emit a delete on every run"
        );
    }

    #[test]
    fn backfill_tombstones_skips_tombstones_that_already_logged_a_delete() {
        let s = store();
        let m = memory("deleted through the normal path");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();

        let before = s.sync_log_since(0).unwrap().len();
        assert_eq!(s.backfill_tombstones().unwrap(), 0);
        assert_eq!(s.sync_log_since(0).unwrap().len(), before);
    }

    #[test]
    fn backfilled_delete_survives_export_and_deletes_on_a_peer() {
        let source = store();
        let m = memory("purged here, still alive on the peer");
        source.store_memory(&m).unwrap();
        source
            .with_txn(|tx| {
                tx.execute(
                    "DELETE FROM memories WHERE id = ?1",
                    params![m.id.to_string()],
                )?;
                Ok(())
            })
            .unwrap();
        orphan_tombstone(&source, m.id);
        assert_eq!(source.backfill_tombstones().unwrap(), 1);

        let peer = SqliteStore::in_memory("machine-peer".to_string()).unwrap();
        peer.store_memory(&m).unwrap();
        assert!(peer.get_memory(m.id).unwrap().is_some());

        for entry in source.sync_log_since(0).unwrap() {
            if entry.op != SyncOp::Delete {
                continue;
            }
            let rec = record(
                SyncOp::Delete,
                SyncNodeType::Memory,
                entry.node_id.clone(),
                None,
            );
            peer.apply_record(&rec).unwrap();
        }

        assert!(
            peer.get_memory(m.id).unwrap().is_none(),
            "the backfilled delete must actually remove the memory on the peer"
        );
    }

    #[test]
    fn create_is_idempotent_and_respects_tombstones() {
        let s = store();
        let m = memory("incoming create");
        let rec = record(
            SyncOp::Create,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&m).unwrap()),
        );
        assert!(matches!(
            s.apply_record(&rec).unwrap(),
            ApplyOutcome::Created
        ));
        assert!(matches!(
            s.apply_record(&rec).unwrap(),
            ApplyOutcome::Skipped(SkipReason::AlreadyPresent)
        ));

        s.delete_memory(m.id).unwrap();
        assert!(
            matches!(
                s.apply_record(&rec).unwrap(),
                ApplyOutcome::Skipped(SkipReason::Tombstoned)
            ),
            "a tombstoned id must never be resurrected by a replayed create"
        );
    }

    #[test]
    fn update_lww_prefers_newer_updated_at() {
        let s = store();
        let mut m = memory("lww base");
        s.store_memory(&m).unwrap();

        let mut older = m.clone();
        older.content = "stale writer".to_string();
        older.updated_at = m.updated_at - chrono::Duration::seconds(60);
        let stale = record(
            SyncOp::Update,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&older).unwrap()),
        );
        assert!(matches!(
            s.apply_record(&stale).unwrap(),
            ApplyOutcome::Skipped(SkipReason::StaleWrite)
        ));
        assert_eq!(s.get_memory(m.id).unwrap().unwrap().content, "lww base");

        m.content = "fresh writer".to_string();
        m.updated_at += chrono::Duration::seconds(60);
        let fresh = record(
            SyncOp::Update,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&m).unwrap()),
        );
        assert!(matches!(
            s.apply_record(&fresh).unwrap(),
            ApplyOutcome::Updated
        ));
        assert_eq!(s.get_memory(m.id).unwrap().unwrap().content, "fresh writer");
    }

    fn session(at: &str) -> DateTime<Utc> {
        at.parse().unwrap()
    }

    fn sync_log_rows(s: &SqliteStore) -> i64 {
        s.reader()
            .query_row("SELECT COUNT(*) FROM sync_log", [], |r| r.get(0))
            .unwrap()
    }

    #[test]
    fn an_update_that_wins_lww_without_a_date_keeps_the_stored_date() {
        let s = store();
        let mut m = memory("dated here");
        m.session_at = Some(session("2026-07-23T09:00:00Z"));
        s.store_memory(&m).unwrap();

        let mut newer = m.clone();
        newer.session_at = None;
        newer.content = "edited on a peer that has no date".to_string();
        newer.updated_at += chrono::Duration::seconds(60);
        let update = record(
            SyncOp::Update,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&newer).unwrap()),
        );
        assert!(matches!(
            s.apply_record(&update).unwrap(),
            ApplyOutcome::Updated
        ));

        let stored = s.get_memory(m.id).unwrap().unwrap();
        assert_eq!(stored.content, "edited on a peer that has no date");
        assert_eq!(stored.session_at, m.session_at);
    }

    #[test]
    fn an_update_that_loses_lww_fills_only_a_missing_date() {
        let s = store();
        let m = memory("undated here");
        s.store_memory(&m).unwrap();
        let superseder = memory("the newer fact");
        s.store_memory(&superseder).unwrap();
        s.supersede_memory(m.id, superseder.id).unwrap();
        let before = s.get_memory(m.id).unwrap().unwrap();
        let log_before = sync_log_rows(&s);
        let outbox_before = outbox_rows(&s);

        let mut stale = m.clone();
        stale.session_at = Some(session("2026-07-23T09:00:00Z"));
        stale.content = "stale content must not land".to_string();
        let update = record(
            SyncOp::Update,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&stale).unwrap()),
        );
        assert!(matches!(
            s.apply_record(&update).unwrap(),
            ApplyOutcome::Skipped(SkipReason::StaleWrite)
        ));

        let after = s.get_memory(m.id).unwrap().unwrap();
        assert_eq!(after.session_at, stale.session_at);
        assert_eq!(after.content, before.content);
        assert_eq!(after.updated_at, before.updated_at);
        assert_eq!(after.tier, before.tier);
        assert_eq!(after.superseded_by, Some(superseder.id));
        assert_eq!(sync_log_rows(&s), log_before, "a fill is not relogged");
        assert_eq!(outbox_rows(&s), outbox_before, "a date is not indexed");

        let mut other = stale.clone();
        other.session_at = Some(session("2026-01-01T00:00:00Z"));
        s.apply_record(&record(
            SyncOp::Update,
            SyncNodeType::Memory,
            m.id.to_string(),
            Some(serde_json::to_value(&other).unwrap()),
        ))
        .unwrap();
        assert_eq!(
            s.get_memory(m.id).unwrap().unwrap().session_at,
            stale.session_at,
            "a losing update never overwrites a known date"
        );
    }

    #[test]
    fn batch_is_atomic_across_a_failing_record() {
        let s = store();
        let good = memory("good batch record");
        let records = vec![
            record(
                SyncOp::Create,
                SyncNodeType::Memory,
                good.id.to_string(),
                Some(serde_json::to_value(&good).unwrap()),
            ),
            // Missing data makes this record fail parsing mid-batch.
            record(
                SyncOp::Create,
                SyncNodeType::Memory,
                Uuid::new_v4().to_string(),
                None,
            ),
        ];
        assert!(s.apply_batch(&records).is_err());
        assert!(
            s.get_memory(good.id).unwrap().is_none(),
            "a failed batch must roll back every record, including the good prefix"
        );
        assert!(
            matches!(s.apply_record(&records[0]).unwrap(), ApplyOutcome::Created),
            "per-record fallback after a rolled-back batch must not double-apply"
        );
    }

    #[test]
    fn relation_with_missing_endpoint_is_skipped() {
        let s = store();
        let a = memory("relation endpoint present");
        s.store_memory(&a).unwrap();
        let rel = Relation {
            from_id: a.id,
            to_id: Uuid::new_v4(),
            relation_type: RelationType::RelatesTo,
            strength: 1.0,
            context: None,
        };
        let rec = record(
            SyncOp::Create,
            SyncNodeType::Relation,
            format!("{}:{}:relates_to", rel.from_id, rel.to_id),
            Some(serde_json::to_value(&rel).unwrap()),
        );
        assert!(matches!(
            s.apply_record(&rec).unwrap(),
            ApplyOutcome::Skipped(SkipReason::DanglingEndpoint)
        ));
    }

    /// Directly inserts a `sync_log` delete row exactly the way the fixed
    /// `delete_memory` re-logging bug used to: a fresh local_seq and a
    /// distinct `machine:origin_seq` id, so it survives the id-uniqueness
    /// dedup guard in `append_sync_log`. This is the real shape duplicate
    /// rows took in the field, not a synthetic stand-in for it.
    fn inject_duplicate_delete(s: &SqliteStore, node_id: &str, machine_id: &str) -> i64 {
        s.with_txn(|tx| {
            let (local_seq, legacy_origin_seq): (i64, i64) = tx.query_row(
                "SELECT COALESCE(MAX(local_seq), 0) + 1, COUNT(*) + 1 FROM sync_log",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )?;
            let id = format!("{machine_id}:{legacy_origin_seq}");
            tx.execute(
                "INSERT INTO sync_log \
                 (id, local_seq, origin_machine_id, origin_seq, op, node_type, node_id, \
                  timestamp, data) \
                 VALUES (?1,?2,?3,?4,'delete','memory',?5,?6,NULL)",
                params![
                    id,
                    local_seq,
                    machine_id,
                    legacy_origin_seq,
                    node_id,
                    Utc::now().to_rfc3339()
                ],
            )?;
            Ok(local_seq)
        })
        .unwrap()
    }

    #[test]
    fn compact_sync_log_collapses_duplicates_keeping_the_latest_and_leaving_max_seq_unchanged() {
        let s = store();
        let m = memory("consolidated raw memory, re-deleted every cleanup cycle");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();
        assert_eq!(deletes_for(&s, m.id), 1, "precondition: one real delete");

        let mut last_injected = 0;
        for _ in 0..4 {
            last_injected = inject_duplicate_delete(&s, &m.id.to_string(), "machine-a");
        }
        assert_eq!(
            deletes_for(&s, m.id),
            5,
            "precondition: 1 real + 4 re-logged duplicates"
        );

        let max_before = s.max_sync_seq().unwrap();
        assert_eq!(
            max_before as i64, last_injected,
            "precondition: the last injected duplicate holds the current global max"
        );

        let stats = s.compact_sync_log(&[SyncOp::Delete], false).unwrap();

        assert_eq!(stats.groups_with_duplicates, 1);
        assert_eq!(stats.rows_deleted, 4);
        assert_eq!(stats.max_local_seq_before, stats.max_local_seq_after);
        assert_eq!(s.max_sync_seq().unwrap(), max_before);
        assert_eq!(
            deletes_for(&s, m.id),
            1,
            "must collapse to exactly one delete row"
        );

        let surviving_seq: i64 = s
            .reader()
            .query_row(
                "SELECT local_seq FROM sync_log WHERE node_id = ?1 AND op = 'delete'",
                params![m.id.to_string()],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(
            surviving_seq, last_injected,
            "the surviving row must be the highest local_seq, or the next write reuses \
             a sequence a peer already considers seen"
        );
    }

    #[test]
    fn compact_sync_log_is_idempotent() {
        let s = store();
        let m = memory("re-deleted repeatedly");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();
        for _ in 0..3 {
            inject_duplicate_delete(&s, &m.id.to_string(), "machine-a");
        }

        let first = s.compact_sync_log(&[SyncOp::Delete], false).unwrap();
        assert_eq!(first.rows_deleted, 3);

        let second = s.compact_sync_log(&[SyncOp::Delete], false).unwrap();
        assert_eq!(second.rows_deleted, 0);
        assert_eq!(second.groups_with_duplicates, 0);
        assert_eq!(deletes_for(&s, m.id), 1);
    }

    #[test]
    fn compact_sync_log_dry_run_reports_without_deleting() {
        let s = store();
        let m = memory("dry-run candidate");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();
        inject_duplicate_delete(&s, &m.id.to_string(), "machine-a");
        inject_duplicate_delete(&s, &m.id.to_string(), "machine-a");

        let stats = s.compact_sync_log(&[SyncOp::Delete], true).unwrap();
        assert_eq!(stats.rows_deleted, 2, "dry run reports the victim count");
        assert_eq!(
            deletes_for(&s, m.id),
            3,
            "dry run must not actually delete anything"
        );
    }

    #[test]
    fn compact_sync_log_leaves_a_single_delete_and_its_create_untouched() {
        let s = store();
        let untouched = memory("created once, never deleted");
        s.store_memory(&untouched).unwrap();
        let deleted_once = memory("created once, deleted once, never duplicated");
        s.store_memory(&deleted_once).unwrap();
        s.delete_memory(deleted_once.id).unwrap();

        let stats = s.compact_sync_log(&[SyncOp::Delete], false).unwrap();
        assert_eq!(
            stats.rows_deleted, 0,
            "nothing here is a duplicate, compaction must be a no-op"
        );

        let creates = |id: Uuid| {
            s.sync_log_since(0)
                .unwrap()
                .into_iter()
                .filter(|e| e.op == SyncOp::Create && e.node_id == id.to_string())
                .count()
        };
        assert_eq!(creates(untouched.id), 1);
        assert_eq!(creates(deleted_once.id), 1);
        assert_eq!(deletes_for(&s, deleted_once.id), 1);
    }

    #[test]
    fn compacted_sync_log_replays_to_the_same_tombstone_set_as_uncompacted() {
        let source = store();
        let m = memory("replicated to two peers, one before compaction, one after");
        source.store_memory(&m).unwrap();
        source.delete_memory(m.id).unwrap();
        for _ in 0..5 {
            inject_duplicate_delete(&source, &m.id.to_string(), "machine-a");
        }

        let apply_all = |peer: &SqliteStore| {
            for entry in source.sync_log_since(0).unwrap() {
                let data = entry
                    .data
                    .as_ref()
                    .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok());
                let rec = record(entry.op, entry.node_type, entry.node_id.clone(), data);
                // A peer may see the same duplicate id twice across two
                // different source states; only the terminal outcome matters.
                let _ = peer.apply_record(&rec);
            }
        };

        let peer_before = SqliteStore::in_memory("machine-peer-before".to_string()).unwrap();
        apply_all(&peer_before);

        source.compact_sync_log(&[SyncOp::Delete], false).unwrap();

        let peer_after = SqliteStore::in_memory("machine-peer-after".to_string()).unwrap();
        apply_all(&peer_after);

        assert_eq!(
            peer_before.tombstone_exists(m.id).unwrap(),
            peer_after.tombstone_exists(m.id).unwrap(),
            "compaction must not change what a peer converges to"
        );
        assert!(
            peer_after.tombstone_exists(m.id).unwrap(),
            "precondition: the delete must actually have propagated"
        );
    }

    #[test]
    fn delete_import_is_idempotent_and_does_not_relog() {
        let s = store();
        let m = memory("locally deleted, then re-sent by a peer as a duplicate");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();
        assert_eq!(deletes_for(&s, m.id), 1, "precondition: one real delete");
        let outbox_before = outbox_rows(&s);

        let rec = record(SyncOp::Delete, SyncNodeType::Memory, m.id.to_string(), None);
        assert_eq!(
            s.apply_record(&rec).unwrap(),
            ApplyOutcome::Skipped(SkipReason::Tombstoned),
            "a delete for an already-tombstoned node must be skipped, matching \
             how Create and Update already treat AlreadyPresent/Tombstoned"
        );
        assert_eq!(
            deletes_for(&s, m.id),
            1,
            "a redundant delete import must not mint a new sync_log row"
        );
        assert_eq!(
            outbox_rows(&s),
            outbox_before,
            "a redundant delete import must not requeue an index eviction"
        );
    }

    #[test]
    fn compacted_delete_does_not_regrow_when_the_same_record_is_reimported() {
        let s = store();
        let m = memory("regression test for the 2026-08-24 sync_log reinflation incident");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();
        for _ in 0..4 {
            inject_duplicate_delete(&s, &m.id.to_string(), "machine-a");
        }
        assert_eq!(
            deletes_for(&s, m.id),
            5,
            "precondition: 1 real + 4 duplicates"
        );

        let pre_compaction_entries: Vec<_> = s
            .sync_log_since(0)
            .unwrap()
            .into_iter()
            .filter(|e| e.op == SyncOp::Delete && e.node_id == m.id.to_string())
            .collect();

        let stats = s.compact_sync_log(&[SyncOp::Delete], false).unwrap();
        assert_eq!(stats.rows_deleted, 4);
        assert_eq!(
            deletes_for(&s, m.id),
            1,
            "precondition: compaction collapsed to one row"
        );

        // A peer that never compacted its own copy would re-send exactly these
        // (origin_machine_id, origin_seq) pairs on the next ordinary sync. A
        // compacted legacy key leaves no trace, so without a tombstone check on
        // import it reinflates the log right back: the actual mechanism behind
        // the 2026-08-24 incident. A new-layout key stays in sync_dedup.
        for entry in &pre_compaction_entries {
            let data = entry
                .data
                .as_ref()
                .and_then(|d| serde_json::from_str::<serde_json::Value>(d).ok());
            let rec = SyncRecord {
                local_seq: entry.local_seq as u64,
                origin_machine_id: entry.origin_machine_id.clone(),
                origin_seq: entry.origin_seq as u64,
                op: entry.op,
                node_type: entry.node_type,
                node_id: entry.node_id.clone(),
                timestamp: entry.timestamp,
                data,
            };
            let expected = if entry.origin_seq >= crate::sqlite_store::NEW_LAYOUT_MIN {
                SkipReason::AlreadyPresent
            } else {
                SkipReason::Tombstoned
            };
            let outcome = s.apply_record(&rec).unwrap();
            assert_eq!(
                outcome,
                ApplyOutcome::Skipped(expected),
                "a compacted-away duplicate must be rejected on reimport, not re-logged"
            );
        }

        assert_eq!(
            deletes_for(&s, m.id),
            1,
            "reimporting compacted-away duplicates must not regrow sync_log"
        );
    }

    #[test]
    fn backfill_tombstones_after_compaction_finds_nothing_to_backfill() {
        let s = store();
        let m = memory("compacted then checked for backfill gaps");
        s.store_memory(&m).unwrap();
        s.delete_memory(m.id).unwrap();
        for _ in 0..2 {
            inject_duplicate_delete(&s, &m.id.to_string(), "machine-a");
        }

        s.compact_sync_log(&[SyncOp::Delete], false).unwrap();

        assert_eq!(
            s.backfill_tombstones().unwrap(),
            0,
            "the compacted store must still have exactly one delete entry per tombstone"
        );
    }

    #[test]
    fn pending_distillation_counts_waiting_raws_and_dates_the_oldest() {
        let s = store();
        assert_eq!(
            s.pending_distillation().unwrap(),
            PendingDistillation::default()
        );

        let mut older = explicit("an older transcript chunk", "claude-code");
        older.created_at = Utc::now() - chrono::Duration::days(3);
        let newer = explicit("a newer transcript chunk", "claude-code");
        let note = explicit("remembered on purpose", "mcp-direct");
        let dist = explicit("a paraphrase", "consolidation");
        for m in [&older, &newer, &note, &dist] {
            s.store_memory(m).unwrap();
        }
        assert_eq!(
            s.pending_distillation().unwrap(),
            PendingDistillation {
                count: 2,
                oldest_created_at: Some(older.created_at),
            }
        );

        s.mark_consolidated(older.id, dist.id, "model").unwrap();
        assert_eq!(
            s.pending_distillation().unwrap(),
            PendingDistillation {
                count: 1,
                oldest_created_at: Some(newer.created_at),
            }
        );
    }
}