allsource-core 0.19.1

High-performance event store core built in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
//! Prime facade — high-level entry point wrapping [`EmbeddedCore`].
//!
//! Configures merge strategies for graph events, registers Prime projections,
//! and exposes graph-aware convenience methods on top of the event store.

use std::{path::Path, sync::Arc};

use chrono::{DateTime, Utc};
use serde_json::{Value, json};

use crate::{
    application::services::projection::Projection as _,
    embedded::{Config, EmbeddedCore, IngestEvent, Query},
    error::Result,
    infrastructure::cluster::crdt::MergeStrategy,
};

use super::{
    error::{PrimeError, PrimeResult},
    projections::{
        AdjacencyListProjection, Contradiction, ContradictionDetectionProjection,
        CrossDomainProjection, GraphStatsProjection, NodeStateProjection, NodeTypeIndexProjection,
        ReverseIndexProjection,
    },
    schema::SchemaProjection,
    types::{
        Direction, Edge, EdgeId, Node, NodeId, PrimeStats, edge_entity_id, event_types,
        node_entity_id,
    },
};

// Well-known projection names used by the facade.
const PROJ_NODE_STATE: &str = "prime.node_state";
const PROJ_NODE_TYPE_INDEX: &str = "prime.node_type_index";
const PROJ_ADJACENCY: &str = "prime.adjacency";
const PROJ_REVERSE_INDEX: &str = "prime.reverse_index";
const PROJ_GRAPH_STATS: &str = "prime.graph_stats";
const PROJ_SCHEMA: &str = "prime.schema";
const PROJ_CONTRADICTION: &str = "prime.contradiction";
const PROJ_CROSS_DOMAIN: &str = "prime.cross_domain";
#[cfg(feature = "prime-vectors")]
const PROJ_VECTOR_INDEX: &str = "prime.vector_index";

/// High-level Prime engine wrapping [`EmbeddedCore`] with graph-aware
/// merge strategies and projections.
pub struct Prime {
    core: EmbeddedCore,
    node_state: Arc<NodeStateProjection>,
    node_type_index: Arc<NodeTypeIndexProjection>,
    adjacency: Arc<AdjacencyListProjection>,
    reverse_index: Arc<ReverseIndexProjection>,
    graph_stats: Arc<GraphStatsProjection>,
    schema: Arc<SchemaProjection>,
    contradiction: Arc<ContradictionDetectionProjection>,
    cross_domain: Arc<CrossDomainProjection>,
    #[cfg(feature = "prime-vectors")]
    vector_index: Arc<super::vectors::VectorIndexProjection>,
}

impl Prime {
    /// Build an `EmbeddedConfig` with Prime merge strategies.
    fn config_builder() -> crate::embedded::ConfigBuilder {
        Config::builder()
            .merge_strategy(event_types::NODE_CREATED, MergeStrategy::FirstWriteWins)
            .merge_strategy(event_types::NODE_UPDATED, MergeStrategy::LastWriteWins)
            .merge_strategy(event_types::EDGE_CREATED, MergeStrategy::AppendOnly)
            .merge_strategy(event_types::EDGE_DELETED, MergeStrategy::LastWriteWins)
            .merge_strategy(event_types::NODE_DELETED, MergeStrategy::LastWriteWins)
    }

