second-brain-core 0.5.1

Core library for second-brain: KuzuDB graph storage, BGE embeddings, and weighted query engine
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
use std::collections::HashMap;
use std::path::Path;
use std::sync::RwLock;

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use kuzu::{Connection, Database, SystemConfig, Value};
use uuid::Uuid;

use crate::schema::{
    Conversation, Entity, Memory, MemoryType, Relation, RelationType, SyncEntry, SyncNodeType,
    SyncOp, SyncState,
};
use crate::store::Store;

type RelationsCache = HashMap<(Uuid, Option<RelationType>), Vec<Relation>>;

pub enum ApplyOutcome {
    Created,
    Updated,
    Deleted,
    Skipped,
}

pub struct KuzuStore {
    db: Database,
    machine_id: String,
    // get_relations(id, rel_type) is deterministic and query-independent: its result
    // only changes when an edge rooted at `id` is created or removed. Caching between
    // such writes is correct, so every write path that touches a memory's outgoing
    // edges must evict the affected key (invariant enforced below).
    relations_cache: RwLock<RelationsCache>,
}

fn memory_return_cols(alias: &str) -> String {
    ["id", "content", "memory_type", "confidence", "created_at", "last_accessed", "access_count", "source", "source_id", "project_path", "machine_id", "updated_at"]
        .iter()
        .map(|col| format!("{alias}.{col}"))
        .collect::<Vec<_>>()
        .join(", ")
}

fn project_path_from_db(s: &str) -> Option<String> {
    if s.is_empty() { None } else { Some(s.to_string()) }
}

impl KuzuStore {
    pub fn open(path: &Path, machine_id: String) -> Result<Self> {
        let db = Database::new(path, SystemConfig::default()).context("opening KùzuDB database")?;
        let store = Self {
            db,
            machine_id,
            relations_cache: RwLock::new(HashMap::new()),
        };
        store.init_schema()?;
        Ok(store)
    }

    pub fn in_memory(machine_id: String) -> Result<Self> {
        let db =
            Database::in_memory(SystemConfig::default()).context("creating in-memory KùzuDB")?;
        let store = Self {
            db,
            machine_id,
            relations_cache: RwLock::new(HashMap::new()),
        };
        store.init_schema()?;
        Ok(store)
    }

    fn evict_relations_for(&self, id: Uuid) {
        let mut cache = self.relations_cache.write().unwrap();
        cache.retain(|(key_id, _), _| *key_id != id);
    }

    // A full clear is acceptable on bulk maintenance paths (consolidation purge,
    // delete-by-source, entity/conversation detach) because they are bursty and rare,
    // not per-recall, and enumerating every memory whose outgoing edge count changed
    // (e.g. memories that MENTIONS a deleted entity) is not cheap. Clearing is always
    // sound; it only discards warmth, never correctness.
    fn clear_relations_cache(&self) {
        self.relations_cache.write().unwrap().clear();
    }

    pub fn machine_id(&self) -> &str {
        &self.machine_id
    }

    fn conn(&self) -> Result<Connection<'_>> {
        Connection::new(&self.db).context("creating connection")
    }

    pub fn diagnostic(&self) -> Result<String> {
        let conn = self.conn()?;

        let mut result = conn.query("MATCH (m:Memory) RETURN count(m);")?;
        let total: i64 = result
            .next()
            .map(|r| match &r[0] {
                Value::Int64(v) => *v,
                _ => -1,
            })
            .unwrap_or(-1);

        let mut result = conn.query(
            "MATCH (m:Memory) WHERE size(m.embedding) > 0 AND m.embedding[1] <> 0.0 RETURN count(m);",
        )?;
        let with_emb: i64 = result
            .next()
            .map(|r| match &r[0] {
                Value::Int64(v) => *v,
                _ => -1,
            })
            .unwrap_or(-1);

        let zeros: Vec<String> = (0..384).map(|_| "0.0".to_string()).collect();
        let zeros_str = format!("[{}]", zeros.join(","));
        let idx_query = format!(
            "CALL QUERY_VECTOR_INDEX('Memory', 'memory_emb_idx', {}, 1) YIELD node, distance RETURN distance;",
            zeros_str
        );
        let idx_status = match conn.query(&idx_query) {
            Ok(mut r) => match r.next() {
                Some(row) => format!("ok (distance: {:?})", &row[0]),
                None => "ok (0 results)".to_string(),
            },
            Err(e) => format!("error: {e}"),
        };

        Ok(format!(
            "total memories: {total}\nwith embeddings: {with_emb}\nvector index: {idx_status}"
        ))
    }

    fn init_schema(&self) -> Result<()> {
        let conn = self.conn()?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS Memory(
                id STRING PRIMARY KEY,
                content STRING,
                embedding FLOAT[384],
                memory_type STRING,
                confidence FLOAT,
                created_at STRING,
                last_accessed STRING,
                access_count INT64,
                source STRING,
                source_id STRING,
                project_path STRING
            );",
        )
        .context("creating Memory table")?;

        conn.query("ALTER TABLE Memory ADD project_path STRING DEFAULT '';").ok();

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS Machine(
                id STRING PRIMARY KEY,
                name STRING
            );",
        )
        .context("creating Machine table")?;

        conn.query("ALTER TABLE Memory ADD machine_id STRING DEFAULT '';").ok();

        conn.query("ALTER TABLE Memory ADD updated_at STRING DEFAULT '';").ok();
        conn.query("MATCH (m:Memory) WHERE m.updated_at = '' SET m.updated_at = m.created_at;").ok();

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS Entity(
                id STRING PRIMARY KEY,
                name STRING,
                entity_type STRING,
                embedding FLOAT[384],
                aliases STRING[]
            );",
        )
        .context("creating Entity table")?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS Conversation(
                id STRING PRIMARY KEY,
                source STRING,
                machine_id STRING,
                started_at STRING,
                project_path STRING
            );",
        )
        .context("creating Conversation table")?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS IngestLog(
                file_path STRING PRIMARY KEY,
                file_hash STRING,
                ingested_at STRING,
                memory_count INT64,
                source STRING
            );",
        )
        .context("creating IngestLog table")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS RELATES_TO(
                FROM Memory TO Memory,
                strength FLOAT,
                context STRING
            );",
        )
        .context("creating RELATES_TO rel")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS MENTIONS(
                FROM Memory TO Entity,
                position INT64
            );",
        )
        .context("creating MENTIONS rel")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS DERIVED_FROM(
                FROM Memory TO Conversation,
                transformation STRING
            );",
        )
        .context("creating DERIVED_FROM rel")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS DISTILLED_FROM(
                FROM Memory TO Memory,
                model STRING
            );",
        )
        .context("creating DISTILLED_FROM rel")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS CONTRADICTS(
                FROM Memory TO Memory,
                resolution STRING
            );",
        )
        .context("creating CONTRADICTS rel")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS REINFORCES(
                FROM Memory TO Memory
            );",
        )
        .context("creating REINFORCES rel")?;

        conn.query(
            "CREATE REL TABLE IF NOT EXISTS SUPERSEDES(
                FROM Memory TO Memory,
                reason STRING
            );",
        )
        .context("creating SUPERSEDES rel")?;

        self.migrate_sync_log(&conn).context("migrating SyncLog table")?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS SyncState(
                peer_id STRING PRIMARY KEY,
                last_seq INT64,
                last_sync_at STRING
            );",
        )
        .context("creating SyncState table")?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS ConsolidationLog(
                memory_id STRING PRIMARY KEY,
                distilled_id STRING,
                consolidated_at STRING,
                model STRING
            );",
        )
        .context("creating ConsolidationLog table")?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS WikiExportLog(
                id STRING PRIMARY KEY,
                last_sync_seq INT64,
                exported_at STRING,
                vault_path STRING,
                pages_created INT64,
                pages_updated INT64,
                memories_processed INT64
            );",
        )
        .context("creating WikiExportLog table")?;

        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS Tombstone(
                node_id STRING PRIMARY KEY,
                node_type STRING,
                deleted_at STRING,
                machine_id STRING);",
        )
        .context("creating Tombstone table")?;

        conn.query(
            "CALL CREATE_VECTOR_INDEX('Memory', 'memory_emb_idx', 'embedding', metric := 'cosine');",
        )
        .ok();

        Ok(())
    }

    fn migrate_sync_log(&self, conn: &Connection<'_>) -> Result<()> {
        // Probe by column: a missing column or a missing table makes the query
        // fail, so on a fresh DB both probes fail and control falls through to
        // the CREATE below. We drop only when the pre-redesign `seq` schema is
        // the one actually present.
        let new_schema_present = conn
            .query("MATCH (s:SyncLog) RETURN s.id LIMIT 1;")
            .is_ok();
        if !new_schema_present {
            let old_schema_present = conn
                .query("MATCH (s:SyncLog) RETURN s.seq LIMIT 1;")
                .is_ok();
            if old_schema_present {
                conn.query("DROP TABLE SyncLog;")?;
                conn.query("MATCH (s:SyncState) SET s.last_seq = 0;").ok();
            }
        }
        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS SyncLog(
                id STRING PRIMARY KEY,
                local_seq INT64,
                origin_machine_id STRING,
                origin_seq INT64,
                op STRING,
                node_type STRING,
                node_id STRING,
                timestamp STRING,
                data STRING
            );",
        )?;
        Ok(())
    }

    fn with_transaction<T>(&self, f: impl FnOnce(&Connection<'_>) -> Result<T>) -> Result<T> {
        let conn = self.conn()?;
        conn.query("BEGIN TRANSACTION;")?;
        match f(&conn) {
            Ok(v) => {
                conn.query("COMMIT;")?;
                Ok(v)
            }
            Err(e) => {
                let _ = conn.query("ROLLBACK;");
                Err(e)
            }
        }
    }

    fn append_sync_log(
        &self,
        conn: &Connection<'_>,
        op: SyncOp,
        node_type: SyncNodeType,
        node_id: &str,
        data: Option<&str>,
        origin_machine_id: &str,
        origin_seq: Option<i64>,
    ) -> Result<()> {
        let mut r = conn.query("MATCH (s:SyncLog) RETURN max(s.local_seq);")?;
        let local_seq: i64 = match r.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => n + 1,
                _ => 1,
            },
            None => 1,
        };
        let origin_seq = origin_seq.unwrap_or(local_seq);
        let id = format!("{}:{}", origin_machine_id, origin_seq);
        let id_esc = escape_cypher(&id);
        let mut dup = conn.query(&format!(
            "MATCH (s:SyncLog {{id: '{id_esc}'}}) RETURN s.id LIMIT 1;"
        ))?;
        if dup.next().is_some() {
            return Ok(());
        }
        let timestamp = chrono::Utc::now().to_rfc3339();
        let op_str = match op {
            SyncOp::Create => "create",
            SyncOp::Update => "update",
            SyncOp::Delete => "delete",
        };
        let nt_str = match node_type {
            SyncNodeType::Memory => "memory",
            SyncNodeType::Entity => "entity",
            SyncNodeType::Conversation => "conversation",
            SyncNodeType::Relation => "relation",
        };
        let origin_machine_esc = escape_cypher(origin_machine_id);
        let node_id_esc = escape_cypher(node_id);
        let data_esc = data.map(escape_cypher).unwrap_or_default();
        conn.query(&format!(
            "CREATE (:SyncLog {{id:'{id_esc}', local_seq:{local_seq}, \
             origin_machine_id:'{origin_machine_esc}', origin_seq:{origin_seq}, \
             op:'{op_str}', node_type:'{nt_str}', node_id:'{node_id_esc}', \
             timestamp:'{timestamp}', data:'{data_esc}'}});"
        ))?;
        Ok(())
    }

    pub fn tombstone_exists(&self, id: Uuid) -> Result<bool> {
        let conn = self.conn()?;
        let id_esc = escape_cypher(&id.to_string());
        let mut result = conn.query(&format!(
            "MATCH (t:Tombstone {{node_id: '{id_esc}'}}) RETURN t.node_id LIMIT 1;"
        ))?;
        Ok(result.next().is_some())
    }

    fn upsert_tombstone(
        &self,
        conn: &Connection<'_>,
        node_id: &str,
        node_type: &str,
        machine_id: &str,
    ) -> Result<()> {
        let node_id_esc = escape_cypher(node_id);
        let node_type_esc = escape_cypher(node_type);
        let machine_id_esc = escape_cypher(machine_id);
        let deleted_at = chrono::Utc::now().to_rfc3339();
        conn.query(&format!(
            "MERGE (t:Tombstone {{node_id: '{node_id_esc}'}}) \
             SET t.node_type = '{node_type_esc}', \
                 t.deleted_at = '{deleted_at}', \
                 t.machine_id = '{machine_id_esc}';"
        ))?;
        Ok(())
    }
}