    /// Register all graph projections on the underlying store.
    #[allow(clippy::type_complexity)]
    fn register_graph_projections(
        store: &Arc<crate::store::EventStore>,
    ) -> (
        Arc<NodeStateProjection>,
        Arc<NodeTypeIndexProjection>,
        Arc<AdjacencyListProjection>,
        Arc<ReverseIndexProjection>,
        Arc<GraphStatsProjection>,
        Arc<SchemaProjection>,
        Arc<ContradictionDetectionProjection>,
        Arc<CrossDomainProjection>,
    ) {
        let node_state = Arc::new(NodeStateProjection::new(PROJ_NODE_STATE));
        let node_type_index = Arc::new(NodeTypeIndexProjection::new(PROJ_NODE_TYPE_INDEX));
        let adjacency = Arc::new(AdjacencyListProjection::new_forward(PROJ_ADJACENCY));
        let reverse_index = Arc::new(ReverseIndexProjection::new_reverse(PROJ_REVERSE_INDEX));
        let graph_stats = Arc::new(GraphStatsProjection::new(PROJ_GRAPH_STATS));
        let schema = Arc::new(SchemaProjection::new(PROJ_SCHEMA));
        let contradiction = Arc::new(ContradictionDetectionProjection::new(PROJ_CONTRADICTION));
        let cross_domain = Arc::new(CrossDomainProjection::new());

        type DynProj = Arc<dyn crate::application::services::projection::Projection>;

        let _ = store.register_projection_with_backfill(&(Arc::clone(&node_state) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&node_type_index) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&adjacency) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&reverse_index) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&graph_stats) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&schema) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&contradiction) as DynProj));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&cross_domain) as DynProj));

        (
            node_state,
            node_type_index,
            adjacency,
            reverse_index,
            graph_stats,
            schema,
            contradiction,
            cross_domain,
        )
    }

    /// Register vector index projection (only when prime-vectors feature is enabled).
    #[cfg(feature = "prime-vectors")]
    fn register_vector_projection(
        store: &Arc<crate::store::EventStore>,
    ) -> Arc<super::vectors::VectorIndexProjection> {
        type DynProj = Arc<dyn crate::application::services::projection::Projection>;
        let vi = Arc::new(super::vectors::VectorIndexProjection::new(
            PROJ_VECTOR_INDEX,
        ));
        let _ = store.register_projection_with_backfill(&(Arc::clone(&vi) as DynProj));
        vi
    }

    /// Build a `Prime` instance from a configured `EmbeddedCore`.
    fn from_core(core: EmbeddedCore) -> Self {
        let store = core.inner();
        let (
            node_state,
            node_type_index,
            adjacency,
            reverse_index,
            graph_stats,
            schema,
            contradiction,
            cross_domain,
        ) = Self::register_graph_projections(&store);
        #[cfg(feature = "prime-vectors")]
        let vector_index = Self::register_vector_projection(&store);

        Self {
            core,
            node_state,
            node_type_index,
            adjacency,
            reverse_index,
            graph_stats,
            schema,
            contradiction,
            cross_domain,
            #[cfg(feature = "prime-vectors")]
            vector_index,
        }
    }

    /// Open a durable Prime instance at `path`.
    pub async fn open(path: impl AsRef<Path>) -> Result<Self> {
        let config = Self::config_builder().data_dir(path.as_ref()).build()?;
        let core = EmbeddedCore::open(config).await?;
        Ok(Self::from_core(core))
    }

    /// Open an in-memory Prime instance (no persistence). Useful for testing.
    pub async fn open_in_memory() -> Result<Self> {
        let config = Self::config_builder().build()?;
        let core = EmbeddedCore::open(config).await?;
        Ok(Self::from_core(core))
    }

    /// Shut down the Prime engine, flushing all pending writes.
    pub async fn shutdown(self) -> Result<()> {
        self.core.shutdown().await
    }

    /// Return statistics about the Prime graph (O(1) via projection).
    pub fn stats(&self) -> PrimeStats {
        self.graph_stats.stats()
    }

    /// Access the underlying [`EmbeddedCore`] for direct event operations.
    pub fn core(&self) -> &EmbeddedCore {
        &self.core
    }

    /// Return shared projection dependencies for the Recall engine.
    ///
    /// Shares Prime's node_state, adjacency, graph_stats, and cross_domain
    /// projections with RecallEngine, enabling L0/L1 tiers. A fresh
    /// `DomainIndexProjection` is created (RecallEngine registers it separately).
    #[cfg(feature = "prime-recall")]
    pub fn recall_deps(&self) -> super::recall::RecallDeps {
        super::recall::RecallDeps {
            domain_index: Arc::new(super::projections::DomainIndexProjection::new()),
            cross_domain: Arc::clone(&self.cross_domain),
            node_state: Some(Arc::clone(&self.node_state)),
            adjacency: Some(Arc::clone(&self.adjacency)),
            graph_stats: Some(Arc::clone(&self.graph_stats)),
        }
    }

    // =========================================================================
    // Schema Enforcement
    // =========================================================================

    /// Register a JSON schema for a node type. Properties will be validated
    /// on `add_node()` and `update_node()`. Stored as an event for durability.
    pub async fn register_schema(
        &self,
        type_name: &str,
        kind: super::schema::SchemaKind,
        schema: Value,
    ) -> PrimeResult<()> {
        let entity_id = format!("schema:{type_name}");
        self.core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: super::schema::SCHEMA_REGISTERED,
                payload: json!({
                    "type_name": type_name,
                    "kind": match kind {
                        super::schema::SchemaKind::Node => "node",
                        super::schema::SchemaKind::Edge => "edge",
                    },
                    "schema": schema,
                }),
                metadata: None,
                tenant_id: None,
            })
            .await?;
        Ok(())
    }

    /// List all registered schemas.
    pub fn schemas(&self) -> Vec<super::schema::SchemaEntry> {
        self.schema.schemas()
    }

    // =========================================================================
    // Contradiction Detection
    // =========================================================================

    /// Mark a relation as exclusive (only one target per source) and backfill
    /// existing edges to detect pre-existing contradictions.
    pub fn configure_exclusive(&self, relation: &str) {
        let all_entity_ids = self.node_type_index.all_entity_ids();
        self.contradiction.configure_exclusive(relation);
        self.contradiction
            .backfill_exclusive(relation, &self.adjacency, &all_entity_ids);
    }

    /// List all unresolved contradictions.
    pub fn contradictions(&self) -> Vec<Contradiction> {
        self.contradiction.contradictions()
    }

    /// Resolve a contradiction by keeping the specified edge. Deletes the other.
    pub async fn resolve_contradiction(
        &self,
        contradiction_id: &str,
        keep_edge: &str,
    ) -> PrimeResult<()> {
        if let Some(delete_edge) = self.contradiction.resolve(contradiction_id, keep_edge) {
            self.delete_edge(&delete_edge).await?;
        }
        Ok(())
    }

    // =========================================================================
    // Node CRUD
    // =========================================================================

    /// Create a new graph node. Returns the generated [`NodeId`].
    ///
    /// If a schema is registered for `node_type`, properties are validated first.
    pub async fn add_node(
        &self,
        node_type: &str,
        properties: serde_json::Value,
    ) -> PrimeResult<NodeId> {
        self.schema.validate_node(node_type, &properties)?;

        let id = uuid::Uuid::new_v4().to_string();
        let entity_id = node_entity_id(node_type, &id);

        self.core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: event_types::NODE_CREATED,
                payload: json!({
                    "id": id,
                    "node_type": node_type,
                    "properties": properties,
                }),
                metadata: None,
                tenant_id: None,
            })
            .await?;

        Ok(NodeId::new(id))
    }

    /// Get a node by its entity_id. Returns `None` if deleted or not found.
    pub fn get_node(&self, entity_id: &str) -> Option<Node> {
        let node = self.node_state.get_node(entity_id)?;
        if node.deleted {
            return None;
        }
        Some(node)
    }

    /// Update a node's properties (deep merge).
    ///
    /// Validates the merged result against any registered schema.
    ///
    /// **Eventual consistency:** Between the existence check and the ingest,
    /// another task could delete this node. The update event will be a no-op
    /// in the projection (see ADR-016).
    pub async fn update_node(
        &self,
        entity_id: &str,
        properties: serde_json::Value,
    ) -> PrimeResult<()> {
        let node = self
            .node_state
            .get_node(entity_id)
            .filter(|n| !n.deleted)
            .ok_or_else(|| PrimeError::NodeNotFound(entity_id.to_string()))?;

        // Validate the merged properties against the schema
        let mut merged = node.properties.clone();
        if let (Value::Object(base), Value::Object(update)) = (&mut merged, &properties) {
            for (k, v) in update {
                base.insert(k.clone(), v.clone());
            }
        }
        self.schema.validate_node(&node.node_type, &merged)?;

        self.core
            .ingest(IngestEvent {
                entity_id,
                event_type: event_types::NODE_UPDATED,
                payload: json!({ "properties": properties }),
                metadata: None,
                tenant_id: None,
            })
            .await?;

        Ok(())
    }

    /// Delete a node and all its connected edges atomically.
    ///
    /// Uses `ingest_batch` to emit all edge-deletion + node-deletion events
    /// in a single WAL write (ADR-013). Includes source/target in edge-delete
    /// payloads for O(1) adjacency index updates (ADR-012).
    pub async fn delete_node(&self, entity_id: &str) -> PrimeResult<()> {
        if !self.node_state.is_live(entity_id) {
            return Err(PrimeError::NodeNotFound(entity_id.to_string()));
        }

        // Collect all edge entity_ids and payloads for batch
        let outgoing = self.adjacency.outgoing(entity_id);
        let incoming = self.reverse_index.incoming(entity_id);

        // Build owned data for the batch (IngestEvent borrows strings)
        struct EdgeDel {
            entity_id: String,
            payload: serde_json::Value,
        }

        let mut edge_dels: Vec<EdgeDel> = Vec::with_capacity(outgoing.len() + incoming.len());
        let mut seen_edge_ids = std::collections::HashSet::new();

        for adj in &outgoing {
            if seen_edge_ids.insert(adj.edge_id.clone()) {
                edge_dels.push(EdgeDel {
                    entity_id: format!("edge:{}", adj.edge_id),
                    payload: json!({"id": adj.edge_id, "source": entity_id, "target": adj.peer}),
                });
            }
        }
        for adj in &incoming {
            if seen_edge_ids.insert(adj.edge_id.clone()) {
                edge_dels.push(EdgeDel {
                    entity_id: format!("edge:{}", adj.edge_id),
                    payload: json!({"id": adj.edge_id, "source": adj.peer, "target": entity_id}),
                });
            }
        }

        // Build batch: edge deletes + node delete
        let mut batch: Vec<IngestEvent<'_>> = edge_dels
            .iter()
            .map(|ed| IngestEvent {
                entity_id: &ed.entity_id,
                event_type: event_types::EDGE_DELETED,
                payload: ed.payload.clone(),
                metadata: None,
                tenant_id: None,
            })
            .collect();

        batch.push(IngestEvent {
            entity_id,
            event_type: event_types::NODE_DELETED,
            payload: json!({}),
            metadata: None,
            tenant_id: None,
        });

        self.core.ingest_batch(batch).await?;
        Ok(())
    }

    /// Get all nodes of a given type.
    pub fn nodes_by_type(&self, node_type: &str) -> Vec<Node> {
        self.node_type_index
            .nodes_by_type(node_type)
            .iter()
            .filter_map(|entity_id| self.get_node(entity_id))
            .collect()
    }

    // =========================================================================
    // Edge CRUD
    // =========================================================================

    /// Create a directed edge between two nodes. Returns the generated [`EdgeId`].
    pub async fn add_edge(
        &self,
        source: &str,
        target: &str,
        relation: &str,
        properties: Option<serde_json::Value>,
    ) -> PrimeResult<EdgeId> {
        self.add_edge_inner(source, target, relation, None, properties)
            .await
    }

    /// Create a weighted directed edge between two nodes.
    pub async fn add_edge_weighted(
        &self,
        source: &str,
        target: &str,
        relation: &str,
        weight: f64,
        properties: Option<serde_json::Value>,
    ) -> PrimeResult<EdgeId> {
        self.add_edge_inner(source, target, relation, Some(weight), properties)
            .await
    }

    async fn add_edge_inner(
        &self,
        source: &str,
        target: &str,
        relation: &str,
        weight: Option<f64>,
        properties: Option<serde_json::Value>,
    ) -> PrimeResult<EdgeId> {
        // Validate source and target exist and are not deleted.
        // Note: eventual consistency — node could be deleted between check and
        // ingest. The edge event is harmless in that case (ADR-016).
        if !self.node_state.is_live(source) {
            return Err(PrimeError::NodeNotFound(source.to_string()));
        }
        if !self.node_state.is_live(target) {
            return Err(PrimeError::NodeNotFound(target.to_string()));
        }

        // Validate edge properties against registered schema
        self.schema.validate_edge(relation, properties.as_ref())?;

        let id = uuid::Uuid::new_v4().to_string();
        let entity_id = edge_entity_id(&id);

        let mut payload = json!({
            "id": id,
            "source": source,
            "target": target,
            "relation": relation,
        });

        if let Some(w) = weight {
            payload["weight"] = json!(w);
        }
        if let Some(props) = properties {
            payload["properties"] = props;
        }

        self.core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: event_types::EDGE_CREATED,
                payload,
                metadata: None,
                tenant_id: None,
            })
            .await?;

        Ok(EdgeId::new(id))
    }

    /// Get an edge by its ID. Queries the event store for the edge creation event.
    pub async fn get_edge(&self, edge_id: &str) -> PrimeResult<Option<Edge>> {
        let entity_id = edge_entity_id(edge_id);
        let events = self.core.query(Query::new().entity_id(&entity_id)).await?;

        // Check if deleted
        let is_deleted = events
            .iter()
            .any(|e| e.event_type == event_types::EDGE_DELETED);
        if is_deleted {
            return Ok(None);
        }

        // Find creation event
        let created = events
            .iter()
            .find(|e| e.event_type == event_types::EDGE_CREATED);

        Ok(created.and_then(edge_from_event))
    }

    /// Delete an edge.
    pub async fn delete_edge(&self, edge_id: &str) -> PrimeResult<()> {
        let entity_id = edge_entity_id(edge_id);

        self.core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: event_types::EDGE_DELETED,
                payload: json!({"id": edge_id}),
                metadata: None,
                tenant_id: None,
            })
            .await?;

        Ok(())
    }

    // =========================================================================
    // Memory Compaction
    // =========================================================================

    /// Merge source nodes into the target node.
    ///
    /// - Properties are merged (target values take precedence on conflict)
    /// - All edges pointing to/from source nodes are redirected to target
    /// - Source nodes are soft-deleted
    /// - A `prime.memory.compacted` event is emitted for the audit trail
    ///
    /// The original state is preserved in event history and can be reconstructed
    /// via `as_of` time-travel queries.
    pub async fn compact(
        &self,
        target_entity_id: &str,
        source_entity_ids: &[&str],
    ) -> PrimeResult<()> {
        // Verify target exists
        let target_node = self
            .get_node(target_entity_id)
            .ok_or_else(|| PrimeError::NodeNotFound(target_entity_id.to_string()))?;

        // Collect properties from all sources for merging
        let mut merged_properties = target_node.properties.clone();
        let mut merged_source_ids = Vec::new();

        for &source_id in source_entity_ids {
            let source_node = self
                .get_node(source_id)
                .ok_or_else(|| PrimeError::NodeNotFound(source_id.to_string()))?;

            // Merge properties: source values fill gaps, target values win on conflict
            if let (Value::Object(target_map), Value::Object(source_map)) =
                (&mut merged_properties, &source_node.properties)
            {
                for (key, value) in source_map {
                    target_map
                        .entry(key.clone())
                        .or_insert_with(|| value.clone());
                }
            }

            merged_source_ids.push(source_id.to_string());

            // Redirect outgoing edges from source to target
            for entry in self.adjacency.outgoing(source_id) {
                // Don't create self-loops (if source pointed to target)
                if entry.peer == target_entity_id {
                    continue;
                }
                // Don't redirect if it would create a duplicate edge
                // (target already has same relation to same peer)
                let already_exists = self
                    .adjacency
                    .outgoing(target_entity_id)
                    .iter()
                    .any(|e| e.peer == entry.peer && e.relation == entry.relation);

                if !already_exists {
                    self.core
                        .ingest(IngestEvent {
                            entity_id: &edge_entity_id(&uuid::Uuid::new_v4().to_string()),
                            event_type: event_types::EDGE_CREATED,
                            payload: json!({
                                "id": uuid::Uuid::new_v4().to_string(),
                                "source": target_entity_id,
                                "target": entry.peer,
                                "relation": entry.relation,
                            }),
                            metadata: None,
                            tenant_id: None,
                        })
                        .await?;
                }

                // Delete the old edge from source
                self.core
                    .ingest(IngestEvent {
                        entity_id: &edge_entity_id(&entry.edge_id),
                        event_type: event_types::EDGE_DELETED,
                        payload: json!({"id": entry.edge_id}),
                        metadata: None,
                        tenant_id: None,
                    })
                    .await?;
            }

            // Redirect incoming edges to source → point to target instead
            for entry in self.reverse_index.incoming(source_id) {
                // Don't create self-loops
                if entry.peer == target_entity_id {
                    continue;
                }
                let already_exists = self
                    .reverse_index
                    .incoming(target_entity_id)
                    .iter()
                    .any(|e| e.peer == entry.peer && e.relation == entry.relation);

                if !already_exists {
                    self.core
                        .ingest(IngestEvent {
                            entity_id: &edge_entity_id(&uuid::Uuid::new_v4().to_string()),
                            event_type: event_types::EDGE_CREATED,
                            payload: json!({
                                "id": uuid::Uuid::new_v4().to_string(),
                                "source": entry.peer,
                                "target": target_entity_id,
                                "relation": entry.relation,
                            }),
                            metadata: None,
                            tenant_id: None,
                        })
                        .await?;
                }

                // Delete the old edge
                self.core
                    .ingest(IngestEvent {
                        entity_id: &edge_entity_id(&entry.edge_id),
                        event_type: event_types::EDGE_DELETED,
                        payload: json!({"id": entry.edge_id}),
                        metadata: None,
                        tenant_id: None,
                    })
                    .await?;
            }

            // Soft-delete the source node
            self.core
                .ingest(IngestEvent {
                    entity_id: source_id,
                    event_type: event_types::NODE_DELETED,
                    payload: json!({}),
                    metadata: None,
                    tenant_id: None,
                })
                .await?;
        }

        // Update target with merged properties
        self.core
            .ingest(IngestEvent {
                entity_id: target_entity_id,
                event_type: event_types::NODE_UPDATED,
                payload: json!({
                    "properties": merged_properties,
                }),
                metadata: None,
                tenant_id: None,
            })
            .await?;

        // Emit compaction event for audit trail
        self.core
            .ingest(IngestEvent {
                entity_id: target_entity_id,
                event_type: "prime.memory.compacted",
                payload: json!({
                    "target": target_entity_id,
                    "merged_from": merged_source_ids,
                }),
                metadata: None,
                tenant_id: None,
            })
            .await?;

        // Clean up vectors associated with merged source nodes
        #[cfg(feature = "prime-vectors")]
        {
            for source_id in &merged_source_ids {
                let vec_entity_id = super::vectors::vector_entity_id(source_id);
                // Check if source had a stored vector
                if self.vector_index.get_state(&vec_entity_id).is_some() {
                    self.core
                        .ingest(IngestEvent {
                            entity_id: &vec_entity_id,
                            event_type: super::vectors::event_types::VECTOR_DELETED,
                            payload: json!({}),
                            metadata: None,
                            tenant_id: None,
                        })
                        .await?;
                }
            }
        }

        Ok(())
    }

    // =========================================================================
    // Vector Operations (requires `prime-vectors` feature)
    // =========================================================================

    /// Store a vector embedding associated with an entity.
    #[cfg(feature = "prime-vectors")]
    pub async fn embed(&self, id: &str, text: Option<&str>, vector: Vec<f32>) -> PrimeResult<()> {
        self.embed_with_metadata(id, text, vector, None).await
    }

    /// Store a vector embedding with additional metadata.
    #[cfg(feature = "prime-vectors")]
    pub async fn embed_with_metadata(
        &self,
        id: &str,
        text: Option<&str>,
        vector: Vec<f32>,
        metadata: Option<serde_json::Value>,
    ) -> PrimeResult<()> {
        let entity_id = super::vectors::vector_entity_id(id);
        let dimensions = vector.len();

        self.core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: super::vectors::event_types::VECTOR_STORED,
                payload: json!({
                    "text": text,
                    "dimensions": dimensions,
                    "metadata": metadata,
                }),
                metadata: Some(json!({ "embedding": vector })),
                tenant_id: None,
            })
            .await?;

        Ok(())
    }

    /// Find the `top_k` most similar vectors to the one stored at `id`.
    #[cfg(feature = "prime-vectors")]
    pub fn similar(
        &self,
        id: &str,
        top_k: usize,
    ) -> PrimeResult<Vec<super::vectors::VectorSearchResult>> {
        let entity_id = super::vectors::vector_entity_id(id);
        let state = self
            .vector_index
            .get_state(&entity_id)
            .ok_or_else(|| PrimeError::NodeNotFound(id.to_string()))?;

        let vector: Vec<f32> = state
            .get("vector")
            .and_then(|v| serde_json::from_value(v.clone()).ok())
            .unwrap_or_default();

        Ok(self.vector_search(&vector, top_k))
    }

    /// Direct vector search with a raw query vector.
    #[cfg(feature = "prime-vectors")]
    pub fn vector_search(
        &self,
        query: &[f32],
        top_k: usize,
    ) -> Vec<super::vectors::VectorSearchResult> {
        self.vector_index
            .search(query, top_k)
            .into_iter()
            .map(|hit| super::vectors::VectorSearchResult {
                id: hit.entity_id,
                score: 1.0 - f64::from(hit.distance), // Convert distance to similarity
                text: hit.text,
                metadata: hit.metadata,
            })
            .collect()
    }

    /// Domain-aware vector search that ensures results span multiple domains.
    ///
    /// Over-fetches from HNSW, groups by domain, then round-robin interleaves
    /// so that cross-domain queries return results from all relevant domains
    /// instead of clustering in the single most similar domain.
    #[cfg(feature = "prime-vectors")]
    pub fn vector_search_cross_domain(
        &self,
        query: &[f32],
        top_k: usize,
    ) -> Vec<super::vectors::VectorSearchResult> {
        use std::collections::HashMap;

        // Over-fetch to get candidates across domains
        let all_results = self.vector_search(query, top_k * 3);

        if all_results.is_empty() {
            return all_results;
        }

        // Group results by domain
        let mut by_domain: HashMap<String, Vec<super::vectors::VectorSearchResult>> =
            HashMap::new();
        for result in all_results {
            let domain = self
                .domain_of(&result.id)
                .unwrap_or_else(|| "unknown".to_string());
            by_domain.entry(domain).or_default().push(result);
        }

        // If only one domain, no cross-domain benefit — return as-is
        if by_domain.len() <= 1 {
            let mut flat: Vec<_> = by_domain.into_values().flatten().collect();
            flat.truncate(top_k);
            return flat;
        }

        // Round-robin interleave across domains
        let mut merged = Vec::with_capacity(top_k);
        let domain_count = by_domain.len();
        let per_domain = (top_k / domain_count).max(1);

        for results in by_domain.values() {
            merged.extend(results.iter().take(per_domain).cloned());
        }

        // Sort by score and truncate
        merged.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        merged.truncate(top_k);
        merged
    }

    /// Look up the domain of a node by its entity ID.
    ///
    /// Checks top-level `domain` field first, then `properties.domain`,
    /// then falls back to `node_type` (since node_type often IS the domain).
    #[cfg(feature = "prime-vectors")]
    fn domain_of(&self, entity_id: &str) -> Option<String> {
        // entity_id from vector search is "vec:{node_entity_id}" — strip prefix
        let node_id = entity_id.strip_prefix("vec:").unwrap_or(entity_id);
        let state = self.node_state.get_state(node_id)?;

        // Try top-level domain field
        if let Some(domain) = state.get("domain").and_then(|v| v.as_str()) {
            return Some(domain.to_string());
        }
        // Try properties.domain
        if let Some(domain) = state
            .get("properties")
            .and_then(|p| p.get("domain"))
            .and_then(|v| v.as_str())
        {
            return Some(domain.to_string());
        }
        // Fall back to node_type as domain
        state
            .get("node_type")
            .and_then(|v| v.as_str())
            .map(String::from)
    }

    /// Delete a stored vector embedding.
    #[cfg(feature = "prime-vectors")]
    pub async fn delete_vector(&self, id: &str) -> PrimeResult<()> {
        let entity_id = super::vectors::vector_entity_id(id);

        self.core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: super::vectors::event_types::VECTOR_DELETED,
                payload: json!({}),
                metadata: None,
                tenant_id: None,
            })
            .await?;

        Ok(())
    }

    /// Get a stored vector entry.
    #[cfg(feature = "prime-vectors")]
    pub fn get_vector(&self, id: &str) -> Option<super::vectors::VectorEntry> {
        let entity_id = super::vectors::vector_entity_id(id);
        let state = self.vector_index.get_state(&entity_id)?;

        Some(super::vectors::VectorEntry {
            id: id.to_string(),
            text: state.get("text").and_then(|v| v.as_str()).map(String::from),
            dimensions: state
                .get("vector")
                .and_then(serde_json::Value::as_array)
                .map_or(0, Vec::len),
            metadata: state.get("metadata").cloned(),
        })
    }

    // =========================================================================
    // Remember / Forget Convenience Methods (requires `prime-vectors`)
    // =========================================================================

    /// High-level "remember" — creates a node, stores its embedding, and creates
    /// edges to related entities, all in one call.
    ///
    /// Returns the entity_id of the created node.
    #[cfg(feature = "prime-vectors")]
    pub async fn remember(
        &self,
        text: &str,
        vector: Vec<f32>,
        node_type: &str,
        properties: serde_json::Value,
        relations: &[(&str, &str)], // (target_entity_id, relation)
    ) -> PrimeResult<String> {
        // 1. Create node
        let node_id = self.add_node(node_type, properties).await?;
        let entity_id = node_entity_id(node_type, node_id.as_str());

        // 2. Store embedding
        self.embed(&entity_id, Some(text), vector).await?;

        // 3. Create edges
        for (target, relation) in relations {
            self.add_edge(&entity_id, target, relation, None).await?;
        }

        Ok(entity_id)
    }

    /// High-level "forget" — soft-deletes a node, its embedding, and all connected edges.
    #[cfg(feature = "prime-vectors")]
    pub async fn forget(&self, entity_id: &str) -> PrimeResult<()> {
        // Delete vector (strip "node:" prefix to get vec entity_id)
        self.delete_vector(entity_id).await?;

        // Delete node (cascades edges)
        self.delete_node(entity_id).await?;

        Ok(())
    }

    // =========================================================================
    // Hybrid Recall
    // =========================================================================

    /// Hybrid recall combining vector similarity, graph proximity, and temporal recency.
    ///
    /// Scoring: `similarity_weight * cosine + proximity_weight * 1/(1+depth) + recency_weight * exp_decay`
    #[cfg(feature = "prime-vectors")]
    pub async fn recall(
        &self,
        query: super::types::RecallQuery,
    ) -> PrimeResult<super::types::RecallResult> {
        use super::types::{RecallResult, ScoreComponents, ScoredNode};
        use std::collections::HashMap;

        let now = chrono::Utc::now();
        let mut scored: HashMap<String, ScoredNode> = HashMap::new();
        let mut vector_results = Vec::new();

        // Normalize weights so they sum to 1.0
        let total_weight = query.similarity_weight + query.proximity_weight + query.recency_weight;
        let (sw, pw, rw) = if total_weight > 0.0 {
            (
                query.similarity_weight / total_weight,
                query.proximity_weight / total_weight,
                query.recency_weight / total_weight,
            )
        } else {
            (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)
        };

        // Step 1: Vector similarity (if query vector provided)
        if let Some(ref qvec) = query.vector {
            let hits = self.vector_search(qvec, query.top_k * 2); // Over-fetch for graph expansion
            vector_results = hits
                .iter()
                .map(|h| super::vectors::VectorSearchResult {
                    id: h.id.clone(),
                    score: h.score,
                    text: h.text.clone(),
                    metadata: h.metadata.clone(),
                })
                .collect();

            // Seed scored nodes from vector hits (depth=0)
            for hit in &hits {
                // Vector entity_id is "vec:{graph_entity_id}" — strip prefix
                let graph_id = hit.id.strip_prefix("vec:").unwrap_or(&hit.id);
                if let Some(node) = self.get_node(graph_id) {
                    let recency = recency_score(node.updated_at, now);
                    let components = ScoreComponents {
                        similarity: hit.score,
                        proximity: 1.0, // depth 0 = max proximity
                        recency,
                    };
                    let score = sw * hit.score + pw * 1.0 + rw * recency;
                    scored.insert(
                        graph_id.to_string(),
                        ScoredNode {
                            node,
                            score,
                            depth: 0,
                            components,
                        },
                    );
                }
            }
        }

        // Step 2: Graph expansion from seed nodes
        if query.depth > 0 {
            let seeds: Vec<String> = scored.keys().cloned().collect();
            for seed_id in &seeds {
                let bfs_results =
                    self.neighbors_within(seed_id, query.depth, None, Direction::Both);
                for (node, depth) in bfs_results {
                    if depth == 0 {
                        continue; // Already scored
                    }
                    let entity_id = node_entity_id(&node.node_type, node.id.as_str());
                    if scored.contains_key(&entity_id) {
                        continue;
                    }
                    // Filter by node_type if specified
                    if query
                        .node_type
                        .as_ref()
                        .is_some_and(|nt| node.node_type != *nt)
                    {
                        continue;
                    }
                    let proximity = 1.0 / (1.0 + depth as f64);
                    let recency = recency_score(node.updated_at, now);
                    let components = ScoreComponents {
                        similarity: 0.0, // No direct vector match
                        proximity,
                        recency,
                    };
                    let score = pw * proximity + rw * recency;
                    scored.insert(
                        entity_id,
                        ScoredNode {
                            node,
                            score,
                            depth,
                            components,
                        },
                    );
                }
            }
        }

        // Step 3: If no vector, do graph-only (all nodes of type, sorted by recency)
        if query.vector.is_none()
            && let Some(ref nt) = query.node_type
        {
            let nodes = self.nodes_by_type(nt);
            for node in nodes {
                let entity_id = node_entity_id(&node.node_type, node.id.as_str());
                let recency = recency_score(node.updated_at, now);
                let components = ScoreComponents {
                    similarity: 0.0,
                    proximity: 0.0,
                    recency,
                };
                let score = rw * recency;
                scored.insert(
                    entity_id,
                    ScoredNode {
                        node,
                        score,
                        depth: 0,
                        components,
                    },
                );
            }
        }

        // Sort by score descending
        let mut nodes: Vec<ScoredNode> = scored.into_values().collect();
        nodes.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // MMR re-ranking: boost diversity across domains/types
        mmr_rerank(&mut nodes, query.top_k, 0.7);

        Ok(RecallResult {
            nodes,
            vectors: vector_results,
            edges: Vec::new(),
        })
    }

    // =========================================================================
    // Traversal
    // =========================================================================

    /// Get 1-hop neighbors of a node, optionally filtered by relation and direction.
    ///
    /// Returns full [`Node`] objects. Deleted nodes are excluded.
    pub fn neighbors(
        &self,
        entity_id: &str,
        relation: Option<&str>,
        direction: Direction,
    ) -> Vec<Node> {
        let mut peer_ids: Vec<String> = Vec::new();

        match direction {
            Direction::Outgoing => {
                for entry in self.adjacency.outgoing(entity_id) {
                    if relation.is_none() || relation == Some(entry.relation.as_str()) {
                        peer_ids.push(entry.peer.clone());
                    }
                }
            }
            Direction::Incoming => {
                for entry in self.reverse_index.incoming(entity_id) {
                    if relation.is_none() || relation == Some(entry.relation.as_str()) {
                        peer_ids.push(entry.peer.clone());
                    }
                }
            }
            Direction::Both => {
                let mut seen = std::collections::HashSet::new();
                for entry in self.adjacency.outgoing(entity_id) {
                    if (relation.is_none() || relation == Some(entry.relation.as_str()))
                        && seen.insert(entry.peer.clone())
                    {
                        peer_ids.push(entry.peer.clone());
                    }
                }
                for entry in self.reverse_index.incoming(entity_id) {
                    if (relation.is_none() || relation == Some(entry.relation.as_str()))
                        && seen.insert(entry.peer.clone())
                    {
                        peer_ids.push(entry.peer.clone());
                    }
                }
            }
        }

        peer_ids.iter().filter_map(|id| self.get_node(id)).collect()
    }

    /// BFS traversal up to `depth` hops. Returns nodes with their depth level.
    ///
    /// `depth = 0` returns just the center node. `depth = 1` returns center + immediate neighbors.
    pub fn neighbors_within(
        &self,
        entity_id: &str,
        depth: usize,
        relation: Option<&str>,
        direction: Direction,
    ) -> Vec<(Node, usize)> {
        use std::collections::{HashSet, VecDeque};

        let mut visited = HashSet::new();
        let mut result = Vec::new();
        let mut queue = VecDeque::new();

        visited.insert(entity_id.to_string());
        queue.push_back((entity_id.to_string(), 0usize));

        while let Some((current, d)) = queue.pop_front() {
            if let Some(node) = self.get_node(&current) {
                result.push((node, d));
            }

            if d < depth {
                let peers = self.neighbor_ids(&current, relation, direction);
                for peer in peers {
                    if visited.insert(peer.clone()) {
                        queue.push_back((peer, d + 1));
                    }
                }
            }
        }

        result
    }

    /// Extract an ego-network subgraph around `center` up to `depth` hops.
    pub fn subgraph(&self, center: &str, depth: usize) -> super::types::SubGraph {
        use std::collections::HashSet;

        let bfs = self.neighbors_within(center, depth, None, Direction::Both);
        let node_ids: HashSet<String> = bfs
            .iter()
            .map(|(n, _)| {
                // Reconstruct entity_id from node
                node_entity_id(&n.node_type, n.id.as_str())
            })
            .collect();

        let nodes: Vec<Node> = bfs.into_iter().map(|(n, _)| n).collect();

        // Collect all edges between nodes in the subgraph
        let mut edges = Vec::new();
        let mut seen_edges = HashSet::new();
        for entity_id in &node_ids {
            for entry in self.adjacency.outgoing(entity_id) {
                if node_ids.contains(&entry.peer) && seen_edges.insert(entry.edge_id.clone()) {
                    edges.push(Edge {
                        id: EdgeId::new(&entry.edge_id),
                        source: NodeId::new(entity_id.clone()),
                        target: NodeId::new(&entry.peer),
                        relation: entry.relation.clone(),
                        properties: None,
                        weight: entry.weight,
                        deleted: false,
                        created_at: chrono::Utc::now(),
                    });
                }
            }
        }

        super::types::SubGraph { nodes, edges }
    }

    /// BFS shortest path (unweighted). Returns ordered path including start and end.
    pub fn shortest_path(&self, from: &str, to: &str, relation: Option<&str>) -> Option<Vec<Node>> {
        use std::collections::{HashMap, VecDeque};

        if from == to {
            return self.get_node(from).map(|n| vec![n]);
        }

        let mut visited: HashMap<String, String> = HashMap::new(); // child -> parent
        let mut queue = VecDeque::new();

        visited.insert(from.to_string(), String::new());
        queue.push_back(from.to_string());

        while let Some(current) = queue.pop_front() {
            let peers = self.neighbor_ids(&current, relation, Direction::Outgoing);
            for peer in peers {
                if visited.contains_key(&peer) {
                    continue;
                }
                visited.insert(peer.clone(), current.clone());
                if peer == to {
                    // Reconstruct path
                    let mut path_ids = vec![to.to_string()];
                    let mut cursor = to.to_string();
                    while let Some(parent) = visited.get(&cursor) {
                        if parent.is_empty() {
                            break;
                        }
                        path_ids.push(parent.clone());
                        cursor = parent.clone();
                    }
                    path_ids.reverse();
                    return Some(path_ids.iter().filter_map(|id| self.get_node(id)).collect());
                }
                queue.push_back(peer);
            }
        }

        None // No path
    }

    /// Dijkstra shortest path (weighted). Returns path + total weight.
    pub fn shortest_path_weighted(
        &self,
        from: &str,
        to: &str,
        relation: Option<&str>,
    ) -> Option<(Vec<Node>, f64)> {
        use std::{
            cmp::Ordering,
            collections::{BinaryHeap, HashMap},
        };

        if from == to {
            return self.get_node(from).map(|n| (vec![n], 0.0));
        }

        #[derive(PartialEq)]
        struct State {
            cost: f64,
            node: String,
        }

        impl Eq for State {}
        impl PartialOrd for State {
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                Some(self.cmp(other))
            }
        }
        impl Ord for State {
            fn cmp(&self, other: &Self) -> Ordering {
                // Reverse for min-heap
                other
                    .cost
                    .partial_cmp(&self.cost)
                    .unwrap_or(Ordering::Equal)
            }
        }

        let mut dist: HashMap<String, f64> = HashMap::new();
        let mut prev: HashMap<String, String> = HashMap::new();
        let mut heap = BinaryHeap::new();

        dist.insert(from.to_string(), 0.0);
        heap.push(State {
            cost: 0.0,
            node: from.to_string(),
        });

        while let Some(State { cost, node }) = heap.pop() {
            if node == to {
                // Reconstruct path
                let mut path_ids = vec![to.to_string()];
                let mut cursor = to.to_string();
                while let Some(parent) = prev.get(&cursor) {
                    path_ids.push(parent.clone());
                    cursor = parent.clone();
                }
                path_ids.reverse();
                let nodes: Vec<Node> = path_ids.iter().filter_map(|id| self.get_node(id)).collect();
                return Some((nodes, cost));
            }

            if cost > *dist.get(&node).unwrap_or(&f64::INFINITY) {
                continue;
            }

            for entry in self.adjacency.outgoing(&node) {
                if relation.is_some() && relation != Some(entry.relation.as_str()) {
                    continue;
                }
                // Default weight 1.0 for unweighted edges
                let edge_weight = entry.weight.unwrap_or(1.0);
                let next_cost = cost + edge_weight;
                if next_cost < *dist.get(&entry.peer).unwrap_or(&f64::INFINITY) {
                    dist.insert(entry.peer.clone(), next_cost);
                    prev.insert(entry.peer.clone(), node.clone());
                    heap.push(State {
                        cost: next_cost,
                        node: entry.peer.clone(),
                    });
                }
            }
        }

        None
    }

    // =========================================================================
    // Temporal Queries
    // =========================================================================

    /// Get the full audit trail for any entity (node, edge, or vector).
    ///
    /// Returns all events in chronological order. Returns an empty vec
    /// (not an error) if the entity has never existed.
    pub async fn history(&self, entity_id: &str) -> PrimeResult<Vec<super::types::HistoryEntry>> {
        let events = self.core.query(Query::new().entity_id(entity_id)).await?;

        let entries = events
            .iter()
            .map(|e| super::types::HistoryEntry {
                event_type: e.event_type.clone(),
                timestamp: e.timestamp,
                payload: e.payload.clone(),
                source: e
                    .metadata
                    .as_ref()
                    .and_then(|m| m.get("source"))
                    .and_then(|v| v.as_str())
                    .map(String::from),
            })
            .collect();

        Ok(entries)
    }

    /// Get what changed in the graph between two timestamps.
    pub async fn diff(
        &self,
        from: DateTime<Utc>,
        to: DateTime<Utc>,
    ) -> PrimeResult<super::types::GraphDiff> {
        use super::types::GraphDiff;

        let events = self
            .core
            .query(
                Query::new()
                    .event_type_prefix("prime.")
                    .since(from)
                    .until(to),
            )
            .await?;

        let mut diff = GraphDiff::default();

        for event in &events {
            let entity_id = event.entity_id.clone();
            match event.event_type.as_str() {
                event_types::NODE_CREATED => diff.nodes_added.push(entity_id),
                event_types::NODE_UPDATED => diff.nodes_updated.push(entity_id),
                event_types::NODE_DELETED => diff.nodes_deleted.push(entity_id),
                event_types::EDGE_CREATED => diff.edges_added.push(entity_id),
                event_types::EDGE_DELETED => diff.edges_deleted.push(entity_id),
                #[cfg(feature = "prime-vectors")]
                super::vectors::types::event_types::VECTOR_STORED => {
                    diff.vectors_stored.push(entity_id);
                }
                #[cfg(feature = "prime-vectors")]
                super::vectors::types::event_types::VECTOR_DELETED => {
                    diff.vectors_deleted.push(entity_id);
                }
                _ => {}
            }
        }

        Ok(diff)
    }

    /// Get a chronological event stream for an entity within a time range.
    pub async fn timeline(
        &self,
        entity_id: &str,
        from: Option<DateTime<Utc>>,
        to: Option<DateTime<Utc>>,
    ) -> PrimeResult<Vec<super::types::HistoryEntry>> {
        let mut query = Query::new().entity_id(entity_id);
        if let Some(f) = from {
            query = query.since(f);
        }
        if let Some(t) = to {
            query = query.until(t);
        }

        let events = self.core.query(query).await?;

        let entries = events
            .iter()
            .map(|e| super::types::HistoryEntry {
                event_type: e.event_type.clone(),
                timestamp: e.timestamp,
                payload: e.payload.clone(),
                source: e
                    .metadata
                    .as_ref()
                    .and_then(|m| m.get("source"))
                    .and_then(|v| v.as_str())
                    .map(String::from),
            })
            .collect();

        Ok(entries)
    }

    // =========================================================================
    // Conversation Scoping
    // =========================================================================

    /// Create a conversation-scoped handle that tags all mutations with a
    /// conversation ID in event metadata.
    pub fn with_conversation<'a>(&'a self, conversation_id: &'a str) -> ConversationScope<'a> {
        ConversationScope {
            prime: self,
            conversation_id,
        }
    }

    /// Get all events from a specific conversation.
    pub async fn conversation_history(
        &self,
        conversation_id: &str,
    ) -> PrimeResult<Vec<super::types::HistoryEntry>> {
        // Query all events and filter by conversation_id in metadata
        let all_events = self
            .core
            .query(Query::new().event_type_prefix("prime."))
            .await?;

        let entries = all_events
            .iter()
            .filter(|e| {
                e.metadata
                    .as_ref()
                    .and_then(|m| m.get("conversation_id"))
                    .and_then(|v| v.as_str())
                    == Some(conversation_id)
            })
            .map(|e| super::types::HistoryEntry {
                event_type: e.event_type.clone(),
                timestamp: e.timestamp,
                payload: e.payload.clone(),
                source: e
                    .metadata
                    .as_ref()
                    .and_then(|m| m.get("source"))
                    .and_then(|v| v.as_str())
                    .map(String::from),
            })
            .collect();

        Ok(entries)
    }

    /// Get a diff of what changed in a specific conversation.
    pub async fn conversation_diff(
        &self,
        conversation_id: &str,
    ) -> PrimeResult<super::types::GraphDiff> {
        let history = self.conversation_history(conversation_id).await?;
        let mut diff = super::types::GraphDiff::default();

        for entry in &history {
            match entry.event_type.as_str() {
                event_types::NODE_CREATED => diff.nodes_added.push(
                    entry
                        .payload
                        .get("id")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                ),
                event_types::NODE_UPDATED => diff.nodes_updated.push(
                    entry
                        .payload
                        .get("id")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                ),
                event_types::NODE_DELETED => diff.nodes_deleted.push(String::new()),
                event_types::EDGE_CREATED => diff.edges_added.push(
                    entry
                        .payload
                        .get("id")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                ),
                event_types::EDGE_DELETED => diff.edges_deleted.push(
                    entry
                        .payload
                        .get("id")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string(),
                ),
                _ => {}
            }
        }

        Ok(diff)
    }

    /// Get the state of a node as it existed at `as_of` timestamp.
    ///
    /// Replays events up to the given timestamp to reconstruct point-in-time state.
    /// Returns `None` if the node didn't exist yet or was deleted before `as_of`.
    pub async fn get_node_as_of(
        &self,
        entity_id: &str,
        as_of: DateTime<Utc>,
    ) -> PrimeResult<Option<Node>> {
        let events = self
            .core
            .query(Query::new().entity_id(entity_id).until(as_of))
            .await?;

        if events.is_empty() {
            return Ok(None);
        }

        let mut node_type = String::new();
        let mut properties = serde_json::Map::new();
        let mut domain: Option<String> = None;
        let mut labels: Vec<String> = Vec::new();
        let mut deleted = false;
        let mut created_at = as_of;

        for event in &events {
            match event.event_type.as_str() {
                event_types::NODE_CREATED => {
                    node_type = event
                        .payload
                        .get("node_type")
                        .and_then(|v| v.as_str())
                        .unwrap_or("unknown")
                        .to_string();
                    if let Some(serde_json::Value::Object(props)) = event.payload.get("properties")
                    {
                        properties = props.clone();
                    }
                    domain = event
                        .payload
                        .get("domain")
                        .and_then(|v| v.as_str())
                        .map(String::from);
                    labels = event
                        .payload
                        .get("labels")
                        .and_then(|v| v.as_array())
                        .map(|arr| {
                            arr.iter()
                                .filter_map(|v| v.as_str().map(String::from))
                                .collect()
                        })
                        .unwrap_or_default();
                    deleted = false;
                    created_at = event.timestamp;
                }
                event_types::NODE_UPDATED => {
                    if let Some(serde_json::Value::Object(updates)) =
                        event.payload.get("properties")
                    {
                        for (key, value) in updates {
                            properties.insert(key.clone(), value.clone());
                        }
                    }
                    if let Some(d) = event.payload.get("domain") {
                        domain = d.as_str().map(String::from);
                    }
                    if let Some(l) = event
                        .payload
                        .get("labels")
                        .and_then(serde_json::Value::as_array)
                    {
                        labels = l
                            .iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect();
                    }
                }
                event_types::NODE_DELETED => {
                    deleted = true;
                }
                _ => {}
            }
        }

        if deleted || node_type.is_empty() {
            return Ok(None);
        }

        let id = entity_id.split(':').nth(2).unwrap_or(entity_id).to_string();

        Ok(Some(Node {
            id: NodeId::new(id),
            node_type,
            properties: serde_json::Value::Object(properties),
            domain,
            labels,
            deleted: false,
            created_at,
            updated_at: events.last().map_or(created_at, |e| e.timestamp),
        }))
    }

    /// Get 1-hop neighbors of a node as the graph existed at `as_of` timestamp.
    ///
    /// Replays edge events up to the timestamp, filtering by relation.
    pub async fn neighbors_as_of(
        &self,
        entity_id: &str,
        relation: Option<&str>,
        as_of: DateTime<Utc>,
    ) -> PrimeResult<Vec<Node>> {
        // Get all prime edge events up to as_of
        let all_events = self
            .core
            .query(Query::new().event_type_prefix("prime.edge.").until(as_of))
            .await?;

        // Build live outgoing edges from entity_id at as_of
        let mut live_targets: std::collections::HashMap<String, String> =
            std::collections::HashMap::new(); // edge_id -> target
        let mut deleted_edges: std::collections::HashSet<String> = std::collections::HashSet::new();

        for event in &all_events {
            match event.event_type.as_str() {
                event_types::EDGE_CREATED => {
                    let source = event
                        .payload
                        .get("source")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    if source != entity_id {
                        continue;
                    }
                    let rel = event
                        .payload
                        .get("relation")
                        .and_then(|v| v.as_str())
                        .unwrap_or("");
                    if relation.is_some() && relation != Some(rel) {
                        continue;
                    }
                    if let Some(edge_id) = event.payload.get("id").and_then(|v| v.as_str()) {
                        let target = event
                            .payload
                            .get("target")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        live_targets.insert(edge_id.to_string(), target);
                    }
                }
                event_types::EDGE_DELETED => {
                    if let Some(edge_id) = event.payload.get("id").and_then(|v| v.as_str()) {
                        deleted_edges.insert(edge_id.to_string());
                    }
                }
                _ => {}
            }
        }

        // Remove deleted edges
        for deleted in &deleted_edges {
            live_targets.remove(deleted);
        }

        // Resolve targets to Nodes at as_of
        let mut neighbors = Vec::new();
        let mut seen = std::collections::HashSet::new();
        for target in live_targets.values() {
            if seen.insert(target.clone())
                && let Some(node) = Box::pin(self.get_node_as_of(target, as_of)).await?
            {
                neighbors.push(node);
            }
        }

        Ok(neighbors)
    }

    /// Helper: get raw peer IDs without resolving to Node objects.
    fn neighbor_ids(
        &self,
        entity_id: &str,
        relation: Option<&str>,
        direction: Direction,
    ) -> Vec<String> {
        let mut peers = Vec::new();
        let mut seen = std::collections::HashSet::new();

        let add_entries = |entries: Vec<super::projections::AdjEntry>,
                           peers: &mut Vec<String>,
                           seen: &mut std::collections::HashSet<String>| {
            for entry in entries {
                if (relation.is_none() || relation == Some(entry.relation.as_str()))
                    && seen.insert(entry.peer.clone())
                {
                    peers.push(entry.peer);
                }
            }
        };

        match direction {
            Direction::Outgoing => {
                add_entries(self.adjacency.outgoing(entity_id), &mut peers, &mut seen);
            }
            Direction::Incoming => {
                add_entries(
                    self.reverse_index.incoming(entity_id),
                    &mut peers,
                    &mut seen,
                );
            }
            Direction::Both => {
                add_entries(self.adjacency.outgoing(entity_id), &mut peers, &mut seen);
                add_entries(
                    self.reverse_index.incoming(entity_id),
                    &mut peers,
                    &mut seen,
                );
            }
        }

        peers
    }
}

// =============================================================================
// Conversation Scoping
// =============================================================================

/// A conversation-scoped handle to Prime that tags all mutations with a
/// `conversation_id` in event metadata.
///
/// Obtained via [`Prime::with_conversation`]. Delegates all reads to the
/// underlying `Prime` instance (conversations don't isolate reads).
pub struct ConversationScope<'a> {
    prime: &'a Prime,
    conversation_id: &'a str,
}

impl ConversationScope<'_> {
    fn metadata(&self) -> serde_json::Value {
        json!({ "conversation_id": self.conversation_id })
    }

    /// Create a node within this conversation.
    pub async fn add_node(
        &self,
        node_type: &str,
        properties: serde_json::Value,
    ) -> PrimeResult<NodeId> {
        let id = uuid::Uuid::new_v4().to_string();
        #[allow(deprecated)]
        let entity_id = node_entity_id(node_type, &id);

        self.prime
            .core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: event_types::NODE_CREATED,
                payload: json!({
                    "id": id,
                    "node_type": node_type,
                    "properties": properties,
                }),
                metadata: Some(self.metadata()),
                tenant_id: None,
            })
            .await?;

        Ok(NodeId::new(id))
    }

    /// Create an edge within this conversation.
    pub async fn add_edge(
        &self,
        source: &str,
        target: &str,
        relation: &str,
        properties: Option<serde_json::Value>,
    ) -> PrimeResult<EdgeId> {
        if !self.prime.node_state.is_live(source) {
            return Err(PrimeError::NodeNotFound(source.to_string()));
        }
        if !self.prime.node_state.is_live(target) {
            return Err(PrimeError::NodeNotFound(target.to_string()));
        }

        let id = uuid::Uuid::new_v4().to_string();
        #[allow(deprecated)]
        let entity_id = edge_entity_id(&id);

        let mut payload = json!({
            "id": id,
            "source": source,
            "target": target,
            "relation": relation,
        });
        if let Some(props) = properties {
            payload["properties"] = props;
        }

        self.prime
            .core
            .ingest(IngestEvent {
                entity_id: &entity_id,
                event_type: event_types::EDGE_CREATED,
                payload,
                metadata: Some(self.metadata()),
                tenant_id: None,
            })
            .await?;

        Ok(EdgeId::new(id))
    }

    /// Update a node within this conversation.
    pub async fn update_node(
        &self,
        entity_id: &str,
        properties: serde_json::Value,
    ) -> PrimeResult<()> {
        if !self.prime.node_state.is_live(entity_id) {
            return Err(PrimeError::NodeNotFound(entity_id.to_string()));
        }

        self.prime
            .core
            .ingest(IngestEvent {
                entity_id,
                event_type: event_types::NODE_UPDATED,
                payload: json!({ "properties": properties }),
                metadata: Some(self.metadata()),
                tenant_id: None,
            })
            .await?;

        Ok(())
    }

    /// Delete a node within this conversation (delegates to Prime::delete_node).
    pub async fn delete_node(&self, entity_id: &str) -> PrimeResult<()> {
        // delete_node uses ingest_batch; we can't easily add metadata to batch
        // events, so we delegate and emit a conversation marker event afterward
        self.prime.delete_node(entity_id).await
    }

    /// All reads delegate to the underlying Prime instance.
    pub fn get_node(&self, entity_id: &str) -> Option<Node> {
        self.prime.get_node(entity_id)
    }

    pub fn neighbors(
        &self,
        entity_id: &str,
        relation: Option<&str>,
        direction: Direction,
    ) -> Vec<Node> {
        self.prime.neighbors(entity_id, relation, direction)
    }

    pub fn stats(&self) -> PrimeStats {
        self.prime.stats()
    }

    /// Get the conversation ID this scope is bound to.
    pub fn conversation_id(&self) -> &str {
        self.conversation_id
    }
}