impl Store for KuzuStore {
    fn store_memory(&self, memory: &Memory) -> Result<()> {
        let data = serde_json::to_string(memory).ok();
        self.with_transaction(|conn| {
            self.create_memory_node(conn, memory)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Memory,
                &memory.id.to_string(),
                data.as_deref(),
                &self.machine_id,
                None,
            )
        })
    }

    fn get_memory(&self, id: Uuid) -> Result<Option<Memory>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (m:Memory {{id: '{}'}}) RETURN {};",
            id, memory_return_cols("m")
        );

        let mut result = conn.query(&query)?;
        match result.next() {
            Some(row) => Ok(Some(row_to_memory(&row)?)),
            None => Ok(None),
        }
    }

    fn delete_memory(&self, id: Uuid) -> Result<()> {
        let id_string = id.to_string();
        let result = self.with_transaction(|conn| {
            conn.query(&format!(
                "MATCH (m:Memory {{id: '{id_string}'}}) DETACH DELETE m;"
            ))?;
            self.upsert_tombstone(conn, &id_string, "memory", &self.machine_id)?;
            self.append_sync_log(
                conn,
                SyncOp::Delete,
                SyncNodeType::Memory,
                &id_string,
                None,
                &self.machine_id,
                None,
            )
        });
        // DETACH DELETE drops this memory's outgoing edges; its cached relations are
        // now stale. Edges where this memory was the target also vanish, but those
        // keys belong to other source ids; a delete is rare enough that a full clear
        // is the safe choice to avoid serving a stale neighbor's relation list.
        self.clear_relations_cache();
        result
    }

    fn store_entity(&self, entity: &Entity) -> Result<()> {
        let data = serde_json::to_string(entity).ok();
        self.with_transaction(|conn| {
            self.create_entity_node(conn, entity)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Entity,
                &entity.id.to_string(),
                data.as_deref(),
                &self.machine_id,
                None,
            )
        })
    }

    fn get_entity(&self, id: Uuid) -> Result<Option<Entity>> {
        let conn = self.conn()?;
        let mut result = conn.query(&format!(
            "MATCH (e:Entity {{id: '{}'}}) RETURN e.id, e.name, e.entity_type;",
            id
        ))?;

        match result.next() {
            Some(row) => Ok(Some(row_to_entity(&row)?)),
            None => Ok(None),
        }
    }

    fn find_entity_by_name(&self, name: &str) -> Result<Option<Entity>> {
        let conn = self.conn()?;
        let name_escaped = escape_cypher(name);
        let query = format!(
            "MATCH (e:Entity) WHERE e.name = '{}' RETURN e.id, e.name, e.entity_type;",
            name_escaped
        );
        let mut result = conn.query(&query)?;

        match result.next() {
            Some(row) => Ok(Some(row_to_entity(&row)?)),
            None => Ok(None),
        }
    }

    fn store_conversation(&self, conversation: &Conversation) -> Result<()> {
        let data = serde_json::to_string(conversation).ok();
        self.with_transaction(|conn| {
            self.create_conversation_node(conn, conversation)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Conversation,
                &conversation.id.to_string(),
                data.as_deref(),
                &self.machine_id,
                None,
            )
        })
    }

    fn store_relation(&self, relation: &Relation) -> Result<()> {
        let rel_type = format!("{:?}", relation.relation_type).to_lowercase();
        let node_id = format!("{}:{}:{}", relation.from_id, relation.to_id, rel_type);
        let data = serde_json::to_string(relation).ok();
        let result = self.with_transaction(|conn| {
            self.create_relation_edge(conn, relation)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Relation,
                &node_id,
                data.as_deref(),
                &self.machine_id,
                None,
            )
        });
        // get_relations keys on the source (from_id) only, so evicting that id is the
        // exact and minimal invalidation for a new outgoing edge.
        self.evict_relations_for(relation.from_id);
        result
    }

    fn get_relations(
        &self,
        node_id: Uuid,
        relation_type: Option<RelationType>,
    ) -> Result<Vec<Relation>> {
        let cache_key = (node_id, relation_type);
        if let Some(hit) = self.relations_cache.read().unwrap().get(&cache_key) {
            return Ok(hit.clone());
        }

        let conn = self.conn()?;
        let id = node_id.to_string();

        let query = match relation_type {
            Some(RelationType::RelatesTo) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[r:RELATES_TO]->(b:Memory) RETURN b.id, r.strength, r.context;",
                id
            ),
            Some(RelationType::Contradicts) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[r:CONTRADICTS]->(b:Memory) RETURN b.id, r.resolution;",
                id
            ),
            Some(RelationType::Reinforces) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[:REINFORCES]->(b:Memory) RETURN b.id;",
                id
            ),
            Some(RelationType::Supersedes) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[r:SUPERSEDES]->(b:Memory) RETURN b.id, r.reason;",
                id
            ),
            Some(RelationType::Mentions) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[:MENTIONS]->(b:Entity) RETURN b.id;",
                id
            ),
            Some(RelationType::DerivedFrom) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[:DERIVED_FROM]->(b:Conversation) RETURN b.id;",
                id
            ),
            Some(RelationType::DistilledFrom) => format!(
                "MATCH (a:Memory {{id: '{}'}})-[:DISTILLED_FROM]->(b:Memory) RETURN b.id;",
                id
            ),
            None => {
                let mut relations = Vec::new();
                let mem_to_mem = [
                    ("RELATES_TO", RelationType::RelatesTo),
                    ("REINFORCES", RelationType::Reinforces),
                    ("CONTRADICTS", RelationType::Contradicts),
                    ("SUPERSEDES", RelationType::Supersedes),
                    ("DISTILLED_FROM", RelationType::DistilledFrom),
                ];
                for (label, rt) in &mem_to_mem {
                    let q = format!(
                        "MATCH (a:Memory {{id: '{}'}})-[:{}]->(b:Memory) RETURN b.id;",
                        id, label
                    );
                    if let Ok(mut result) = conn.query(&q) {
                        for row in &mut result {
                            let to_id_str = value_to_string(&row[0]);
                            let to_id = Uuid::parse_str(&to_id_str).unwrap_or_default();
                            relations.push(Relation {
                                from_id: node_id,
                                to_id,
                                relation_type: *rt,
                                strength: 1.0,
                                context: None,
                            });
                        }
                    }
                }
                for (label, target, rt) in [
                    ("MENTIONS", "Entity", RelationType::Mentions),
                    ("DERIVED_FROM", "Conversation", RelationType::DerivedFrom),
                ] {
                    let q = format!(
                        "MATCH (a:Memory {{id: '{}'}})-[:{}]->(b:{}) RETURN b.id;",
                        id, label, target
                    );
                    if let Ok(mut result) = conn.query(&q) {
                        for row in &mut result {
                            let to_id_str = value_to_string(&row[0]);
                            let to_id = Uuid::parse_str(&to_id_str).unwrap_or_default();
                            relations.push(Relation {
                                from_id: node_id,
                                to_id,
                                relation_type: rt,
                                strength: 1.0,
                                context: None,
                            });
                        }
                    }
                }
                self.relations_cache
                    .write()
                    .unwrap()
                    .insert(cache_key, relations.clone());
                return Ok(relations);
            }
        };

        let mut result = conn.query(&query)?;
        let mut relations = Vec::new();

        for row in &mut result {
            let to_id_str = value_to_string(&row[0]);
            let to_id = Uuid::parse_str(&to_id_str).unwrap_or_default();

            relations.push(Relation {
                from_id: node_id,
                to_id,
                relation_type: relation_type.unwrap_or(RelationType::RelatesTo),
                strength: 1.0,
                context: None,
            });
        }

        self.relations_cache
            .write()
            .unwrap()
            .insert(cache_key, relations.clone());
        Ok(relations)
    }

    fn vector_search(&self, embedding: &[f32], limit: usize) -> Result<Vec<(Memory, f32)>> {
        let conn = self.conn()?;
        let embedding_str = format_embedding(embedding);

        let query = format!(
            "CALL QUERY_VECTOR_INDEX('Memory', 'memory_emb_idx', {}, {}) YIELD node, distance
             RETURN {}, distance;",
            embedding_str, limit, memory_return_cols("node")
        );

        let mut result = conn.query(&query)?;
        let mut results = Vec::new();

        for row in &mut result {
            let memory = row_to_memory(&row[..12])?;
            let distance = value_to_f32(&row[12]);
            let similarity = 1.0 - distance;
            results.push((memory, similarity));
        }

        Ok(results)
    }

    fn traverse(&self, start_id: Uuid, depth: u32) -> Result<Vec<(Memory, Vec<Relation>)>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (start:Memory {{id: '{}'}})-[r:RELATES_TO|REINFORCES*1..{}]->(m:Memory)
             RETURN DISTINCT {};",
            start_id, depth, memory_return_cols("m")
        );

        let mut result = conn.query(&query)?;
        let mut results = Vec::new();

        for row in &mut result {
            let memory = row_to_memory(&row)?;
            results.push((memory, Vec::new()));
        }

        Ok(results)
    }

    fn memories_by_source(&self, source: &str) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let source_escaped = escape_cypher(source);
        let query = format!(
            "MATCH (m:Memory) WHERE m.source = '{}' RETURN {};",
            source_escaped, memory_return_cols("m")
        );
        let mut result = conn.query(&query)?;

        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    fn memories_by_type(&self, memory_type: MemoryType) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let type_str = format!("{:?}", memory_type).to_lowercase();
        let query = format!(
            "MATCH (m:Memory) WHERE m.memory_type = '{}' RETURN {};",
            type_str, memory_return_cols("m")
        );
        let mut result = conn.query(&query)?;

        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    fn memories_needing_decay(&self, threshold_days: u32) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let cutoff = chrono::Utc::now() - chrono::Duration::days(threshold_days as i64);
        let cutoff_str = cutoff.to_rfc3339();

        let query = format!(
            "MATCH (m:Memory) WHERE m.last_accessed < '{}' AND m.confidence > 0.05 RETURN {};",
            cutoff_str, memory_return_cols("m")
        );

        let mut result = conn.query(&query)?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    fn update_memory(&self, memory: &Memory) -> Result<()> {
        let id = memory.id.to_string();
        let last_accessed = memory.last_accessed.to_rfc3339();
        let updated_at = memory.updated_at.to_rfc3339();
        let project_path_escaped = escape_cypher(memory.project_path.as_deref().unwrap_or(""));
        let machine_id_escaped = escape_cypher(&memory.machine_id);
        let data = serde_json::to_string(memory).ok();
        self.with_transaction(|conn| {
            let query = format!(
                "MATCH (m:Memory {{id: '{}'}}) SET m.confidence = {}, m.last_accessed = '{}', m.access_count = {}, m.project_path = '{}', m.updated_at = '{}', m.machine_id = '{}';",
                id, memory.confidence, last_accessed, memory.access_count, project_path_escaped, updated_at, machine_id_escaped
            );
            conn.query(&query)?;
            self.append_sync_log(
                conn,
                SyncOp::Update,
                SyncNodeType::Memory,
                &id,
                data.as_deref(),
                &self.machine_id,
                None,
            )
        })
    }

    fn record_access(&self, memory: &Memory) -> Result<()> {
        let id_esc = escape_cypher(&memory.id.to_string());
        let last_accessed = memory.last_accessed.to_rfc3339();
        let last_accessed_esc = escape_cypher(&last_accessed);
        let conn = self.conn()?;
        conn.query(&format!(
            "MATCH (m:Memory {{id: '{id_esc}'}}) SET \
             m.last_accessed = '{last_accessed_esc}', \
             m.access_count = {}, \
             m.confidence = {};",
            memory.access_count, memory.confidence
        ))?;
        Ok(())
    }

    fn text_search(&self, query: &str, limit: usize) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let query_escaped = escape_cypher(&query.to_lowercase());
        let cypher = format!(
            "MATCH (m:Memory) WHERE lower(m.content) CONTAINS '{}' RETURN {} LIMIT {};",
            query_escaped, memory_return_cols("m"), limit
        );

        let mut result = conn.query(&cypher)?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    fn memory_count(&self) -> Result<usize> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (m:Memory) RETURN count(m);")?;
        match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => Ok(*n as usize),
                _ => Ok(0),
            },
            None => Ok(0),
        }
    }

    fn all_memory_ids(&self) -> Result<Vec<Uuid>> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (m:Memory) RETURN m.id;")?;
        let mut ids = Vec::new();
        for row in &mut result {
            let id_str = value_to_string(&row[0]);
            ids.push(Uuid::parse_str(&id_str).unwrap_or_default());
        }
        Ok(ids)
    }

    fn all_relations(&self) -> Result<Vec<Relation>> {
        let conn = self.conn()?;
        let mut relations = Vec::new();

        let mem_to_mem = [
            ("RELATES_TO", RelationType::RelatesTo),
            ("REINFORCES", RelationType::Reinforces),
            ("CONTRADICTS", RelationType::Contradicts),
            ("SUPERSEDES", RelationType::Supersedes),
            ("DISTILLED_FROM", RelationType::DistilledFrom),
        ];
        for (label, rt) in &mem_to_mem {
            let q = format!(
                "MATCH (a:Memory)-[:{}]->(b:Memory) RETURN a.id, b.id;",
                label
            );
            let mut result = conn.query(&q)?;
            for row in &mut result {
                let from_id = Uuid::parse_str(&value_to_string(&row[0])).unwrap_or_default();
                let to_id = Uuid::parse_str(&value_to_string(&row[1])).unwrap_or_default();
                relations.push(Relation {
                    from_id,
                    to_id,
                    relation_type: *rt,
                    strength: 1.0,
                    context: None,
                });
            }
        }

        for (label, target, rt) in [
            ("MENTIONS", "Entity", RelationType::Mentions),
            ("DERIVED_FROM", "Conversation", RelationType::DerivedFrom),
        ] {
            let q = format!(
                "MATCH (a:Memory)-[:{}]->(b:{}) RETURN a.id, b.id;",
                label, target
            );
            let mut result = conn.query(&q)?;
            for row in &mut result {
                let from_id = Uuid::parse_str(&value_to_string(&row[0])).unwrap_or_default();
                let to_id = Uuid::parse_str(&value_to_string(&row[1])).unwrap_or_default();
                relations.push(Relation {
                    from_id,
                    to_id,
                    relation_type: rt,
                    strength: 1.0,
                    context: None,
                });
            }
        }

        Ok(relations)
    }
}

impl KuzuStore {
    pub 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)
    }

    pub fn memory_content_exists(&self, content_prefix: &str) -> Result<bool> {
        let conn = self.conn()?;
        let escaped = escape_cypher(content_prefix);
        let query = format!(
            "MATCH (m:Memory) WHERE starts_with(m.content, '{}') RETURN m.id LIMIT 1;",
            escaped
        );
        let mut result = conn.query(&query)?;
        Ok(result.next().is_some())
    }

    pub fn unconsolidated_memories(&self, limit: usize) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (m:Memory) WHERE NOT EXISTS {{MATCH (c:ConsolidationLog) WHERE c.memory_id = m.id}} AND m.source <> 'consolidation' RETURN {} LIMIT {};",
            memory_return_cols("m"), limit
        );
        let mut result = conn.query(&query)?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    pub fn memories_created_between(
        &self,
        start: &DateTime<Utc>,
        end: &DateTime<Utc>,
    ) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (m:Memory) WHERE m.created_at >= '{}' AND m.created_at < '{}' RETURN {} ORDER BY m.created_at ASC;",
            start.to_rfc3339(),
            end.to_rfc3339(),
            memory_return_cols("m")
        );
        let mut result = conn.query(&query)?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    pub fn mark_consolidated(&self, raw_id: Uuid, distilled_id: Uuid, model: &str) -> Result<()> {
        let conn = self.conn()?;
        let now = Utc::now().to_rfc3339();
        let query = format!(
            "CREATE (:ConsolidationLog {{memory_id: '{}', distilled_id: '{}', consolidated_at: '{}', model: '{}'}});",
            raw_id,
            distilled_id,
            now,
            escape_cypher(model)
        );
        conn.query(&query)?;
        Ok(())
    }

    pub fn consolidation_count(&self) -> Result<usize> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (c:ConsolidationLog) RETURN count(c);")?;
        match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => Ok(*n as usize),
                _ => Ok(0),
            },
            None => Ok(0),
        }
    }

    pub fn delete_consolidated_raw(&self) -> Result<usize> {
        let ids: Vec<Uuid> = {
            let conn = self.conn()?;
            let result = conn.query(
                "MATCH (c:ConsolidationLog) WHERE c.memory_id <> c.distilled_id RETURN c.memory_id;",
            )?;
            let mut acc = Vec::new();
            for row in result {
                if let Value::String(id) = &row[0]
                    && let Ok(uuid) = Uuid::parse_str(id)
                {
                    acc.push(uuid);
                }
            }
            acc
        };
        let count = ids.len();
        let machine_id = self.machine_id.clone();
        for id in &ids {
            let id_str = id.to_string();
            let mid = machine_id.clone();
            self.with_transaction(|conn| {
                conn.query(&format!(
                    "MATCH (m:Memory {{id: '{id_str}'}}) DETACH DELETE m;"
                ))?;
                self.upsert_tombstone(conn, &id_str, "memory", &mid)?;
                self.append_sync_log(
                    conn,
                    SyncOp::Delete,
                    SyncNodeType::Memory,
                    &id_str,
                    None,
                    &mid,
                    None,
                )
            })?;
        }
        if count > 0 {
            self.clear_relations_cache();
        }
        Ok(count)
    }

    pub fn rebuild_vector_index(&self) -> Result<()> {
        let conn = self.conn()?;
        conn.query("CALL DROP_VECTOR_INDEX('Memory', 'memory_emb_idx');")
            .ok();
        conn.query(
            "CALL CREATE_VECTOR_INDEX('Memory', 'memory_emb_idx', 'embedding', metric := 'cosine');",
        )?;
        Ok(())
    }

    pub fn clear_ingest_log(&self) -> Result<usize> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (l:IngestLog) RETURN count(l);")?;
        let count = match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => *n as usize,
                _ => 0,
            },
            None => 0,
        };
        conn.query("MATCH (l:IngestLog) DETACH DELETE l;")?;
        Ok(count)
    }

    pub fn delete_memories_by_source(&self, source: &str) -> Result<usize> {
        let conn = self.conn()?;
        let escaped = escape_cypher(source);
        let mut result = conn.query(&format!(
            "MATCH (m:Memory) WHERE m.source = '{}' RETURN count(m);",
            escaped
        ))?;
        let count = match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => *n as usize,
                _ => 0,
            },
            None => 0,
        };
        conn.query(&format!(
            "MATCH (m:Memory) WHERE m.source = '{}' DETACH DELETE m;",
            escaped
        ))?;
        if count > 0 {
            self.clear_relations_cache();
        }
        Ok(count)
    }

    pub fn is_file_ingested(&self, file_path: &str) -> Result<bool> {
        let conn = self.conn()?;
        let escaped = escape_cypher(file_path);
        let mut result = conn.query(&format!(
            "MATCH (l:IngestLog {{file_path: '{}'}}) RETURN l.file_path;",
            escaped
        ))?;
        Ok(result.next().is_some())
    }

    pub fn is_file_changed(&self, file_path: &str, file_hash: &str) -> Result<bool> {
        let conn = self.conn()?;
        let escaped = escape_cypher(file_path);
        let mut result = conn.query(&format!(
            "MATCH (l:IngestLog {{file_path: '{}'}}) RETURN l.file_hash;",
            escaped
        ))?;
        match result.next() {
            Some(row) => {
                let stored_hash = value_to_string(&row[0]);
                Ok(stored_hash != file_hash)
            }
            None => Ok(true),
        }
    }

    pub fn mark_ingested(
        &self,
        file_path: &str,
        file_hash: &str,
        memory_count: usize,
        source: &str,
    ) -> Result<()> {
        let conn = self.conn()?;
        let path_escaped = escape_cypher(file_path);
        let hash_escaped = escape_cypher(file_hash);
        let source_escaped = escape_cypher(source);
        let now = chrono::Utc::now().to_rfc3339();

        conn.query(&format!(
            "MERGE (l:IngestLog {{file_path: '{}'}})
             SET l.file_hash = '{}', l.ingested_at = '{}', l.memory_count = {}, l.source = '{}';",
            path_escaped, hash_escaped, now, memory_count as i64, source_escaped
        ))?;
        Ok(())
    }

    pub fn ingested_file_count(&self) -> Result<usize> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (l:IngestLog) RETURN count(l);")?;
        match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => Ok(*n as usize),
                _ => Ok(0),
            },
            None => Ok(0),
        }
    }
}