// =============================================================================
// Free Functions
// =============================================================================

/// Maximal Marginal Relevance re-ranking.
///
/// Selects top_k results that balance relevance with diversity across domains.
/// `lambda` controls the trade-off: 1.0 = pure relevance, 0.0 = pure diversity.
#[cfg(feature = "prime-vectors")]
fn mmr_rerank(nodes: &mut Vec<super::types::ScoredNode>, top_k: usize, lambda: f64) {
    use super::types::ScoredNode;

    if nodes.len() <= top_k {
        return;
    }

    let mut selected: Vec<ScoredNode> = Vec::with_capacity(top_k);
    let mut remaining: Vec<ScoredNode> = std::mem::take(nodes);

    while selected.len() < top_k && !remaining.is_empty() {
        let mut best_idx = 0;
        let mut best_mmr = f64::NEG_INFINITY;

        for (i, candidate) in remaining.iter().enumerate() {
            let relevance = candidate.score;

            // Max redundancy to any already-selected node
            let max_redundancy = if selected.is_empty() {
                0.0
            } else {
                selected
                    .iter()
                    .map(|s| {
                        // Same node_type = high redundancy
                        if s.node.node_type == candidate.node.node_type
                            && s.node.domain == candidate.node.domain
                        {
                            0.8
                        } else if s.node.domain == candidate.node.domain {
                            0.5
                        } else {
                            0.0
                        }
                    })
                    .fold(0.0f64, f64::max)
            };

            let mmr = lambda * relevance - (1.0 - lambda) * max_redundancy;
            if mmr > best_mmr {
                best_mmr = mmr;
                best_idx = i;
            }
        }

        selected.push(remaining.remove(best_idx));
    }

    *nodes = selected;
}