impl KuzuStore {
    fn create_memory_node(&self, conn: &Connection<'_>, memory: &Memory) -> Result<()> {
        let id = memory.id.to_string();
        let memory_type = format!("{:?}", memory.memory_type).to_lowercase();
        let created_at = memory.created_at.to_rfc3339();
        let last_accessed = memory.last_accessed.to_rfc3339();
        let embedding_str = format_embedding(&memory.embedding);
        let content_escaped = escape_cypher(&memory.content);
        let source_escaped = escape_cypher(&memory.source);
        let source_id_escaped = escape_cypher(&memory.source_id);
        let project_path_escaped = escape_cypher(memory.project_path.as_deref().unwrap_or(""));
        let machine_id_escaped = escape_cypher(&memory.machine_id);
        let updated_at = memory.updated_at.to_rfc3339();

        let query = format!(
            "CREATE (:Memory {{
                id: '{id}',
                content: '{content_escaped}',
                embedding: {embedding_str},
                memory_type: '{memory_type}',
                confidence: {confidence},
                created_at: '{created_at}',
                last_accessed: '{last_accessed}',
                access_count: {access_count},
                source: '{source_escaped}',
                source_id: '{source_id_escaped}',
                project_path: '{project_path_escaped}',
                machine_id: '{machine_id_escaped}',
                updated_at: '{updated_at}'
            }});",
            confidence = memory.confidence,
            access_count = memory.access_count,
        );

        conn.query(&query)?;
        Ok(())
    }

    fn create_entity_node(&self, conn: &Connection<'_>, entity: &Entity) -> Result<()> {
        let id = entity.id.to_string();
        let embedding_str = format_embedding(&entity.embedding);
        let aliases_str = format_string_array(&entity.aliases);
        let name_escaped = escape_cypher(&entity.name);
        let etype_escaped = escape_cypher(&entity.entity_type);

        let query = format!(
            "CREATE (:Entity {{
                id: '{id}',
                name: '{name_escaped}',
                entity_type: '{etype_escaped}',
                embedding: {embedding_str},
                aliases: {aliases_str}
            }});"
        );

        conn.query(&query)?;
        Ok(())
    }

    fn create_conversation_node(
        &self,
        conn: &Connection<'_>,
        conversation: &Conversation,
    ) -> Result<()> {
        let id = conversation.id.to_string();
        let started_at = conversation.started_at.to_rfc3339();
        let source_escaped = escape_cypher(&conversation.source);
        let machine_escaped = escape_cypher(&conversation.machine_id);
        let project_escaped = escape_cypher(conversation.project_path.as_deref().unwrap_or(""));

        let query = format!(
            "CREATE (:Conversation {{
                id: '{id}',
                source: '{source_escaped}',
                machine_id: '{machine_escaped}',
                started_at: '{started_at}',
                project_path: '{project_escaped}'
            }});"
        );

        conn.query(&query)?;
        Ok(())
    }

    fn create_relation_edge(&self, conn: &Connection<'_>, relation: &Relation) -> Result<()> {
        let from_id = relation.from_id.to_string();
        let to_id = relation.to_id.to_string();

        let query = match relation.relation_type {
            RelationType::RelatesTo => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Memory {{id: '{}'}}) CREATE (a)-[:RELATES_TO {{strength: {}, context: '{}'}}]->(b);",
                from_id,
                to_id,
                relation.strength,
                relation.context.as_deref().unwrap_or("")
            ),
            RelationType::Mentions => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Entity {{id: '{}'}}) CREATE (a)-[:MENTIONS {{position: 0}}]->(b);",
                from_id, to_id
            ),
            RelationType::DerivedFrom => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Conversation {{id: '{}'}}) CREATE (a)-[:DERIVED_FROM {{transformation: '{}'}}]->(b);",
                from_id,
                to_id,
                relation.context.as_deref().unwrap_or("direct")
            ),
            RelationType::Contradicts => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Memory {{id: '{}'}}) CREATE (a)-[:CONTRADICTS {{resolution: '{}'}}]->(b);",
                from_id,
                to_id,
                relation.context.as_deref().unwrap_or("")
            ),
            RelationType::Reinforces => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Memory {{id: '{}'}}) CREATE (a)-[:REINFORCES]->(b);",
                from_id, to_id
            ),
            RelationType::DistilledFrom => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Memory {{id: '{}'}}) CREATE (a)-[:DISTILLED_FROM {{model: '{}'}}]->(b);",
                from_id,
                to_id,
                relation.context.as_deref().unwrap_or("")
            ),
            RelationType::Supersedes => format!(
                "MATCH (a:Memory {{id: '{}'}}), (b:Memory {{id: '{}'}}) CREATE (a)-[:SUPERSEDES {{reason: '{}'}}]->(b);",
                from_id,
                to_id,
                relation.context.as_deref().unwrap_or("")
            ),
        };

        conn.query(&query)?;
        Ok(())
    }
}

impl KuzuStore {
    pub fn get_conversation(&self, id: Uuid) -> Result<Option<Conversation>> {
        let conn = self.conn()?;
        let mut result = conn.query(&format!(
            "MATCH (c:Conversation {{id: '{}'}}) RETURN c.id, c.source, c.machine_id, c.started_at, c.project_path;",
            id
        ))?;

        match result.next() {
            Some(row) => {
                let id = Uuid::parse_str(&value_to_string(&row[0])).unwrap_or_default();
                let source = value_to_string(&row[1]);
                let machine_id = value_to_string(&row[2]);
                let started_at_str = value_to_string(&row[3]);
                let project_path = {
                    let s = value_to_string(&row[4]);
                    if s.is_empty() { None } else { Some(s) }
                };
                let started_at = chrono::DateTime::parse_from_rfc3339(&started_at_str)
                    .map(|dt| dt.with_timezone(&chrono::Utc))
                    .unwrap_or_else(|_| chrono::Utc::now());

                Ok(Some(Conversation {
                    id,
                    source,
                    machine_id,
                    started_at,
                    project_path,
                }))
            }
            None => Ok(None),
        }
    }