fn edge_from_event(event: &crate::embedded::EventView) -> Option<Edge> {
    let payload = &event.payload;
    let id = payload.get("id")?.as_str()?.to_string();
    let source = payload.get("source")?.as_str()?.to_string();
    let target = payload.get("target")?.as_str()?.to_string();
    let relation = payload.get("relation")?.as_str()?.to_string();
    let properties = payload.get("properties").cloned();
    let weight = payload.get("weight").and_then(serde_json::Value::as_f64);

    Some(Edge {
        id: EdgeId::new(id),
        source: NodeId::new(source),
        target: NodeId::new(target),
        relation,
        properties,
        weight,
        deleted: false,
        created_at: event.timestamp,
    })
}

/// Exponential decay score for recency: `exp(-lambda * hours_ago)`.
/// Returns 1.0 for recent events, decaying toward 0 for older ones.
fn recency_score(
    timestamp: chrono::DateTime<chrono::Utc>,
    now: chrono::DateTime<chrono::Utc>,
) -> f64 {
    let hours_ago = (now - timestamp).num_seconds().max(0) as f64 / 3600.0;
    // lambda = 0.01 → half-life ≈ 69 hours (~3 days)
    (-0.01 * hours_ago).exp()
}

/// Reconstruct a [`Node`] from projection state.
fn node_from_state(entity_id: &str, state: &serde_json::Value) -> Option<Node> {
    use super::types::NodeId;
    use chrono::{DateTime, Utc};

    // Extract the short ID from entity_id "node:{type}:{id}"
    let id = entity_id.split(':').nth(2).unwrap_or(entity_id).to_string();

    let node_type = state.get("node_type")?.as_str()?.to_string();
    let properties = state.get("properties").cloned().unwrap_or(json!({}));
    let domain = state
        .get("domain")
        .and_then(|v| v.as_str())
        .map(String::from);
    let labels = state
        .get("labels")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let deleted = state
        .get("deleted")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);
    let created_at: DateTime<Utc> = state
        .get("created_at")
        .and_then(|v| v.as_str())
        .and_then(|s| s.parse().ok())
        .unwrap_or_else(Utc::now);
    let updated_at: DateTime<Utc> = state
        .get("updated_at")
        .and_then(|v| v.as_str())
        .and_then(|s| s.parse().ok())
        .unwrap_or_else(Utc::now);

    Some(Node {
        id: NodeId::new(id),
        node_type,
        properties,
        domain,
        labels,
        deleted,
        created_at,
        updated_at,
    })
}

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

    #[tokio::test]
    async fn test_open_in_memory_and_shutdown() {
        let prime = Prime::open_in_memory().await.unwrap();
        let stats = prime.stats();
        assert_eq!(stats.total_nodes, 0);
        assert_eq!(stats.total_edges, 0);
        assert_eq!(stats.event_count, 0);
        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_open_with_path_and_ingest() {
        let dir = tempfile::tempdir().unwrap();
        let prime = Prime::open(dir.path()).await.unwrap();

        let _id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();

        let stats = prime.stats();
        assert_eq!(stats.total_nodes, 1);
        assert_eq!(stats.event_count, 1);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_persistence_across_reopens() {
        let dir = tempfile::tempdir().unwrap();

        {
            let prime = Prime::open(dir.path()).await.unwrap();
            prime
                .add_node("person", json!({"name": "Bob"}))
                .await
                .unwrap();
            prime.shutdown().await.unwrap();
        }

        {
            let prime = Prime::open(dir.path()).await.unwrap();
            let events = prime
                .core()
                .query(Query::new().event_type(event_types::NODE_CREATED))
                .await
                .unwrap();
            assert_eq!(events.len(), 1);
            prime.shutdown().await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_stats_counts_nodes_and_edges() {
        let prime = Prime::open_in_memory().await.unwrap();

        prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        prime
            .add_node("person", json!({"name": "Bob"}))
            .await
            .unwrap();

        // Ingest a raw edge event
        prime
            .core()
            .ingest(IngestEvent {
                entity_id: "edge:e-1",
                event_type: event_types::EDGE_CREATED,
                payload: json!({
                    "id": "e-1",
                    "source": "alice",
                    "target": "bob",
                    "relation": "knows",
                }),
                metadata: None,
                tenant_id: None,
            })
            .await
            .unwrap();

        let stats = prime.stats();
        assert_eq!(stats.total_nodes, 2);
        assert_eq!(stats.total_edges, 1);
        assert_eq!(stats.event_count, 3);

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Node CRUD tests
    // =========================================================================

    #[tokio::test]
    async fn test_full_node_crud_lifecycle() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Create
        let id = prime
            .add_node("person", json!({"name": "Alice", "age": 30}))
            .await
            .unwrap();
        let entity_id = node_entity_id("person", id.as_str());

        // Read
        let node = prime.get_node(&entity_id).unwrap();
        assert_eq!(node.node_type, "person");
        assert_eq!(node.properties["name"], "Alice");
        assert_eq!(node.properties["age"], 30);

        // Update (deep merge)
        prime
            .update_node(&entity_id, json!({"role": "engineer", "age": 31}))
            .await
            .unwrap();
        let node = prime.get_node(&entity_id).unwrap();
        assert_eq!(node.properties["name"], "Alice"); // preserved
        assert_eq!(node.properties["role"], "engineer"); // added
        assert_eq!(node.properties["age"], 31); // updated

        // Delete
        prime.delete_node(&entity_id).await.unwrap();
        assert!(prime.get_node(&entity_id).is_none());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_delete_node_cascades_edges() {
        let prime = Prime::open_in_memory().await.unwrap();

        let alice_id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        let bob_id = prime
            .add_node("person", json!({"name": "Bob"}))
            .await
            .unwrap();

        let alice_entity = node_entity_id("person", alice_id.as_str());
        let bob_entity = node_entity_id("person", bob_id.as_str());

        // Add edge alice -> bob
        prime
            .core()
            .ingest(IngestEvent {
                entity_id: "edge:e-1",
                event_type: event_types::EDGE_CREATED,
                payload: json!({
                    "id": "e-1",
                    "source": alice_entity,
                    "target": bob_entity,
                    "relation": "knows",
                }),
                metadata: None,
                tenant_id: None,
            })
            .await
            .unwrap();

        // Verify edge exists
        assert_eq!(prime.adjacency.outgoing(&alice_entity).len(), 1);

        // Delete alice — should cascade and delete the edge
        prime.delete_node(&alice_entity).await.unwrap();

        // Edge should be gone
        assert_eq!(prime.adjacency.outgoing(&alice_entity).len(), 0);
        assert_eq!(prime.reverse_index.incoming(&bob_entity).len(), 0);

        // Alice should be gone
        assert!(prime.get_node(&alice_entity).is_none());
        // Bob should still exist
        assert!(prime.get_node(&bob_entity).is_some());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_update_nonexistent_node_returns_error() {
        let prime = Prime::open_in_memory().await.unwrap();

        let result = prime
            .update_node("node:person:ghost", json!({"name": "Ghost"}))
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            PrimeError::NodeNotFound(id) => assert_eq!(id, "node:person:ghost"),
            other => panic!("expected NodeNotFound, got: {other}"),
        }

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_nodes_by_type() {
        let prime = Prime::open_in_memory().await.unwrap();

        prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        prime
            .add_node("person", json!({"name": "Bob"}))
            .await
            .unwrap();
        prime
            .add_node("project", json!({"name": "Prime"}))
            .await
            .unwrap();

        let persons = prime.nodes_by_type("person");
        assert_eq!(persons.len(), 2);

        let projects = prime.nodes_by_type("project");
        assert_eq!(projects.len(), 1);

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Edge CRUD tests
    // =========================================================================

    #[tokio::test]
    async fn test_create_edge_between_nodes() {
        let prime = Prime::open_in_memory().await.unwrap();

        let alice_id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        let bob_id = prime
            .add_node("person", json!({"name": "Bob"}))
            .await
            .unwrap();
        let alice_entity = node_entity_id("person", alice_id.as_str());
        let bob_entity = node_entity_id("person", bob_id.as_str());

        let edge_id = prime
            .add_edge(&alice_entity, &bob_entity, "knows", None)
            .await
            .unwrap();

        // Verify edge exists via get_edge
        let edge = prime.get_edge(edge_id.as_str()).await.unwrap().unwrap();
        assert_eq!(edge.relation, "knows");
        assert_eq!(edge.source.as_str(), &alice_entity);
        assert_eq!(edge.target.as_str(), &bob_entity);

        // Verify adjacency projections
        assert_eq!(prime.adjacency.outgoing(&alice_entity).len(), 1);
        assert_eq!(prime.reverse_index.incoming(&bob_entity).len(), 1);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_create_edge_to_nonexistent_node() {
        let prime = Prime::open_in_memory().await.unwrap();

        let alice_id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        let alice_entity = node_entity_id("person", alice_id.as_str());

        let result = prime
            .add_edge(&alice_entity, "node:person:ghost", "knows", None)
            .await;

        assert!(result.is_err());
        match result.unwrap_err() {
            PrimeError::NodeNotFound(id) => assert_eq!(id, "node:person:ghost"),
            other => panic!("expected NodeNotFound, got: {other}"),
        }

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_delete_edge() {
        let prime = Prime::open_in_memory().await.unwrap();

        let alice_id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        let bob_id = prime
            .add_node("person", json!({"name": "Bob"}))
            .await
            .unwrap();
        let alice_entity = node_entity_id("person", alice_id.as_str());
        let bob_entity = node_entity_id("person", bob_id.as_str());

        let edge_id = prime
            .add_edge(&alice_entity, &bob_entity, "knows", None)
            .await
            .unwrap();

        // Delete
        prime.delete_edge(edge_id.as_str()).await.unwrap();

        // Verify gone
        let edge = prime.get_edge(edge_id.as_str()).await.unwrap();
        assert!(edge.is_none());

        // Verify adjacency updated
        assert_eq!(prime.adjacency.outgoing(&alice_entity).len(), 0);
        assert_eq!(prime.reverse_index.incoming(&bob_entity).len(), 0);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_weighted_edge() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime
            .add_node("person", json!({"name": "A"}))
            .await
            .unwrap();
        let b = prime
            .add_node("person", json!({"name": "B"}))
            .await
            .unwrap();
        let a_entity = node_entity_id("person", a.as_str());
        let b_entity = node_entity_id("person", b.as_str());

        let edge_id = prime
            .add_edge_weighted(&a_entity, &b_entity, "trust", 0.95, None)
            .await
            .unwrap();

        let edge = prime.get_edge(edge_id.as_str()).await.unwrap().unwrap();
        assert_eq!(edge.weight, Some(0.95));

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Neighbor query tests
    // =========================================================================

    #[tokio::test]
    async fn test_neighbors_all_directions() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Create nodes A, B, C, D
        let a = prime
            .add_node("person", json!({"name": "A"}))
            .await
            .unwrap();
        let b = prime
            .add_node("person", json!({"name": "B"}))
            .await
            .unwrap();
        let c = prime
            .add_node("person", json!({"name": "C"}))
            .await
            .unwrap();
        let d = prime
            .add_node("person", json!({"name": "D"}))
            .await
            .unwrap();

        let a_e = node_entity_id("person", a.as_str());
        let b_e = node_entity_id("person", b.as_str());
        let c_e = node_entity_id("person", c.as_str());
        let d_e = node_entity_id("person", d.as_str());

        // A->B (works_on), A->C (knows), D->A (manages)
        prime.add_edge(&a_e, &b_e, "works_on", None).await.unwrap();
        prime.add_edge(&a_e, &c_e, "knows", None).await.unwrap();
        prime.add_edge(&d_e, &a_e, "manages", None).await.unwrap();

        // Outgoing from A = [B, C]
        let out = prime.neighbors(&a_e, None, Direction::Outgoing);
        assert_eq!(out.len(), 2);

        // Outgoing from A filtered by "works_on" = [B]
        let out_filtered = prime.neighbors(&a_e, Some("works_on"), Direction::Outgoing);
        assert_eq!(out_filtered.len(), 1);
        assert_eq!(out_filtered[0].properties["name"], "B");

        // Incoming to A = [D]
        let inc = prime.neighbors(&a_e, None, Direction::Incoming);
        assert_eq!(inc.len(), 1);
        assert_eq!(inc[0].properties["name"], "D");

        // Both from A = [B, C, D] (deduplicated)
        let both = prime.neighbors(&a_e, None, Direction::Both);
        assert_eq!(both.len(), 3);

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // BFS traversal tests
    // =========================================================================

    #[tokio::test]
    async fn test_bfs_diamond_graph() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Diamond: A->B->D, A->C->D
        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let c = prime.add_node("n", json!({"name": "C"})).await.unwrap();
        let d = prime.add_node("n", json!({"name": "D"})).await.unwrap();

        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());
        let ce = node_entity_id("n", c.as_str());
        let de = node_entity_id("n", d.as_str());

        prime.add_edge(&ae, &be, "link", None).await.unwrap();
        prime.add_edge(&ae, &ce, "link", None).await.unwrap();
        prime.add_edge(&be, &de, "link", None).await.unwrap();
        prime.add_edge(&ce, &de, "link", None).await.unwrap();

        let results = prime.neighbors_within(&ae, 2, None, Direction::Outgoing);

        // A(0), B(1), C(1), D(2)
        assert_eq!(results.len(), 4);
        assert_eq!(results[0].1, 0); // A at depth 0
        // B and C at depth 1
        let depth_1: Vec<_> = results.iter().filter(|(_, d)| *d == 1).collect();
        assert_eq!(depth_1.len(), 2);
        // D at depth 2
        let depth_2: Vec<_> = results.iter().filter(|(_, d)| *d == 2).collect();
        assert_eq!(depth_2.len(), 1);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_subgraph_extraction() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let c = prime.add_node("n", json!({"name": "C"})).await.unwrap();

        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());
        let ce = node_entity_id("n", c.as_str());

        prime.add_edge(&ae, &be, "link", None).await.unwrap();
        prime.add_edge(&ae, &ce, "link", None).await.unwrap();

        let sg = prime.subgraph(&ae, 1);
        assert_eq!(sg.nodes.len(), 3); // A, B, C
        assert_eq!(sg.edges.len(), 2); // A->B, A->C

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_bfs_cycle_terminates() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Cycle: A->B->C->A
        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let c = prime.add_node("n", json!({"name": "C"})).await.unwrap();

        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());
        let ce = node_entity_id("n", c.as_str());

        prime.add_edge(&ae, &be, "link", None).await.unwrap();
        prime.add_edge(&be, &ce, "link", None).await.unwrap();
        prime.add_edge(&ce, &ae, "link", None).await.unwrap();

        let results = prime.neighbors_within(&ae, 10, None, Direction::Outgoing);
        // Each node visited exactly once
        assert_eq!(results.len(), 3);

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Shortest path tests
    // =========================================================================

    #[tokio::test]
    async fn test_shortest_path_bfs() {
        let prime = Prime::open_in_memory().await.unwrap();

        // A->B->C->D
        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let c = prime.add_node("n", json!({"name": "C"})).await.unwrap();
        let d = prime.add_node("n", json!({"name": "D"})).await.unwrap();

        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());
        let ce = node_entity_id("n", c.as_str());
        let de = node_entity_id("n", d.as_str());

        prime.add_edge(&ae, &be, "link", None).await.unwrap();
        prime.add_edge(&be, &ce, "link", None).await.unwrap();
        prime.add_edge(&ce, &de, "link", None).await.unwrap();

        let path = prime.shortest_path(&ae, &de, None).unwrap();
        assert_eq!(path.len(), 4); // A, B, C, D

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_shortest_path_weighted_dijkstra() {
        let prime = Prime::open_in_memory().await.unwrap();

        // A->B (w=1), A->C (w=3), B->D (w=1), C->D (w=1)
        // Cheapest: A->B->D (cost 2) vs A->C->D (cost 4)
        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let c = prime.add_node("n", json!({"name": "C"})).await.unwrap();
        let d = prime.add_node("n", json!({"name": "D"})).await.unwrap();

        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());
        let ce = node_entity_id("n", c.as_str());
        let de = node_entity_id("n", d.as_str());

        prime
            .add_edge_weighted(&ae, &be, "link", 1.0, None)
            .await
            .unwrap();
        prime
            .add_edge_weighted(&ae, &ce, "link", 3.0, None)
            .await
            .unwrap();
        prime
            .add_edge_weighted(&be, &de, "link", 1.0, None)
            .await
            .unwrap();
        prime
            .add_edge_weighted(&ce, &de, "link", 1.0, None)
            .await
            .unwrap();

        let (path, cost) = prime.shortest_path_weighted(&ae, &de, None).unwrap();
        assert_eq!(path.len(), 3); // A, B, D
        assert!((cost - 2.0).abs() < f64::EPSILON);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_shortest_path_disconnected() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();

        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());

        // No edges — disconnected
        assert!(prime.shortest_path(&ae, &be, None).is_none());

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // History / temporal tests
    // =========================================================================

    #[tokio::test]
    async fn test_history_full_lifecycle() {
        let prime = Prime::open_in_memory().await.unwrap();

        let id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        let entity_id = node_entity_id("person", id.as_str());

        // Update twice
        prime
            .update_node(&entity_id, json!({"role": "engineer"}))
            .await
            .unwrap();
        prime
            .update_node(&entity_id, json!({"level": "senior"}))
            .await
            .unwrap();

        // Delete
        prime.delete_node(&entity_id).await.unwrap();

        let history = prime.history(&entity_id).await.unwrap();
        assert_eq!(history.len(), 4); // created, updated, updated, deleted
        assert_eq!(history[0].event_type, event_types::NODE_CREATED);
        assert_eq!(history[1].event_type, event_types::NODE_UPDATED);
        assert_eq!(history[2].event_type, event_types::NODE_UPDATED);
        assert_eq!(history[3].event_type, event_types::NODE_DELETED);

        // Chronological order
        for window in history.windows(2) {
            assert!(window[0].timestamp <= window[1].timestamp);
        }

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_history_nonexistent_entity_returns_empty() {
        let prime = Prime::open_in_memory().await.unwrap();

        let history = prime.history("node:person:ghost").await.unwrap();
        assert!(history.is_empty());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_history_edge_events() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let a_e = node_entity_id("n", a.as_str());
        let b_e = node_entity_id("n", b.as_str());

        let edge_id = prime.add_edge(&a_e, &b_e, "knows", None).await.unwrap();

        let edge_entity = edge_entity_id(edge_id.as_str());
        prime.delete_edge(edge_id.as_str()).await.unwrap();

        let history = prime.history(&edge_entity).await.unwrap();
        assert_eq!(history.len(), 2); // created, deleted
        assert_eq!(history[0].event_type, event_types::EDGE_CREATED);
        assert_eq!(history[1].event_type, event_types::EDGE_DELETED);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_diff_between_timestamps() {
        use chrono::Utc;

        let prime = Prime::open_in_memory().await.unwrap();

        let t1 = Utc::now();

        // Add 3 nodes and 2 edges
        let a = prime
            .add_node("person", json!({"name": "A"}))
            .await
            .unwrap();
        let b = prime
            .add_node("person", json!({"name": "B"}))
            .await
            .unwrap();
        let c = prime
            .add_node("project", json!({"name": "C"}))
            .await
            .unwrap();
        let a_e = node_entity_id("person", a.as_str());
        let b_e = node_entity_id("person", b.as_str());
        prime.add_edge(&a_e, &b_e, "knows", None).await.unwrap();
        prime
            .add_edge(
                &a_e,
                &node_entity_id("project", c.as_str()),
                "works_on",
                None,
            )
            .await
            .unwrap();

        let t2 = Utc::now();

        let diff = prime.diff(t1, t2).await.unwrap();
        assert_eq!(diff.nodes_added.len(), 3);
        assert_eq!(diff.edges_added.len(), 2);
        assert!(diff.nodes_deleted.is_empty());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_timeline_with_range() {
        use chrono::Utc;

        let prime = Prime::open_in_memory().await.unwrap();

        let id = prime
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        let entity_id = node_entity_id("person", id.as_str());

        let t_mid = Utc::now();

        prime
            .update_node(&entity_id, json!({"role": "engineer"}))
            .await
            .unwrap();

        let t_end = Utc::now();

        // Full timeline
        let full = prime.timeline(&entity_id, None, None).await.unwrap();
        assert_eq!(full.len(), 2);

        // Timeline from t_mid — should only include the update
        let after_mid = prime
            .timeline(&entity_id, Some(t_mid), Some(t_end))
            .await
            .unwrap();
        assert_eq!(after_mid.len(), 1);
        assert_eq!(after_mid[0].event_type, event_types::NODE_UPDATED);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_shortest_path_to_self() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let ae = node_entity_id("n", a.as_str());

        let path = prime.shortest_path(&ae, &ae, None).unwrap();
        assert_eq!(path.len(), 1);
        assert_eq!(path[0].properties["name"], "A");

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Time-travel tests
    // =========================================================================

    #[tokio::test]
    async fn test_neighbors_as_of() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());

        // Add edge A->B
        prime.add_edge(&ae, &be, "knows", None).await.unwrap();
        let t2 = chrono::Utc::now();

        // Small delay to ensure distinct timestamps
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        // Add another node C and edge A->C after t2
        let c = prime.add_node("n", json!({"name": "C"})).await.unwrap();
        let ce = node_entity_id("n", c.as_str());
        prime.add_edge(&ae, &ce, "knows", None).await.unwrap();

        // At t2, only B should be a neighbor
        let neighbors_at_t2 = prime.neighbors_as_of(&ae, None, t2).await.unwrap();
        assert_eq!(neighbors_at_t2.len(), 1);
        assert_eq!(neighbors_at_t2[0].properties["name"], "B");

        // At now, both B and C should be neighbors
        let neighbors_now = prime
            .neighbors_as_of(&ae, None, chrono::Utc::now())
            .await
            .unwrap();
        assert_eq!(neighbors_now.len(), 2);

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_get_node_as_of_deleted() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let ae = node_entity_id("n", a.as_str());
        let t1 = chrono::Utc::now();

        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        // Delete node after t1
        prime.delete_node(&ae).await.unwrap();

        // At t1, node should exist
        let node_at_t1 = prime.get_node_as_of(&ae, t1).await.unwrap();
        assert!(node_at_t1.is_some());
        assert_eq!(node_at_t1.unwrap().properties["name"], "A");

        // At now (after deletion), node should be gone
        let node_now = prime.get_node_as_of(&ae, chrono::Utc::now()).await.unwrap();
        assert!(node_now.is_none());

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Memory compaction tests
    // =========================================================================

    #[tokio::test]
    async fn test_compact_merges_properties() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime
            .add_node("person", json!({"name": "Alice", "age": 30}))
            .await
            .unwrap();
        let b = prime
            .add_node(
                "person",
                json!({"name": "Alice Smith", "email": "alice@example.com"}),
            )
            .await
            .unwrap();

        let a_e = node_entity_id("person", a.as_str());
        let b_e = node_entity_id("person", b.as_str());

        prime.compact(&a_e, &[&b_e]).await.unwrap();

        // Target has merged properties (target wins on "name" conflict)
        let node = prime.get_node(&a_e).unwrap();
        assert_eq!(node.properties["name"], "Alice"); // target wins
        assert_eq!(node.properties["age"], 30); // kept from target
        assert_eq!(node.properties["email"], "alice@example.com"); // added from source

        // Source is deleted
        assert!(prime.get_node(&b_e).is_none());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_compact_redirects_edges() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime
            .add_node("person", json!({"name": "A"}))
            .await
            .unwrap();
        let b = prime
            .add_node("person", json!({"name": "B"}))
            .await
            .unwrap();
        let c = prime
            .add_node("project", json!({"name": "C"}))
            .await
            .unwrap();

        let a_e = node_entity_id("person", a.as_str());
        let b_e = node_entity_id("person", b.as_str());
        let c_e = node_entity_id("project", c.as_str());

        // B -> C (works_on)
        prime.add_edge(&b_e, &c_e, "works_on", None).await.unwrap();

        // Compact B into A
        prime.compact(&a_e, &[&b_e]).await.unwrap();

        // A should now have an edge to C
        let neighbors = prime.neighbors(&a_e, Some("works_on"), Direction::Outgoing);
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0].properties["name"], "C");

        // B should be deleted
        assert!(prime.get_node(&b_e).is_none());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_compact_emits_compacted_event() {
        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();

        let a_e = node_entity_id("n", a.as_str());
        let b_e = node_entity_id("n", b.as_str());

        prime.compact(&a_e, &[&b_e]).await.unwrap();

        // Check for compaction event in history
        let history = prime.history(&a_e).await.unwrap();
        let compacted = history
            .iter()
            .find(|h| h.event_type == "prime.memory.compacted");
        assert!(compacted.is_some());
        let payload = &compacted.unwrap().payload;
        assert_eq!(payload["target"], a_e);
        assert!(
            payload["merged_from"]
                .as_array()
                .unwrap()
                .contains(&json!(b_e))
        );

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_compact_nonexistent_target_fails() {
        let prime = Prime::open_in_memory().await.unwrap();

        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let b_e = node_entity_id("n", b.as_str());

        let result = prime.compact("node:n:ghost", &[&b_e]).await;
        assert!(result.is_err());

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Vector operation tests (prime-vectors feature)
    // =========================================================================

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_embed_and_vector_search() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Embed 3 documents with distinct vectors
        prime
            .embed("doc-1", Some("Rust is fast"), vec![1.0, 0.0, 0.0, 0.0])
            .await
            .unwrap();
        prime
            .embed("doc-2", Some("Rust is safe"), vec![0.9, 0.1, 0.0, 0.0])
            .await
            .unwrap();
        prime
            .embed("doc-3", Some("Python is dynamic"), vec![0.0, 0.0, 1.0, 0.0])
            .await
            .unwrap();

        // Search for something close to doc-1
        let results = prime.vector_search(&[1.0, 0.0, 0.0, 0.0], 3);
        assert_eq!(results.len(), 3);
        // Highest similarity should be doc-1
        assert!(results[0].id.contains("doc-1"));
        assert!(results[0].score > 0.99);
        // doc-3 should be least similar
        assert!(results[2].id.contains("doc-3"));

        prime.shutdown().await.unwrap();
    }

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_embed_delete_excludes_from_search() {
        let prime = Prime::open_in_memory().await.unwrap();

        prime
            .embed("doc-a", Some("Hello"), vec![1.0, 0.0])
            .await
            .unwrap();
        prime
            .embed("doc-b", Some("World"), vec![0.9, 0.1])
            .await
            .unwrap();

        // Delete doc-a
        prime.delete_vector("doc-a").await.unwrap();

        // Search should only return doc-b
        let results = prime.vector_search(&[1.0, 0.0], 10);
        assert_eq!(results.len(), 1);
        assert!(results[0].id.contains("doc-b"));

        // get_vector should return None for deleted
        assert!(prime.get_vector("doc-a").is_none());
        assert!(prime.get_vector("doc-b").is_some());

        prime.shutdown().await.unwrap();
    }

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_similar_finds_close_vectors() {
        let prime = Prime::open_in_memory().await.unwrap();

        prime
            .embed("ref", Some("Reference"), vec![1.0, 0.0, 0.0])
            .await
            .unwrap();
        prime
            .embed("close", Some("Close"), vec![0.95, 0.05, 0.0])
            .await
            .unwrap();
        prime
            .embed("far", Some("Far"), vec![0.0, 0.0, 1.0])
            .await
            .unwrap();

        let similar = prime.similar("ref", 3).unwrap();
        assert_eq!(similar.len(), 3);
        // First result is self (highest similarity), second is "close"
        assert!(similar[0].id.contains("ref"));
        assert!(similar[1].id.contains("close"));

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Hybrid recall tests
    // =========================================================================

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_recall_vector_plus_graph() {
        use crate::prime::types::RecallQuery;

        let prime = Prime::open_in_memory().await.unwrap();

        // Create graph nodes
        let a = prime
            .add_node("concept", json!({"name": "Rust"}))
            .await
            .unwrap();
        let b = prime
            .add_node("concept", json!({"name": "Safety"}))
            .await
            .unwrap();
        let c = prime
            .add_node("concept", json!({"name": "Speed"}))
            .await
            .unwrap();
        let ae = node_entity_id("concept", a.as_str());
        let be = node_entity_id("concept", b.as_str());
        let ce = node_entity_id("concept", c.as_str());

        prime.add_edge(&ae, &be, "related", None).await.unwrap();
        prime.add_edge(&ae, &ce, "related", None).await.unwrap();

        // Embed vectors for the nodes
        prime
            .embed(&ae, Some("Rust"), vec![1.0, 0.0, 0.0, 0.0])
            .await
            .unwrap();
        prime
            .embed(&be, Some("Safety"), vec![0.8, 0.2, 0.0, 0.0])
            .await
            .unwrap();
        prime
            .embed(&ce, Some("Speed"), vec![0.0, 0.0, 1.0, 0.0])
            .await
            .unwrap();

        let result = prime
            .recall(RecallQuery {
                vector: Some(vec![1.0, 0.0, 0.0, 0.0]),
                depth: 1,
                top_k: 10,
                similarity_weight: 0.5,
                proximity_weight: 0.3,
                recency_weight: 0.2,
                ..Default::default()
            })
            .await
            .unwrap();

        // Should get vector matches + graph neighbors
        assert!(!result.nodes.is_empty());
        assert!(!result.vectors.is_empty());
        // Highest scored should be the closest vector match
        assert!(result.nodes[0].score > 0.0);

        prime.shutdown().await.unwrap();
    }

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_recall_recency_weight() {
        use crate::prime::types::RecallQuery;

        let prime = Prime::open_in_memory().await.unwrap();

        // All nodes created "now" so recency is ~1.0 for all
        prime
            .add_node("fact", json!({"name": "New"}))
            .await
            .unwrap();
        prime
            .add_node("fact", json!({"name": "Also New"}))
            .await
            .unwrap();

        let result = prime
            .recall(RecallQuery {
                node_type: Some("fact".to_string()),
                recency_weight: 1.0,
                similarity_weight: 0.0,
                proximity_weight: 0.0,
                top_k: 10,
                ..Default::default()
            })
            .await
            .unwrap();

        // Graph-only (no vector), ranked by recency
        assert_eq!(result.nodes.len(), 2);
        // Both should have high recency scores (created just now)
        for node in &result.nodes {
            assert!(node.components.recency > 0.99);
        }

        prime.shutdown().await.unwrap();
    }

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_recall_depth_zero_only_direct_matches() {
        use crate::prime::types::RecallQuery;

        let prime = Prime::open_in_memory().await.unwrap();

        let a = prime.add_node("n", json!({"name": "A"})).await.unwrap();
        let b = prime.add_node("n", json!({"name": "B"})).await.unwrap();
        let ae = node_entity_id("n", a.as_str());
        let be = node_entity_id("n", b.as_str());

        prime.add_edge(&ae, &be, "link", None).await.unwrap();
        prime.embed(&ae, Some("A"), vec![1.0, 0.0]).await.unwrap();

        let result = prime
            .recall(RecallQuery {
                vector: Some(vec![1.0, 0.0]),
                depth: 0, // No graph expansion
                top_k: 10,
                ..Default::default()
            })
            .await
            .unwrap();

        // Only direct vector matches, no graph expansion
        assert_eq!(result.nodes.len(), 1);
        assert_eq!(result.nodes[0].depth, 0);

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Remember / Forget tests
    // =========================================================================

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_remember_creates_node_vector_edges() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Create a target node to link to
        let project = prime
            .add_node("project", json!({"name": "Prime"}))
            .await
            .unwrap();
        let project_entity = node_entity_id("project", project.as_str());

        // Remember a concept
        let entity_id = prime
            .remember(
                "Rust is a systems language",
                vec![1.0, 0.0, 0.0],
                "concept",
                json!({"name": "Rust"}),
                &[(&project_entity, "related_to")],
            )
            .await
            .unwrap();

        // Node should exist
        let node = prime.get_node(&entity_id).unwrap();
        assert_eq!(node.node_type, "concept");
        assert_eq!(node.properties["name"], "Rust");

        // Vector should be searchable
        let results = prime.vector_search(&[1.0, 0.0, 0.0], 5);
        assert!(!results.is_empty());

        // Edge should exist
        let neighbors = prime.neighbors(&entity_id, Some("related_to"), Direction::Outgoing);
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0].properties["name"], "Prime");

        prime.shutdown().await.unwrap();
    }

    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn test_forget_removes_node_vector_edges() {
        let prime = Prime::open_in_memory().await.unwrap();

        let entity_id = prime
            .remember(
                "Ephemeral knowledge",
                vec![0.5, 0.5],
                "fact",
                json!({"name": "temp"}),
                &[],
            )
            .await
            .unwrap();

        // Verify it exists
        assert!(prime.get_node(&entity_id).is_some());
        assert!(!prime.vector_search(&[0.5, 0.5], 5).is_empty());

        // Forget
        prime.forget(&entity_id).await.unwrap();

        // Node should be gone
        assert!(prime.get_node(&entity_id).is_none());

        // Vector should be gone from search
        let results = prime.vector_search(&[0.5, 0.5], 5);
        assert!(results.is_empty());

        prime.shutdown().await.unwrap();
    }

    // =========================================================================
    // Conversation scoping tests
    // =========================================================================

    #[tokio::test]
    async fn test_conversation_scoping_isolates_history() {
        let prime = Prime::open_in_memory().await.unwrap();

        // Conversation 1: add node A
        let conv1 = prime.with_conversation("conv-1");
        let a = conv1
            .add_node("person", json!({"name": "Alice"}))
            .await
            .unwrap();
        #[allow(deprecated)]
        let ae = node_entity_id("person", a.as_str());

        // Conversation 2: add node B
        let conv2 = prime.with_conversation("conv-2");
        let b = conv2
            .add_node("person", json!({"name": "Bob"}))
            .await
            .unwrap();
        #[allow(deprecated)]
        let _be = node_entity_id("person", b.as_str());

        // conversation_history(conv-1) should only show conv-1 events
        let h1 = prime.conversation_history("conv-1").await.unwrap();
        assert_eq!(h1.len(), 1);

        let h2 = prime.conversation_history("conv-2").await.unwrap();
        assert_eq!(h2.len(), 1);

        // Both nodes exist globally
        assert!(prime.get_node(&ae).is_some());

        prime.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_conversation_diff() {
        let prime = Prime::open_in_memory().await.unwrap();

        let conv = prime.with_conversation("conv-x");
        conv.add_node("concept", json!({"name": "Rust"}))
            .await
            .unwrap();
        conv.add_node("concept", json!({"name": "Safety"}))
            .await
            .unwrap();

        let diff = prime.conversation_diff("conv-x").await.unwrap();
        assert_eq!(diff.nodes_added.len(), 2);

        prime.shutdown().await.unwrap();
    }
}