    pub fn get_memory_with_embedding(&self, id: Uuid) -> Result<Option<Memory>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (m:Memory {{id: '{}'}}) RETURN {}, m.embedding;",
            id, memory_return_cols("m")
        );

        let mut result = conn.query(&query)?;
        match result.next() {
            Some(row) => {
                let mut memory = row_to_memory(&row[..12])?;
                memory.embedding = value_to_f32_vec(&row[12]);
                Ok(Some(memory))
            }
            None => Ok(None),
        }
    }

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

    fn tombstone_exists_on(&self, conn: &Connection<'_>, id: Uuid) -> Result<bool> {
        let id_esc = escape_cypher(&id.to_string());
        let mut result = conn.query(&format!(
            "MATCH (t:Tombstone {{node_id: '{id_esc}'}}) RETURN t.node_id LIMIT 1;"
        ))?;
        Ok(result.next().is_some())
    }

    fn normalize_incoming(mem: &mut Memory) {
        if mem.updated_at == DateTime::UNIX_EPOCH {
            mem.updated_at = mem.created_at;
        }
    }

    pub fn apply_create_memory(
        &self,
        mem: &Memory,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let mut mem = mem.clone();
        Self::normalize_incoming(&mut mem);
        let data = serde_json::to_string(&mem).ok();
        let node_id = mem.id.to_string();
        self.with_transaction(|conn| {
            if self.tombstone_exists_on(conn, mem.id)? {
                return Ok(ApplyOutcome::Skipped);
            }
            if self.get_memory(mem.id)?.is_some() {
                return Ok(ApplyOutcome::Skipped);
            }
            self.create_memory_node(conn, &mem)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Memory,
                &node_id,
                data.as_deref(),
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Created)
        })
    }

    // Holds a single write transaction open for the whole closure so a batch of
    // creates commits with one fsync instead of one per record. KuzuDB is single
    // writer and forbids nested transactions, so the closure must not call any
    // method that opens its own transaction; it may only use the `*_on_tx` apply
    // helpers and read-only lookups (which run on separate read connections and
    // see committed state, matching the per-record skip semantics).
    pub fn with_write_transaction<T>(
        &self,
        f: impl FnOnce(&Connection<'_>) -> Result<T>,
    ) -> Result<T> {
        self.with_transaction(f)
    }

    pub fn apply_create_memory_on_tx(
        &self,
        conn: &Connection<'_>,
        mem: &Memory,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let mut mem = mem.clone();
        Self::normalize_incoming(&mut mem);
        let data = serde_json::to_string(&mem).ok();
        let node_id = mem.id.to_string();
        if self.tombstone_exists_on(conn, mem.id)? {
            return Ok(ApplyOutcome::Skipped);
        }
        if self.get_memory(mem.id)?.is_some() {
            return Ok(ApplyOutcome::Skipped);
        }
        self.create_memory_node(conn, &mem)?;
        self.append_sync_log(
            conn,
            SyncOp::Create,
            SyncNodeType::Memory,
            &node_id,
            data.as_deref(),
            origin_machine_id,
            Some(origin_seq),
        )?;
        Ok(ApplyOutcome::Created)
    }

    pub fn apply_create_conversation_on_tx(
        &self,
        conn: &Connection<'_>,
        conv: &Conversation,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let data = serde_json::to_string(conv).ok();
        let node_id = conv.id.to_string();
        if self.get_conversation(conv.id)?.is_some() {
            return Ok(ApplyOutcome::Skipped);
        }
        self.create_conversation_node(conn, conv)?;
        self.append_sync_log(
            conn,
            SyncOp::Create,
            SyncNodeType::Conversation,
            &node_id,
            data.as_deref(),
            origin_machine_id,
            Some(origin_seq),
        )?;
        Ok(ApplyOutcome::Created)
    }

    pub fn apply_create_entity_on_tx(
        &self,
        conn: &Connection<'_>,
        entity: &Entity,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let data = serde_json::to_string(entity).ok();
        let node_id = entity.id.to_string();
        if self.get_entity(entity.id)?.is_some() {
            return Ok(ApplyOutcome::Skipped);
        }
        self.create_entity_node(conn, entity)?;
        self.append_sync_log(
            conn,
            SyncOp::Create,
            SyncNodeType::Entity,
            &node_id,
            data.as_deref(),
            origin_machine_id,
            Some(origin_seq),
        )?;
        Ok(ApplyOutcome::Created)
    }

    pub fn apply_create_relation_on_tx(
        &self,
        conn: &Connection<'_>,
        relation: &Relation,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let rel_type = format!("{:?}", relation.relation_type).to_lowercase();
        let node_id = format!("{}:{}:{}", relation.from_id, relation.to_id, rel_type);
        let data = serde_json::to_string(relation).ok();
        match self.create_relation_edge(conn, relation) {
            Ok(()) => {
                self.append_sync_log(
                    conn,
                    SyncOp::Create,
                    SyncNodeType::Relation,
                    &node_id,
                    data.as_deref(),
                    origin_machine_id,
                    Some(origin_seq),
                )?;
                Ok(ApplyOutcome::Created)
            }
            // create_relation_edge fails when an endpoint node is absent; a relation
            // whose endpoints are not present yet is skipped, matching the per-record path.
            Err(_) => Ok(ApplyOutcome::Skipped),
        }
    }

    pub fn note_relation_created(&self, from_id: Uuid) {
        self.evict_relations_for(from_id);
    }

    pub fn apply_update_memory(
        &self,
        incoming: &Memory,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<(ApplyOutcome, Option<Memory>)> {
        let mut incoming = incoming.clone();
        Self::normalize_incoming(&mut incoming);
        let data = serde_json::to_string(&incoming).ok();
        let node_id = incoming.id.to_string();
        self.with_transaction(|conn| {
            match self.get_memory(incoming.id)? {
                None => {
                    if self.tombstone_exists_on(conn, incoming.id)? {
                        return Ok((ApplyOutcome::Skipped, None));
                    }
                    self.create_memory_node(conn, &incoming)?;
                    self.append_sync_log(
                        conn,
                        SyncOp::Create,
                        SyncNodeType::Memory,
                        &node_id,
                        data.as_deref(),
                        origin_machine_id,
                        Some(origin_seq),
                    )?;
                    Ok((ApplyOutcome::Created, Some(incoming)))
                }
                Some(existing) => {
                    let incoming_wins = if incoming.updated_at != existing.updated_at {
                        incoming.updated_at > existing.updated_at
                    } else if incoming.access_count != existing.access_count {
                        incoming.access_count > existing.access_count
                    } else {
                        incoming.machine_id > existing.machine_id
                    };

                    if !incoming_wins {
                        return Ok((ApplyOutcome::Skipped, None));
                    }

                    let id = incoming.id.to_string();
                    let content_escaped = escape_cypher(&incoming.content);
                    let memory_type = format!("{:?}", incoming.memory_type).to_lowercase();
                    let created_at = incoming.created_at.to_rfc3339();
                    let last_accessed = incoming.last_accessed.to_rfc3339();
                    let updated_at = incoming.updated_at.to_rfc3339();
                    let source_escaped = escape_cypher(&incoming.source);
                    let source_id_escaped = escape_cypher(&incoming.source_id);
                    let project_path_escaped =
                        escape_cypher(incoming.project_path.as_deref().unwrap_or(""));
                    let machine_id_escaped = escape_cypher(&incoming.machine_id);
                    // embedding is excluded because KuzuDB forbids SET on HNSW-indexed columns;
                    // the embedding is recomputed at ingest time so skipping it here is safe
                    conn.query(&format!(
                        "MATCH (m:Memory {{id: '{id}'}}) SET \
                         m.content = '{content_escaped}', \
                         m.memory_type = '{memory_type}', \
                         m.confidence = {confidence}, \
                         m.created_at = '{created_at}', \
                         m.last_accessed = '{last_accessed}', \
                         m.access_count = {access_count}, \
                         m.source = '{source_escaped}', \
                         m.source_id = '{source_id_escaped}', \
                         m.project_path = '{project_path_escaped}', \
                         m.machine_id = '{machine_id_escaped}', \
                         m.updated_at = '{updated_at}';",
                        confidence = incoming.confidence,
                        access_count = incoming.access_count,
                    ))?;
                    self.append_sync_log(
                        conn,
                        SyncOp::Update,
                        SyncNodeType::Memory,
                        &node_id,
                        data.as_deref(),
                        origin_machine_id,
                        Some(origin_seq),
                    )?;
                    Ok((ApplyOutcome::Updated, Some(incoming)))
                }
            }
        })
    }

    pub fn apply_delete_memory(
        &self,
        node_id: &str,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let result = self.with_transaction(|conn| {
            conn.query(&format!(
                "MATCH (m:Memory {{id: '{node_id}'}}) DETACH DELETE m;"
            ))?;
            self.upsert_tombstone(conn, node_id, "memory", origin_machine_id)?;
            self.append_sync_log(
                conn,
                SyncOp::Delete,
                SyncNodeType::Memory,
                node_id,
                None,
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Deleted)
        });
        // DETACH DELETE removes both this memory's outgoing edges and edges where it
        // was the target (changing neighbors' relation lists), so clear the whole cache.
        self.clear_relations_cache();
        result
    }

    pub fn apply_create_conversation(
        &self,
        conv: &Conversation,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let data = serde_json::to_string(conv).ok();
        let node_id = conv.id.to_string();
        self.with_transaction(|conn| {
            if self.get_conversation(conv.id)?.is_some() {
                return Ok(ApplyOutcome::Skipped);
            }
            self.create_conversation_node(conn, conv)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Conversation,
                &node_id,
                data.as_deref(),
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Created)
        })
    }

    pub fn apply_upsert_conversation(
        &self,
        conv: &Conversation,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let data = serde_json::to_string(conv).ok();
        let node_id = conv.id.to_string();
        let source_escaped = escape_cypher(&conv.source);
        let machine_escaped = escape_cypher(&conv.machine_id);
        let project_escaped = escape_cypher(conv.project_path.as_deref().unwrap_or(""));
        let started_at = conv.started_at.to_rfc3339();
        self.with_transaction(|conn| {
            conn.query(&format!(
                "MERGE (c:Conversation {{id: '{node_id}'}}) SET \
                 c.source = '{source_escaped}', \
                 c.machine_id = '{machine_escaped}', \
                 c.started_at = '{started_at}', \
                 c.project_path = '{project_escaped}';"
            ))?;
            self.append_sync_log(
                conn,
                SyncOp::Update,
                SyncNodeType::Conversation,
                &node_id,
                data.as_deref(),
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Updated)
        })
    }

    pub fn apply_delete_conversation(
        &self,
        node_id: &str,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let result = self.with_transaction(|conn| {
            conn.query(&format!(
                "MATCH (c:Conversation {{id: '{node_id}'}}) DETACH DELETE c;"
            ))?;
            self.append_sync_log(
                conn,
                SyncOp::Delete,
                SyncNodeType::Conversation,
                node_id,
                None,
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Deleted)
        });
        // DETACH DELETE drops DERIVED_FROM edges from memories pointing at this
        // conversation, changing those memories' relation lists. The source ids are not
        // enumerated here, so clear the whole cache.
        self.clear_relations_cache();
        result
    }

    pub fn apply_create_entity(
        &self,
        entity: &Entity,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let data = serde_json::to_string(entity).ok();
        let node_id = entity.id.to_string();
        self.with_transaction(|conn| {
            if self.get_entity(entity.id)?.is_some() {
                return Ok(ApplyOutcome::Skipped);
            }
            self.create_entity_node(conn, entity)?;
            self.append_sync_log(
                conn,
                SyncOp::Create,
                SyncNodeType::Entity,
                &node_id,
                data.as_deref(),
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Created)
        })
    }

    pub fn apply_upsert_entity(
        &self,
        entity: &Entity,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let data = serde_json::to_string(entity).ok();
        let node_id = entity.id.to_string();
        let name_escaped = escape_cypher(&entity.name);
        let etype_escaped = escape_cypher(&entity.entity_type);
        let embedding_str = format_embedding(&entity.embedding);
        let aliases_str = format_string_array(&entity.aliases);
        self.with_transaction(|conn| {
            conn.query(&format!(
                "MERGE (e:Entity {{id: '{node_id}'}}) SET \
                 e.name = '{name_escaped}', \
                 e.entity_type = '{etype_escaped}', \
                 e.embedding = {embedding_str}, \
                 e.aliases = {aliases_str};"
            ))?;
            self.append_sync_log(
                conn,
                SyncOp::Update,
                SyncNodeType::Entity,
                &node_id,
                data.as_deref(),
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Updated)
        })
    }

    pub fn apply_delete_entity(
        &self,
        node_id: &str,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let result = self.with_transaction(|conn| {
            conn.query(&format!(
                "MATCH (e:Entity {{id: '{node_id}'}}) DETACH DELETE e;"
            ))?;
            self.append_sync_log(
                conn,
                SyncOp::Delete,
                SyncNodeType::Entity,
                node_id,
                None,
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Deleted)
        });
        // DETACH DELETE drops MENTIONS edges from memories pointing at this entity,
        // changing those memories' relation lists; the source ids are not enumerated
        // here, so clear the whole cache.
        self.clear_relations_cache();
        result
    }

    pub fn apply_create_relation(
        &self,
        relation: &Relation,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let rel_type = format!("{:?}", relation.relation_type).to_lowercase();
        let node_id = format!("{}:{}:{}", relation.from_id, relation.to_id, rel_type);
        let data = serde_json::to_string(relation).ok();
        let result = self.with_transaction(|conn| {
            match self.create_relation_edge(conn, relation) {
                Ok(()) => {
                    self.append_sync_log(
                        conn,
                        SyncOp::Create,
                        SyncNodeType::Relation,
                        &node_id,
                        data.as_deref(),
                        origin_machine_id,
                        Some(origin_seq),
                    )?;
                    Ok(ApplyOutcome::Created)
                }
                Err(_) => Ok(ApplyOutcome::Skipped),
            }
        });
        self.evict_relations_for(relation.from_id);
        result
    }

    pub fn apply_delete_relation(
        &self,
        node_id: &str,
        relation: Option<&Relation>,
        origin_machine_id: &str,
        origin_seq: i64,
    ) -> Result<ApplyOutcome> {
        let Some(rel) = relation else {
            // Nothing to delete or relay because there is no deserializable relation data,
            // so skip rather than inflate the delete counter with a hollow log entry.
            return Ok(ApplyOutcome::Skipped);
        };
        let evict_id = rel.from_id;
        let result = self.with_transaction(|conn| {
            let from_id = rel.from_id.to_string();
            let to_id = rel.to_id.to_string();
            let rel_label = match rel.relation_type {
                crate::schema::RelationType::RelatesTo => "RELATES_TO",
                crate::schema::RelationType::Mentions => "MENTIONS",
                crate::schema::RelationType::DerivedFrom => "DERIVED_FROM",
                crate::schema::RelationType::Contradicts => "CONTRADICTS",
                crate::schema::RelationType::Reinforces => "REINFORCES",
                crate::schema::RelationType::Supersedes => "SUPERSEDES",
                crate::schema::RelationType::DistilledFrom => "DISTILLED_FROM",
            };
            conn.query(&format!(
                "MATCH (a {{id: '{from_id}'}})-[r:{rel_label}]->(b {{id: '{to_id}'}}) DELETE r;"
            ))
            .ok();
            self.append_sync_log(
                conn,
                SyncOp::Delete,
                SyncNodeType::Relation,
                node_id,
                None,
                origin_machine_id,
                Some(origin_seq),
            )?;
            Ok(ApplyOutcome::Deleted)
        });
        self.evict_relations_for(evict_id);
        result
    }

    pub fn sync_log_page(&self, after_seq: u64, limit: Option<usize>) -> Result<Vec<SyncEntry>> {
        let conn = self.conn()?;
        let limit_clause = match limit {
            Some(n) => format!(" LIMIT {}", n),
            None => String::new(),
        };
        let query = format!(
            "MATCH (s:SyncLog) WHERE s.local_seq > {} \
             RETURN s.id, s.local_seq, s.origin_machine_id, s.origin_seq, s.op, s.node_type, s.node_id, s.timestamp, s.data \
             ORDER BY s.local_seq{};",
            after_seq, limit_clause
        );

        let mut result = conn.query(&query)?;
        let mut entries = Vec::new();

        for row in &mut result {
            let id = value_to_string(&row[0]);
            let local_seq = match &row[1] {
                Value::Int64(n) => *n,
                _ => 0,
            };
            let origin_machine_id = value_to_string(&row[2]);
            let origin_seq = match &row[3] {
                Value::Int64(n) => *n,
                _ => 0,
            };
            let op_str = value_to_string(&row[4]);
            let node_type_str = value_to_string(&row[5]);
            let node_id = value_to_string(&row[6]);
            let timestamp_str = value_to_string(&row[7]);
            let data_str = value_to_string(&row[8]);

            let op = match op_str.as_str() {
                "create" => SyncOp::Create,
                "update" => SyncOp::Update,
                "delete" => SyncOp::Delete,
                _ => continue,
            };
            let node_type = match node_type_str.as_str() {
                "memory" => SyncNodeType::Memory,
                "entity" => SyncNodeType::Entity,
                "conversation" => SyncNodeType::Conversation,
                "relation" => SyncNodeType::Relation,
                _ => continue,
            };
            let timestamp = chrono::DateTime::parse_from_rfc3339(&timestamp_str)
                .map(|dt| dt.with_timezone(&chrono::Utc))
                .unwrap_or_else(|_| chrono::Utc::now());

            let data = if data_str.is_empty() {
                None
            } else {
                Some(data_str)
            };

            entries.push(SyncEntry {
                id,
                local_seq,
                origin_machine_id,
                origin_seq,
                op,
                node_type,
                node_id,
                timestamp,
                data,
            });
        }

        Ok(entries)
    }

    pub fn get_sync_state(&self, peer_id: &str) -> Result<Option<SyncState>> {
        let conn = self.conn()?;
        let escaped = escape_cypher(peer_id);
        let mut result = conn.query(&format!(
            "MATCH (s:SyncState {{peer_id: '{}'}}) RETURN s.peer_id, s.last_seq, s.last_sync_at;",
            escaped
        ))?;

        match result.next() {
            Some(row) => {
                let peer_id = value_to_string(&row[0]);
                let last_seq = match &row[1] {
                    Value::Int64(n) => *n as u64,
                    _ => 0,
                };
                let last_sync_at_str = value_to_string(&row[2]);
                let last_sync_at = chrono::DateTime::parse_from_rfc3339(&last_sync_at_str)
                    .map(|dt| dt.with_timezone(&chrono::Utc))
                    .unwrap_or_else(|_| chrono::Utc::now());

                Ok(Some(SyncState {
                    peer_id,
                    last_seq,
                    last_sync_at,
                }))
            }
            None => Ok(None),
        }
    }

    pub fn set_sync_state(&self, state: &SyncState) -> Result<()> {
        let conn = self.conn()?;
        let peer_escaped = escape_cypher(&state.peer_id);
        let now = state.last_sync_at.to_rfc3339();

        conn.query(&format!(
            "MERGE (s:SyncState {{peer_id: '{}'}}) SET s.last_seq = {}, s.last_sync_at = '{}';",
            peer_escaped, state.last_seq, now
        ))?;
        Ok(())
    }

    pub fn get_all_sync_states(&self) -> Result<Vec<SyncState>> {
        let conn = self.conn()?;
        let mut result =
            conn.query("MATCH (s:SyncState) RETURN s.peer_id, s.last_seq, s.last_sync_at;")?;
        let mut states = Vec::new();

        for row in &mut result {
            let peer_id = value_to_string(&row[0]);
            let last_seq = match &row[1] {
                Value::Int64(n) => *n as u64,
                _ => 0,
            };
            let last_sync_at_str = value_to_string(&row[2]);
            let last_sync_at = chrono::DateTime::parse_from_rfc3339(&last_sync_at_str)
                .map(|dt| dt.with_timezone(&chrono::Utc))
                .unwrap_or_else(|_| chrono::Utc::now());

            states.push(SyncState {
                peer_id,
                last_seq,
                last_sync_at,
            });
        }

        Ok(states)
    }

    pub fn all_entities(&self) -> Result<Vec<Entity>> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (e:Entity) RETURN e.id, e.name, e.entity_type;")?;
        let mut entities = Vec::new();
        for row in &mut result {
            entities.push(row_to_entity(&row)?);
        }
        Ok(entities)
    }

    pub fn memories_for_entity(&self, entity_id: Uuid) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (m:Memory)-[:MENTIONS]->(e:Entity {{id: '{}'}}) RETURN {};",
            entity_id, memory_return_cols("m")
        );
        let mut result = conn.query(&query)?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    pub fn unassociated_memories(&self) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let mut result = conn.query(
            &format!("MATCH (m:Memory) WHERE NOT EXISTS {{MATCH (m)-[:MENTIONS]->(:Entity)}} RETURN {};", memory_return_cols("m"))
        )?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    pub fn related_entity_names(&self, entity_id: Uuid) -> Result<Vec<String>> {
        let conn = self.conn()?;
        let query = format!(
            "MATCH (m:Memory)-[:MENTIONS]->(e1:Entity {{id: '{}'}}), (m)-[:MENTIONS]->(e2:Entity) WHERE e2.id <> '{}' RETURN DISTINCT e2.name;",
            entity_id, entity_id
        );
        let mut result = conn.query(&query)?;
        let mut names = Vec::new();
        for row in &mut result {
            names.push(value_to_string(&row[0]));
        }
        Ok(names)
    }

    pub fn max_sync_seq(&self) -> Result<u64> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (s:SyncLog) RETURN max(s.local_seq);")?;
        match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => Ok(*n as u64),
                _ => Ok(0),
            },
            None => Ok(0),
        }
    }

    pub fn backfill_project_paths(&self) -> Result<u64> {
        let conn = self.conn()?;
        let mut result = conn.query(
            "MATCH (m:Memory)-[:DERIVED_FROM]->(c:Conversation) WHERE m.project_path = '' AND c.project_path IS NOT NULL AND c.project_path <> '' SET m.project_path = c.project_path RETURN count(m);"
        )?;
        match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => Ok(*n as u64),
                _ => Ok(0),
            },
            None => Ok(0),
        }
    }

    pub fn memories_by_project_path(&self, project_path: &str) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let escaped = escape_cypher(project_path);
        let cols = memory_return_cols("m");
        let query = format!(
            "MATCH (m:Memory) WHERE m.project_path = '{}' RETURN {} LIMIT 20;",
            escaped, cols
        );
        let mut result = conn.query(&query)?;
        let mut memories = Vec::new();
        for row in &mut result {
            memories.push(row_to_memory(&row)?);
        }
        Ok(memories)
    }

    pub fn all_memories_with_embeddings(&self) -> Result<Vec<Memory>> {
        let conn = self.conn()?;
        let mut result = conn.query(&format!(
            "MATCH (m:Memory) RETURN {}, m.embedding;",
            memory_return_cols("m")
        ))?;
        let mut acc = Vec::new();
        for row in &mut result {
            // row_to_memory nulls the embedding; repopulate it from the trailing
            // m.embedding column so callers get the real vector, not Vec::new().
            let mut memory = row_to_memory(&row[..12])?;
            memory.embedding = value_to_f32_vec(&row[12]);
            acc.push(memory);
        }
        Ok(acc)
    }

    pub fn backfill_sync_log(&self) -> Result<u64> {
        let mut count = 0u64;

        let memories = self.all_memories_with_embeddings()?;

        for memory in &memories {
            let origin_mid = memory.machine_id.clone();
            let data = serde_json::to_string(memory).ok();
            let node_id = memory.id.to_string();
            self.with_transaction(|conn| {
                self.append_sync_log(
                    conn,
                    SyncOp::Create,
                    SyncNodeType::Memory,
                    &node_id,
                    data.as_deref(),
                    &origin_mid,
                    None,
                )
            })?;
            count += 1;
        }

        let conversations: Vec<Conversation> = {
            let conn = self.conn()?;
            let mut result = conn.query(
                "MATCH (c:Conversation) RETURN c.id, c.source, c.machine_id, c.started_at, c.project_path;",
            )?;
            let mut acc = Vec::new();
            for row in &mut result {
                let id = Uuid::parse_str(&value_to_string(&row[0])).unwrap_or_default();
                let source = value_to_string(&row[1]);
                let machine_id = value_to_string(&row[2]);
                let started_at_str = value_to_string(&row[3]);
                let project_path = {
                    let s = value_to_string(&row[4]);
                    if s.is_empty() { None } else { Some(s) }
                };
                let started_at = chrono::DateTime::parse_from_rfc3339(&started_at_str)
                    .map(|dt| dt.with_timezone(&chrono::Utc))
                    .unwrap_or_else(|_| chrono::Utc::now());
                acc.push(Conversation { id, source, machine_id, started_at, project_path });
            }
            acc
        };

        for conv in &conversations {
            let origin_mid = conv.machine_id.clone();
            let data = serde_json::to_string(conv).ok();
            let node_id = conv.id.to_string();
            self.with_transaction(|conn| {
                self.append_sync_log(
                    conn,
                    SyncOp::Create,
                    SyncNodeType::Conversation,
                    &node_id,
                    data.as_deref(),
                    &origin_mid,
                    None,
                )
            })?;
            count += 1;
        }

        Ok(count)
    }
}

impl KuzuStore {
    pub fn upsert_machine(&self, id: &str, name: &str) -> Result<()> {
        let conn = self.conn()?;
        let id_escaped = escape_cypher(id);
        let name_escaped = escape_cypher(name);
        conn.query(&format!(
            "MERGE (m:Machine {{id: '{id_escaped}'}}) SET m.name = '{name_escaped}';"
        ))?;
        Ok(())
    }

    pub fn get_machine_name(&self, id: &str) -> Result<Option<String>> {
        let conn = self.conn()?;
        let id_escaped = escape_cypher(id);
        let mut result = conn.query(&format!(
            "MATCH (m:Machine {{id: '{id_escaped}'}}) RETURN m.name;"
        ))?;
        match result.next() {
            Some(row) => Ok(Some(value_to_string(&row[0]))),
            None => Ok(None),
        }
    }

    pub fn get_all_machines(&self) -> Result<std::collections::HashMap<String, String>> {
        let conn = self.conn()?;
        let mut result = conn.query("MATCH (m:Machine) RETURN m.id, m.name;")?;
        let mut map = std::collections::HashMap::new();
        for row in &mut result {
            map.insert(value_to_string(&row[0]), value_to_string(&row[1]));
        }
        Ok(map)
    }

    pub fn backfill_machine_id(&self, machine_id: &str) -> Result<u64> {
        let conn = self.conn()?;
        let escaped = escape_cypher(machine_id);
        let mut result = conn.query(&format!(
            "MATCH (m:Memory) WHERE m.machine_id = '' SET m.machine_id = '{escaped}' RETURN count(m);"
        ))?;
        match result.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => Ok(*n as u64),
                _ => Ok(0),
            },
            None => Ok(0),
        }
    }

    pub fn register_machine(&self, identity: &crate::machine::MachineIdentity) -> Result<()> {
        self.upsert_machine(&identity.id, &identity.name)?;
        let count = self.backfill_machine_id(&identity.id)?;
        if count > 0 {
            tracing::info!("backfilled machine_id on {count} existing memories");
        }
        Ok(())
    }
}

fn format_embedding(embedding: &[f32]) -> String {
    if embedding.is_empty() {
        let zeros: Vec<String> = (0..384).map(|_| "0.0".to_string()).collect();
        return format!("[{}]", zeros.join(","));
    }
    let parts: Vec<String> = embedding.iter().map(|v| format!("{}", v)).collect();
    format!("[{}]", parts.join(","))
}

fn escape_cypher(s: &str) -> String {
    s.replace('\\', "\\\\").replace('\'', "\\'")
}

fn format_string_array(items: &[String]) -> String {
    let parts: Vec<String> = items
        .iter()
        .map(|s| format!("'{}'", s.replace('\'', "''")))
        .collect();
    format!("[{}]", parts.join(","))
}

fn value_to_string(val: &Value) -> String {
    match val {
        Value::String(s) => s.clone(),
        other => format!("{:?}", other),
    }
}

fn value_to_f32(val: &Value) -> f32 {
    match val {
        Value::Float(f) => *f,
        Value::Double(d) => *d as f32,
        Value::Int64(i) => *i as f32,
        _ => 0.0,
    }
}

fn value_to_f32_vec(val: &Value) -> Vec<f32> {
    match val {
        Value::Array(_, items) | Value::List(_, items) => items.iter().map(value_to_f32).collect(),
        _ => Vec::new(),
    }
}

fn row_to_memory(row: &[Value]) -> Result<Memory> {
    let id_str = value_to_string(&row[0]);
    let id = Uuid::parse_str(&id_str).unwrap_or_default();
    let content = value_to_string(&row[1]);
    let memory_type_str = value_to_string(&row[2]);
    let confidence = value_to_f32(&row[3]);
    let created_at_str = value_to_string(&row[4]);
    let last_accessed_str = value_to_string(&row[5]);
    let access_count = match &row[6] {
        Value::Int64(i) => *i as u32,
        _ => 0,
    };
    let source = value_to_string(&row[7]);
    let source_id = value_to_string(&row[8]);
    let project_path = project_path_from_db(&value_to_string(&row[9]));
    let machine_id = value_to_string(&row[10]);
    let updated_at_str = value_to_string(&row[11]);

    let memory_type = match memory_type_str.as_str() {
        "episodic" => MemoryType::Episodic,
        "procedural" => MemoryType::Procedural,
        "decision" => MemoryType::Decision,
        "architecture" => MemoryType::Architecture,
        "debugging" => MemoryType::Debugging,
        "task" => MemoryType::Task,
        "question" => MemoryType::Question,
        _ => MemoryType::Semantic,
    };

    let created_at = chrono::DateTime::parse_from_rfc3339(&created_at_str)
        .map(|dt| dt.with_timezone(&chrono::Utc))
        .unwrap_or_else(|_| chrono::Utc::now());

    let last_accessed = chrono::DateTime::parse_from_rfc3339(&last_accessed_str)
        .map(|dt| dt.with_timezone(&chrono::Utc))
        .unwrap_or_else(|_| chrono::Utc::now());

    let updated_at = if updated_at_str.is_empty() {
        created_at
    } else {
        chrono::DateTime::parse_from_rfc3339(&updated_at_str)
            .map(|dt| dt.with_timezone(&chrono::Utc))
            .unwrap_or(created_at)
    };

    Ok(Memory {
        id,
        content,
        embedding: Vec::new(),
        memory_type,
        confidence,
        created_at,
        last_accessed,
        access_count,
        source,
        source_id,
        project_path,
        machine_id,
        updated_at,
    })
}

fn row_to_entity(row: &[Value]) -> Result<Entity> {
    let id_str = value_to_string(&row[0]);
    let id = Uuid::parse_str(&id_str).unwrap_or_default();
    let name = value_to_string(&row[1]);
    let entity_type = value_to_string(&row[2]);

    Ok(Entity {
        id,
        name,
        entity_type,
        embedding: Vec::new(),
        aliases: Vec::new(),
    })
}

unsafe impl Send for KuzuStore {}
unsafe impl Sync for KuzuStore {}

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

    #[test]
    fn migrate_sync_log_recreates_old_schema_and_resets_cursors() {
        let store = KuzuStore::in_memory("test-machine-migrate".to_string()).unwrap();
        let conn = store.conn().unwrap();

        // Tear down the new-schema table that init_schema already created and
        // replace it with the pre-redesign schema (seq INT64 PRIMARY KEY).
        conn.query("DROP TABLE SyncLog;").unwrap();
        conn.query(
            "CREATE NODE TABLE SyncLog(\
                seq INT64 PRIMARY KEY, \
                op STRING, \
                node_type STRING, \
                node_id STRING, \
                machine_id STRING, \
                timestamp STRING, \
                data STRING\
            );",
        )
        .unwrap();
        conn.query(
            "CREATE (:SyncLog {seq: 1, op: 'create', node_type: 'memory', \
             node_id: 'abc', machine_id: 'old-machine', \
             timestamp: '2024-01-01T00:00:00Z', data: ''});",
        )
        .unwrap();

        // Seed a SyncState cursor at a non-zero position so we can verify it gets reset.
        conn.query(
            "MERGE (s:SyncState {peer_id: 'peer-x'}) \
             SET s.last_seq = 5, s.last_sync_at = '2024-01-01T00:00:00Z';",
        )
        .unwrap();

        store.migrate_sync_log(&conn).unwrap();

        // New-schema column must exist (table was recreated with id STRING PRIMARY KEY).
        assert!(
            conn.query("MATCH (s:SyncLog) RETURN s.id LIMIT 1;").is_ok(),
            "new-schema column s.id must be present after migration"
        );

        // SyncState cursor must have been reset to 0.
        let mut r = conn
            .query(
                "MATCH (s:SyncState {peer_id: 'peer-x'}) RETURN s.last_seq;",
            )
            .unwrap();
        let last_seq = match r.next() {
            Some(row) => match &row[0] {
                Value::Int64(n) => *n,
                _ => panic!("unexpected value type for last_seq"),
            },
            None => panic!("SyncState row not found after migration"),
        };
        assert_eq!(last_seq, 0, "last_seq must be reset to 0 after migration");
    }

    #[test]
    fn rollback_leaves_no_partial_state() {
        let store = KuzuStore::in_memory("test-machine-rollback".to_string()).unwrap();
        let embedding = std::iter::repeat("0.0")
            .take(384)
            .collect::<Vec<_>>()
            .join(", ");

        let result: Result<()> = store.with_transaction(|conn| {
            conn.query(&format!(
                "CREATE (:Memory {{id: 'rollback-test-id', content: 'x', \
                 embedding: [{embedding}], memory_type: 'semantic', confidence: 1.0, \
                 created_at: '2024-01-01T00:00:00Z', last_accessed: '2024-01-01T00:00:00Z', \
                 access_count: 0, source: 'test', source_id: '', project_path: '', \
                 machine_id: 'x', updated_at: '2024-01-01T00:00:00Z'}});"
            ))?;
            Err(anyhow::anyhow!("deliberate rollback"))
        });

        assert!(
            result.is_err(),
            "with_transaction must propagate the closure error"
        );

        let entries = store.sync_log_since(0).unwrap();
        assert_eq!(entries.len(), 0, "no SyncLog rows may survive a rollback");
        assert_eq!(
            store.memory_count().unwrap(),
            0,
            "the Memory node created inside the transaction must be rolled back"
        );
    }

    fn memory_with_embedding(content: &str, embedding: Vec<f32>) -> Memory {
        let mut m = Memory::new(
            content.to_string(),
            MemoryType::Semantic,
            "test".to_string(),
            String::new(),
        );
        m.embedding = embedding;
        m
    }

    #[test]
    fn recall_reflects_new_relation_after_cache_invalidation() {
        use crate::query::{QueryEngine, QueryFilters, QueryRequest};

        let store = KuzuStore::in_memory("test-machine-invalidate".to_string()).unwrap();

        let mut emb_a = vec![0.0_f32; 384];
        emb_a[0] = 1.0;
        let mut emb_b = vec![0.0_f32; 384];
        emb_b[1] = 1.0;
        let target = memory_with_embedding("kuzu is the embedded graph store", emb_a.clone());
        let neighbor = memory_with_embedding("an unrelated note about sync", emb_b);
        store.store_memory(&target).unwrap();
        store.store_memory(&neighbor).unwrap();

        let request = QueryRequest {
            text: "graph store".to_string(),
            embedding: emb_a,
            limit: 10,
            filters: QueryFilters::default(),
        };

        let before = QueryEngine::new(&store).recall(&request).unwrap();
        let before_score = before
            .iter()
            .find(|r| r.memory.id == target.id)
            .expect("target must be recalled")
            .score;

        // Adding a Reinforces edge raises the graph-relevance term, so a stale cache
        // (which returned the empty pre-edge relation list) would leave the score
        // unchanged. Asserting the score rises proves store_relation evicted the key.
        let rel = Relation {
            from_id: target.id,
            to_id: neighbor.id,
            relation_type: RelationType::Reinforces,
            strength: 1.0,
            context: None,
        };
        store.store_relation(&rel).unwrap();

        let after = QueryEngine::new(&store).recall(&request).unwrap();
        let after_score = after
            .iter()
            .find(|r| r.memory.id == target.id)
            .expect("target must still be recalled")
            .score;

        assert!(
            after_score > before_score,
            "recall must reflect the new relation: before={before_score} after={after_score}"
        );
    }

    #[test]
    fn get_relations_cached_matches_fresh_uncached_store() {
        let machine = "test-machine-equivalence".to_string();
        let warm = KuzuStore::in_memory(machine.clone()).unwrap();

        let a = memory_with_embedding("memory a", {
            let mut e = vec![0.0_f32; 384];
            e[0] = 1.0;
            e
        });
        let b = memory_with_embedding("memory b", {
            let mut e = vec![0.0_f32; 384];
            e[1] = 1.0;
            e
        });
        let c = memory_with_embedding("memory c", {
            let mut e = vec![0.0_f32; 384];
            e[2] = 1.0;
            e
        });
        for m in [&a, &b, &c] {
            warm.store_memory(m).unwrap();
        }
        let rels = [
            Relation {
                from_id: a.id,
                to_id: b.id,
                relation_type: RelationType::RelatesTo,
                strength: 0.7,
                context: None,
            },
            Relation {
                from_id: a.id,
                to_id: c.id,
                relation_type: RelationType::Reinforces,
                strength: 1.0,
                context: None,
            },
            Relation {
                from_id: b.id,
                to_id: c.id,
                relation_type: RelationType::Supersedes,
                strength: 1.0,
                context: None,
            },
        ];
        for r in &rels {
            warm.store_relation(r).unwrap();
        }

        // Warm the cache by reading every (id, type) pair twice; the second read is a
        // cache hit. A freshly opened store sees the same persisted data with an empty
        // cache, so the two must agree edge-for-edge.
        let types = [
            None,
            Some(RelationType::RelatesTo),
            Some(RelationType::Reinforces),
            Some(RelationType::Supersedes),
            Some(RelationType::Mentions),
        ];
        for id in [a.id, b.id, c.id] {
            for rt in types {
                let first = warm.get_relations(id, rt).unwrap();
                let second = warm.get_relations(id, rt).unwrap();
                assert_eq!(
                    first.len(),
                    second.len(),
                    "cache hit must match the live read for ({id}, {rt:?})"
                );
                let mut a_ids: Vec<Uuid> = first.iter().map(|r| r.to_id).collect();
                let mut b_ids: Vec<Uuid> = second.iter().map(|r| r.to_id).collect();
                a_ids.sort();
                b_ids.sort();
                assert_eq!(a_ids, b_ids);
            }
        }
    }
}