khive-runtime 0.2.1

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
//! High-level operations composing storage capabilities into user-facing verbs.

use std::collections::HashMap;
use std::str::FromStr;

use serde::Serialize;
use uuid::Uuid;

use khive_score::{rrf_score, DeterministicScore};
use khive_storage::note::Note;
use khive_storage::types::{
    DeleteMode, Direction, EdgeSortField, GraphPath, LinkId, NeighborHit, NeighborQuery, Page,
    PageRequest, SortOrder, SqlRow, SqlStatement, TextDocument, TextFilter, TextQueryMode,
    TextSearchRequest, TraversalRequest,
};
use khive_storage::{Edge, EdgeRelation, Entity, EntityFilter, Event, EventFilter};
use khive_types::{EdgeEndpointRule, EndpointKind, EventKind, SubstrateKind};

use crate::error::{RuntimeError, RuntimeResult};
use crate::runtime::{KhiveRuntime, NamespaceToken};

// Test-only failure injection for `create_note_inner`.
//
// A test sets `LINK_FAIL_AFTER` to N > 0 before calling `create_note`.  The
// Nth `link` call inside the loop returns `RuntimeError::Internal("injected
// link failure")` instead of calling the real implementation.  The counter is
// reset to 0 after each call regardless of whether it triggered, so tests are
// isolated from one another.
#[cfg(test)]
std::thread_local! {
    static LINK_FAIL_AFTER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// A note search result with UUID, salience-weighted RRF score, and display text.
#[derive(Clone, Debug)]
pub struct NoteSearchHit {
    pub note_id: Uuid,
    pub score: DeterministicScore,
    pub title: Option<String>,
    pub snippet: Option<String>,
}

fn text_preview(text: &str, max_chars: usize) -> Option<String> {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.chars().take(max_chars).collect())
    }
}

/// ADR-002: symmetric relations (`competes_with`, `composed_with`) are stored
/// with a canonical source (lower UUID wins), so a directed `Out` or `In` query
/// may miss results. When the relations filter is non-empty and contains **only**
/// symmetric relations, override direction to `Both` so callers always see all
/// edges for these relations regardless of storage canonicalization.
fn normalize_symmetric_direction(
    direction: Direction,
    relations: Option<&[EdgeRelation]>,
) -> Direction {
    let Some(rels) = relations else {
        return direction;
    };
    if rels.is_empty() {
        return direction;
    }
    let all_symmetric = rels
        .iter()
        .all(|r| matches!(r, EdgeRelation::CompetesWith | EdgeRelation::ComposedWith));
    if all_symmetric {
        Direction::Both
    } else {
        direction
    }
}

fn note_title(note: &Note) -> Option<String> {
    note.name
        .clone()
        .filter(|s| !s.trim().is_empty())
        .or_else(|| text_preview(&note.content, 80))
}

fn note_snippet(note: &Note) -> Option<String> {
    text_preview(&note.content, 200)
}

/// Result of resolving a UUID to its substrate kind.
#[derive(Clone, Debug)]
pub enum Resolved {
    Entity(Entity),
    Note(Note),
    Event(Event),
}

/// Map a resolved endpoint to its `(substrate, kind)` pair, or `None` if
/// the substrate is not a valid edge endpoint (events, edges).
fn resolved_pair(r: Option<&Resolved>) -> Option<(&'static str, &str)> {
    match r? {
        Resolved::Entity(e) => Some(("entity", e.kind.as_str())),
        Resolved::Note(n) => Some(("note", n.kind.as_str())),
        Resolved::Event(_) => None,
    }
}

/// `true` if `spec` matches the given substrate + kind pair.
fn endpoint_matches(spec: &EndpointKind, substrate: &str, kind: &str) -> bool {
    match spec {
        EndpointKind::EntityOfKind(k) => substrate == "entity" && *k == kind,
        EndpointKind::NoteOfKind(k) => substrate == "note" && *k == kind,
    }
}

/// `true` if any pack-declared edge endpoint rule allows the
/// `(source, relation, target)` triple. ADR-031: rules are additive only.
fn pack_rule_allows(
    rules: &[EdgeEndpointRule],
    relation: EdgeRelation,
    src: Option<&Resolved>,
    tgt: Option<&Resolved>,
) -> bool {
    let Some((src_sub, src_kind)) = resolved_pair(src) else {
        return false;
    };
    let Some((tgt_sub, tgt_kind)) = resolved_pair(tgt) else {
        return false;
    };
    rules.iter().any(|r| {
        r.relation == relation
            && endpoint_matches(&r.source, src_sub, src_kind)
            && endpoint_matches(&r.target, tgt_sub, tgt_kind)
    })
}

/// ADR-002 base endpoint allowlist for entity→entity relations.
///
/// Returns `true` if `(src_kind, relation, tgt_kind)` is an explicitly listed
/// triple in the ADR-002 base contract. `"*"` as `src_kind` means "any entity
/// kind" (used for `instance_of` whose source is unrestricted).
///
/// Pack rules (via `EDGE_RULES`) are additive — they cannot remove rows here.
fn base_entity_rule_allows(src_kind: &str, relation: EdgeRelation, tgt_kind: &str) -> bool {
    const RULES: &[(&str, EdgeRelation, &str)] = &[
        // Structure
        ("concept", EdgeRelation::Contains, "concept"),
        ("project", EdgeRelation::Contains, "project"),
        ("project", EdgeRelation::Contains, "artifact"),
        ("org", EdgeRelation::Contains, "project"),
        ("org", EdgeRelation::Contains, "service"),
        ("concept", EdgeRelation::PartOf, "concept"),
        ("project", EdgeRelation::PartOf, "project"),
        ("project", EdgeRelation::PartOf, "org"),
        ("*", EdgeRelation::InstanceOf, "concept"),
        ("service", EdgeRelation::InstanceOf, "project"),
        // Derivation
        ("concept", EdgeRelation::Extends, "concept"),
        ("concept", EdgeRelation::VariantOf, "concept"),
        ("artifact", EdgeRelation::VariantOf, "artifact"),
        ("concept", EdgeRelation::IntroducedBy, "document"),
        ("concept", EdgeRelation::IntroducedBy, "person"),
        ("artifact", EdgeRelation::IntroducedBy, "document"),
        // Provenance
        ("artifact", EdgeRelation::DerivedFrom, "dataset"),
        ("artifact", EdgeRelation::DerivedFrom, "document"),
        ("artifact", EdgeRelation::DerivedFrom, "project"),
        ("artifact", EdgeRelation::DerivedFrom, "artifact"),
        // Temporal
        ("document", EdgeRelation::Precedes, "document"),
        ("dataset", EdgeRelation::Precedes, "dataset"),
        ("artifact", EdgeRelation::Precedes, "artifact"),
        ("service", EdgeRelation::Precedes, "service"),
        ("project", EdgeRelation::Precedes, "project"),
        // Dependency
        ("project", EdgeRelation::DependsOn, "project"),
        ("service", EdgeRelation::DependsOn, "project"),
        ("service", EdgeRelation::DependsOn, "service"),
        ("service", EdgeRelation::DependsOn, "artifact"),
        ("service", EdgeRelation::DependsOn, "dataset"),
        ("artifact", EdgeRelation::DependsOn, "project"),
        ("artifact", EdgeRelation::DependsOn, "service"),
        ("concept", EdgeRelation::Enables, "concept"),
        ("service", EdgeRelation::Enables, "concept"),
        ("dataset", EdgeRelation::Enables, "concept"),
        // Implementation
        ("project", EdgeRelation::Implements, "concept"),
        ("service", EdgeRelation::Implements, "concept"),
        // Lateral
        ("concept", EdgeRelation::CompetesWith, "concept"),
        ("project", EdgeRelation::CompetesWith, "project"),
        ("service", EdgeRelation::CompetesWith, "service"),
        ("concept", EdgeRelation::ComposedWith, "concept"),
        ("project", EdgeRelation::ComposedWith, "project"),
        // Versioning (Supersedes — ADR-002:190-194: Concept/Document/Artifact/Service/Dataset only)
        ("concept", EdgeRelation::Supersedes, "concept"),
        ("document", EdgeRelation::Supersedes, "document"),
        ("artifact", EdgeRelation::Supersedes, "artifact"),
        ("service", EdgeRelation::Supersedes, "service"),
        ("dataset", EdgeRelation::Supersedes, "dataset"),
    ];
    RULES.iter().any(|(src, rel, tgt)| {
        *rel == relation && (*src == "*" || *src == src_kind) && *tgt == tgt_kind
    })
}

/// Canonical endpoint order for symmetric relations (F012).
///
/// For `competes_with` and `composed_with`, normalises direction so that
/// `source_uuid < target_uuid` (lexicographic on the UUID bytes). This
/// collapses A→B and B→A into a single canonical row, preventing duplicates.
fn canonical_edge_endpoints(
    relation: EdgeRelation,
    source_id: Uuid,
    target_id: Uuid,
) -> (Uuid, Uuid) {
    if relation.is_symmetric() && target_id < source_id {
        (target_id, source_id)
    } else {
        (source_id, target_id)
    }
}

/// Infer the default `dependency_kind` from endpoint entity kinds (ADR-002).
fn infer_dependency_kind(src_kind: &str, tgt_kind: &str) -> Option<&'static str> {
    match (src_kind, tgt_kind) {
        ("project", "project") => Some("build"),
        ("service", "service") => Some("runtime"),
        ("service", "dataset") => Some("data"),
        ("service", "artifact") => Some("artifact"),
        ("artifact", "project") | ("artifact", "service") => Some("tooling"),
        _ => None,
    }
}

/// Merge an inferred `dependency_kind` into `depends_on` edge metadata.
///
/// If `metadata` already carries a `dependency_kind` key the existing value is
/// preserved. If the key is absent and the endpoint pair has a known default,
/// the inferred value is added. Returns `metadata` unchanged for all other
/// cases (no matching default, or metadata already has the key).
fn merge_dependency_kind(
    src_kind: &str,
    tgt_kind: &str,
    metadata: Option<serde_json::Value>,
) -> Option<serde_json::Value> {
    if let Some(ref m) = metadata {
        if m.get("dependency_kind").is_some() {
            return metadata;
        }
    }
    let inferred = infer_dependency_kind(src_kind, tgt_kind)?;
    let mut obj = metadata.unwrap_or_else(|| serde_json::json!({}));
    if let Some(o) = obj.as_object_mut() {
        o.insert("dependency_kind".to_string(), serde_json::json!(inferred));
    }
    Some(obj)
}

/// Valid `dependency_kind` values for `depends_on` edges (ADR-002).
const VALID_DEPENDENCY_KINDS: &[&str] = &["build", "runtime", "data", "artifact", "tooling"];

/// Validate governed edge metadata keys (ADR-002 §Edge Metadata).
///
/// Currently enforces:
/// - `dependency_kind` is only valid on `depends_on` edges.
/// - `dependency_kind`, when present, must be one of the five governed values.
fn validate_edge_metadata(
    relation: EdgeRelation,
    metadata: Option<&serde_json::Value>,
) -> RuntimeResult<()> {
    let Some(meta) = metadata else {
        return Ok(());
    };
    if let Some(dk) = meta.get("dependency_kind") {
        if relation != EdgeRelation::DependsOn {
            return Err(RuntimeError::InvalidInput(format!(
                "dependency_kind is only valid on depends_on edges (got {})",
                relation.as_str()
            )));
        }
        let dk_str = dk
            .as_str()
            .ok_or_else(|| RuntimeError::InvalidInput("dependency_kind must be a string".into()))?;
        if !VALID_DEPENDENCY_KINDS.contains(&dk_str) {
            return Err(RuntimeError::InvalidInput(format!(
                "unknown dependency_kind {dk_str:?}; valid: {}",
                VALID_DEPENDENCY_KINDS.join(" | ")
            )));
        }
    }
    Ok(())
}

impl KhiveRuntime {
    // ---- Entity operations ----

    /// Create and persist a new entity.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_entity(
        &self,
        token: &NamespaceToken,
        kind: &str,
        entity_type: Option<&str>,
        name: &str,
        description: Option<&str>,
        properties: Option<serde_json::Value>,
        tags: Vec<String>,
    ) -> RuntimeResult<Entity> {
        let ns = token.namespace().as_str();
        let mut entity = Entity::new(ns, kind, name).with_entity_type(entity_type);
        if let Some(d) = description {
            entity = entity.with_description(d);
        }
        if let Some(p) = properties {
            entity = entity.with_properties(p);
        }
        if !tags.is_empty() {
            entity = entity.with_tags(tags);
        }
        self.entities(token)?.upsert_entity(entity.clone()).await?;

        let body = match &entity.description {
            Some(d) if !d.is_empty() => format!("{} {}", entity.name, d),
            _ => entity.name.clone(),
        };
        self.text(token)?
            .upsert_document(TextDocument {
                subject_id: entity.id,
                kind: SubstrateKind::Entity,
                title: Some(entity.name.clone()),
                body: body.clone(),
                tags: entity.tags.clone(),
                namespace: ns.to_string(),
                metadata: entity.properties.clone(),
                updated_at: chrono::Utc::now(),
            })
            .await?;

        if self.config().embedding_model.is_some() {
            let vector = self.embed(&body).await?;
            self.vectors(token)?
                .insert(
                    entity.id,
                    SubstrateKind::Entity,
                    ns,
                    "entity.body",
                    vec![vector],
                )
                .await?;
        }

        Ok(entity)
    }

    /// Retrieve an entity by ID, enforcing namespace isolation (ADR-007).
    ///
    /// Returns `Err(NotFound)` if the entity does not exist in storage,
    /// or `Err(NamespaceMismatch)` if it exists in a different namespace.
    pub async fn get_entity(&self, token: &NamespaceToken, id: Uuid) -> RuntimeResult<Entity> {
        let entity = self
            .entities(token)?
            .get_entity(id)
            .await?
            .ok_or_else(|| RuntimeError::NotFound("not found in this namespace".into()))?;
        self.ensure_namespace(&entity.namespace, token, id)?;
        Ok(entity)
    }

    /// Enforce that `actual` matches the token's namespace.
    ///
    /// Returns `Err(NamespaceMismatch { id })` when they differ, preserving ADR-007
    /// timing-oracle mitigation (the external message is "not found in this namespace").
    pub(crate) fn ensure_namespace(
        &self,
        actual: &str,
        token: &NamespaceToken,
        id: Uuid,
    ) -> RuntimeResult<()> {
        if actual == token.namespace().as_str() {
            return Ok(());
        }
        Err(RuntimeError::NamespaceMismatch { id })
    }

    /// List entities in a namespace, optionally filtered by kind and entity_type.
    pub async fn list_entities(
        &self,
        token: &NamespaceToken,
        kind: Option<&str>,
        entity_type: Option<&str>,
        limit: u32,
        offset: u32,
    ) -> RuntimeResult<Vec<Entity>> {
        let filter = EntityFilter {
            kinds: match kind {
                Some(k) => vec![k.to_string()],
                None => vec![],
            },
            entity_types: match entity_type {
                Some(t) => vec![t.to_string()],
                None => vec![],
            },
            ..Default::default()
        };
        let page = self
            .entities(token)?
            .query_entities(
                token.namespace().as_str(),
                filter,
                PageRequest {
                    offset: offset.into(),
                    limit,
                },
            )
            .await?;
        Ok(page.items)
    }

    /// List events in the namespace proven by the caller token.
    pub async fn list_events(
        &self,
        token: &NamespaceToken,
        filter: EventFilter,
        page: PageRequest,
    ) -> RuntimeResult<Page<Event>> {
        self.events(token)?
            .query_events(filter, page)
            .await
            .map_err(Into::into)
    }

    // ---- Edge operations ----

    /// Validate that `source_id` and `target_id` are legal endpoints for `relation`.
    ///
    /// Centralises the ADR-002/ADR-019/ADR-024 three-case contract so that both
    /// `link()` and `update_edge()` share identical enforcement:
    ///
    /// - `annotates`: source MUST be a note; target may be any substrate.
    /// - `supersedes`: same-substrate only (note→note or entity→entity).
    /// - All other 11 relations: both endpoints MUST be entities.
    ///
    /// Returns `Ok(())` when valid; otherwise `InvalidInput` or `NotFound` with
    /// the same messages as the previous inline block (byte-identical behaviour).
    async fn validate_edge_relation_endpoints(
        &self,
        token: &NamespaceToken,
        source_id: Uuid,
        target_id: Uuid,
        relation: EdgeRelation,
    ) -> RuntimeResult<()> {
        if relation == EdgeRelation::Annotates {
            // Source must be a note in namespace.
            match self.resolve(token, source_id).await? {
                Some(Resolved::Note(_)) => {}
                Some(_) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "annotates source {source_id} must be a note"
                    )));
                }
                None => {
                    // Existing edge used as annotates source: wrong kind, not absent.
                    if self.get_edge(token, source_id).await?.is_some() {
                        return Err(RuntimeError::InvalidInput(format!(
                            "annotates source {source_id} must be a note"
                        )));
                    }
                    return Err(RuntimeError::NotFound(format!(
                        "link source {source_id} not found in namespace"
                    )));
                }
            }
            // Target may be any substrate (entity, note, event, or edge).
            if !self.substrate_exists_in_ns(token, target_id).await? {
                return Err(RuntimeError::NotFound(format!(
                    "link target {target_id} not found in namespace"
                )));
            }
        } else if relation == EdgeRelation::Supersedes {
            // supersedes: same-substrate only (note→note or entity→entity).
            // Event and edge endpoints are invalid regardless of the other endpoint.
            let src = match self.resolve(token, source_id).await? {
                Some(r) => r,
                None => {
                    if self.get_edge(token, source_id).await?.is_some() {
                        return Err(RuntimeError::InvalidInput(format!(
                            "supersedes source {source_id} must be a note or entity (got edge)"
                        )));
                    }
                    return Err(RuntimeError::NotFound(format!(
                        "link source {source_id} not found in namespace"
                    )));
                }
            };
            let tgt = match self.resolve(token, target_id).await? {
                Some(r) => r,
                None => {
                    if self.get_edge(token, target_id).await?.is_some() {
                        return Err(RuntimeError::InvalidInput(format!(
                            "supersedes target {target_id} must be a note or entity (got edge)"
                        )));
                    }
                    return Err(RuntimeError::NotFound(format!(
                        "link target {target_id} not found in namespace"
                    )));
                }
            };
            match (&src, &tgt) {
                (Resolved::Entity(src_e), Resolved::Entity(tgt_e)) => {
                    if !base_entity_rule_allows(&src_e.kind, EdgeRelation::Supersedes, &tgt_e.kind)
                    {
                        return Err(RuntimeError::InvalidInput(format!(
                            "({}) -[supersedes]-> ({}) is not in the ADR-002 base endpoint \
                             allowlist; supersedes requires same-kind entity endpoints",
                            src_e.kind, tgt_e.kind
                        )));
                    }
                }
                (Resolved::Note(_), Resolved::Note(_)) => {}
                (Resolved::Event(_), _) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "supersedes does not apply to events; source {source_id} is an event"
                    )));
                }
                (_, Resolved::Event(_)) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "supersedes does not apply to events; target {target_id} is an event"
                    )));
                }
                (Resolved::Entity(_), Resolved::Note(_)) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "supersedes endpoints must be the same substrate (note→note or entity→entity); \
                         got source={source_id} (entity) target={target_id} (note)"
                    )));
                }
                (Resolved::Note(_), Resolved::Entity(_)) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "supersedes endpoints must be the same substrate (note→note or entity→entity); \
                         got source={source_id} (note) target={target_id} (entity)"
                    )));
                }
            }
        } else {
            // All 13 base relations: ADR-002 contract is entity→entity with
            // kind-level restrictions (see base allowlist). ADR-031 allows packs
            // to extend the allowlist additively via EDGE_RULES.
            //
            // Strategy: resolve both endpoints once, consult pack rules; on
            // miss, fall through to the original base-rule error messages.
            let src_res = self.resolve(token, source_id).await?;
            let tgt_res = self.resolve(token, target_id).await?;

            if pack_rule_allows(
                &self.pack_edge_rules(),
                relation,
                src_res.as_ref(),
                tgt_res.as_ref(),
            ) {
                return Ok(());
            }

            // Substrate check: both endpoints must be entities.
            let src_kind = match src_res {
                Some(Resolved::Entity(e)) => e.kind,
                Some(_) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "link source {source_id} must be an entity for relation {relation:?} \
                         (ADR-002: only `annotates` crosses substrates)"
                    )));
                }
                None => {
                    if self.get_edge(token, source_id).await?.is_some() {
                        return Err(RuntimeError::InvalidInput(format!(
                            "link source {source_id} must be an entity for relation {relation:?} \
                             (ADR-002: only `annotates` crosses substrates)"
                        )));
                    }
                    return Err(RuntimeError::NotFound(format!(
                        "link source {source_id} not found in namespace"
                    )));
                }
            };
            let tgt_kind = match tgt_res {
                Some(Resolved::Entity(e)) => e.kind,
                Some(_) => {
                    return Err(RuntimeError::InvalidInput(format!(
                        "link target {target_id} must be an entity for relation {relation:?} \
                         (ADR-002: only `annotates` crosses substrates)"
                    )));
                }
                None => {
                    if self.get_edge(token, target_id).await?.is_some() {
                        return Err(RuntimeError::InvalidInput(format!(
                            "link target {target_id} must be an entity for relation {relation:?} \
                             (ADR-002: only `annotates` crosses substrates)"
                        )));
                    }
                    return Err(RuntimeError::NotFound(format!(
                        "link target {target_id} not found in namespace"
                    )));
                }
            };
            if !base_entity_rule_allows(&src_kind, relation, &tgt_kind) {
                return Err(RuntimeError::InvalidInput(format!(
                    "({src_kind}) -[{}]-> ({tgt_kind}) is not in the ADR-002 base endpoint \
                     allowlist; use pack EDGE_RULES to extend the allowlist",
                    relation.as_str()
                )));
            }
        }
        Ok(())
    }

    /// Create a directed edge between two substrates.
    ///
    /// Enforces the ADR-002/ADR-019/ADR-024 three-case relation contract via
    /// `validate_edge_relation_endpoints`. See that method for the full contract.
    ///
    /// For symmetric relations (`competes_with`, `composed_with`) the endpoint
    /// pair is canonicalised to `source_uuid < target_uuid` so that A→B and B→A
    /// deduplicate to one row (F012).
    ///
    /// `metadata` is validated against governed keys (ADR-002 §Edge Metadata);
    /// `dependency_kind` is inferred for `depends_on` edges when absent (F013).
    ///
    /// ADR-009 invariant: `target_backend` is always `None` for locally-routed
    /// edges written through this path. The `validate_edge_relation_endpoints`
    /// call above already ensures both endpoints exist in the local namespace,
    /// so setting `target_backend = None` is the only valid choice (F161).
    ///
    /// A record that exists but belongs to a different namespace is treated as not found
    /// (fail-closed; no cross-namespace existence leak).
    pub async fn link(
        &self,
        token: &NamespaceToken,
        source_id: Uuid,
        target_id: Uuid,
        relation: EdgeRelation,
        weight: f64,
        metadata: Option<serde_json::Value>,
    ) -> RuntimeResult<Edge> {
        self.validate_edge_relation_endpoints(token, source_id, target_id, relation)
            .await?;
        let (source_id, target_id) = canonical_edge_endpoints(relation, source_id, target_id);
        let metadata = if relation == EdgeRelation::DependsOn {
            match (
                self.resolve(token, source_id).await?,
                self.resolve(token, target_id).await?,
            ) {
                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, metadata)
                }
                _ => metadata,
            }
        } else {
            metadata
        };
        validate_edge_metadata(relation, metadata.as_ref())?;
        let now = chrono::Utc::now();
        let ns = token.namespace().as_str();
        let edge = Edge {
            id: LinkId::from(Uuid::new_v4()),
            namespace: ns.to_string(),
            source_id,
            target_id,
            relation,
            weight,
            created_at: now,
            updated_at: now,
            deleted_at: None,
            metadata,
            target_backend: None,
        };
        self.graph(token)?.upsert_edge(edge.clone()).await?;
        Ok(edge)
    }

    /// Returns `true` if `id` resolves to a live substrate record in `namespace`.
    ///
    /// Covers entity, note, event (via `resolve`) and edge (via `get_edge`).
    /// A record that exists in a different namespace returns `false` (fail-closed).
    async fn substrate_exists_in_ns(
        &self,
        token: &NamespaceToken,
        id: Uuid,
    ) -> RuntimeResult<bool> {
        if self.resolve(token, id).await?.is_some() {
            return Ok(true);
        }
        Ok(self.get_edge(token, id).await?.is_some())
    }

    /// Get immediate neighbors of a node, optionally filtered by relation type.
    ///
    /// Pass `relations: Some(vec![EdgeRelation::Annotates])` to retrieve only
    /// annotation edges, enabling cross-substrate navigation as described in ADR-024.
    ///
    /// ADR-002: symmetric relations (`competes_with`, `composed_with`) are stored
    /// with the canonical source as the lower UUID. Direction normalization is
    /// applied in `neighbors_with_query` so both callers see correct results.
    pub async fn neighbors(
        &self,
        token: &NamespaceToken,
        node_id: Uuid,
        direction: Direction,
        limit: Option<u32>,
        relations: Option<Vec<EdgeRelation>>,
    ) -> RuntimeResult<Vec<NeighborHit>> {
        self.neighbors_with_query(
            token,
            node_id,
            NeighborQuery {
                direction,
                relations,
                limit,
                min_weight: None,
            },
        )
        .await
    }

    /// Get neighbors with full query control (includes `min_weight`).
    ///
    /// Applies symmetric-relation direction normalization (ADR-002): if the
    /// relations filter contains only symmetric relations the direction is
    /// overridden to `Both` so edges stored in canonical order are always found.
    pub async fn neighbors_with_query(
        &self,
        token: &NamespaceToken,
        node_id: Uuid,
        mut query: NeighborQuery,
    ) -> RuntimeResult<Vec<NeighborHit>> {
        query.direction =
            normalize_symmetric_direction(query.direction, query.relations.as_deref());
        let mut hits = self.graph(token)?.neighbors(node_id, query).await?;
        self.enrich_neighbor_hits(token, &mut hits).await;
        Ok(hits)
    }

    /// Traverse the graph from a set of root nodes.
    pub async fn traverse(
        &self,
        token: &NamespaceToken,
        request: TraversalRequest,
    ) -> RuntimeResult<Vec<GraphPath>> {
        let mut paths = self.graph(token)?.traverse(request).await?;
        self.enrich_path_nodes(token, &mut paths).await;
        Ok(paths)
    }

    /// Populate `name` and `kind` on each `NeighborHit` from the corresponding
    /// entity record (#162). Best-effort — IDs that don't resolve to an entity
    /// (e.g. note-to-note `annotates` edges) leave the fields `None`.
    ///
    /// Done as a single batched entity fetch instead of an SQL JOIN at the
    /// graph store, so test databases that wire up a graph store without an
    /// entities table still work. Cost: one query per neighbors() call.
    async fn enrich_neighbor_hits(&self, token: &NamespaceToken, hits: &mut [NeighborHit]) {
        if hits.is_empty() {
            return;
        }
        let store = match self.entities(token) {
            Ok(s) => s,
            Err(_) => return, // no entity store configured; leave name/kind as None
        };
        for hit in hits.iter_mut() {
            if let Ok(Some(entity)) = store.get_entity(hit.node_id).await {
                hit.name = Some(entity.name);
                hit.kind = Some(entity.kind);
            }
        }
    }

    /// Populate `name` and `kind` on each `PathNode` from the corresponding
    /// entity record (#162). Same best-effort policy as `enrich_neighbor_hits`.
    async fn enrich_path_nodes(&self, token: &NamespaceToken, paths: &mut [GraphPath]) {
        if paths.is_empty() {
            return;
        }
        let store = match self.entities(token) {
            Ok(s) => s,
            Err(_) => return,
        };
        for path in paths.iter_mut() {
            for node in path.nodes.iter_mut() {
                if let Ok(Some(entity)) = store.get_entity(node.node_id).await {
                    node.name = Some(entity.name);
                    node.kind = Some(entity.kind);
                }
            }
        }
    }

    // ---- Note operations ----

    /// Create and persist a note, optionally with properties and annotation targets.
    ///
    /// After creating the note:
    /// - Always indexes into FTS5 at the `notes_<namespace>` key.
    /// - If an embedding model is configured, indexes into the vector store with
    ///   `SubstrateKind::Note`.
    /// - For each UUID in `annotates`, creates an `EdgeRelation::Annotates` edge from
    ///   the note to that target.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_note(
        &self,
        token: &NamespaceToken,
        kind: &str,
        name: Option<&str>,
        content: &str,
        salience: Option<f64>,
        properties: Option<serde_json::Value>,
        annotates: Vec<Uuid>,
    ) -> RuntimeResult<Note> {
        self.create_note_inner(
            token, kind, name, content, salience, None, properties, annotates,
        )
        .await
    }

    /// Like [`create_note`] but also sets a non-zero decay factor on the note.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_note_with_decay(
        &self,
        token: &NamespaceToken,
        kind: &str,
        name: Option<&str>,
        content: &str,
        salience: Option<f64>,
        decay_factor: f64,
        properties: Option<serde_json::Value>,
        annotates: Vec<Uuid>,
    ) -> RuntimeResult<Note> {
        self.create_note_inner(
            token,
            kind,
            name,
            content,
            salience,
            Some(decay_factor),
            properties,
            annotates,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    async fn create_note_inner(
        &self,
        token: &NamespaceToken,
        kind: &str,
        name: Option<&str>,
        content: &str,
        salience: Option<f64>,
        decay_factor: Option<f64>,
        properties: Option<serde_json::Value>,
        annotates: Vec<Uuid>,
    ) -> RuntimeResult<Note> {
        let ns = token.namespace().as_str();

        // Validate all annotates targets before any write (ADR-024:295 atomicity).
        for &target_id in &annotates {
            if !self.substrate_exists_in_ns(token, target_id).await? {
                return Err(RuntimeError::NotFound(format!(
                    "create_note annotates target {target_id} not found in namespace"
                )));
            }
        }

        let mut note = Note::new(ns, kind, content);
        if let Some(s) = salience {
            note = note.with_salience(s);
        }
        if let Some(df) = decay_factor {
            note = note.with_decay(df);
        }
        if let Some(n) = name {
            note = note.with_name(n);
        }
        if let Some(p) = properties {
            note = note.with_properties(p);
        }
        self.notes(token)?.upsert_note(note.clone()).await?;

        let body = match &note.name {
            Some(n) => format!("{n} {}", note.content),
            None => note.content.clone(),
        };

        self.text_for_notes(token)?
            .upsert_document(TextDocument {
                subject_id: note.id,
                kind: SubstrateKind::Note,
                title: note.name.clone(),
                body,
                tags: vec![],
                namespace: ns.to_string(),
                metadata: note.properties.clone(),
                updated_at: chrono::Utc::now(),
            })
            .await?;

        if self.config().embedding_model.is_some() {
            let vector = self.embed(&note.content).await?;
            self.vectors(token)?
                .insert(
                    note.id,
                    SubstrateKind::Note,
                    ns,
                    "note.content",
                    vec![vector],
                )
                .await?;
        }

        // Create annotates edges, compensating on failure to preserve atomicity.
        //
        // Pre-validation (above) ensures all targets exist, so link failures are
        // unexpected. If one occurs: delete any edges already created, then remove
        // the note, its FTS document, and its vector entry.
        let mut created_edges: Vec<Uuid> = Vec::with_capacity(annotates.len());

        // In test builds, iterate with an index so the failure-injection hook can
        // target a specific call.  In release builds, skip the enumerate overhead.
        #[cfg(test)]
        let annotates_iter: Vec<(usize, Uuid)> = annotates
            .iter()
            .enumerate()
            .map(|(i, &id)| (i, id))
            .collect();
        #[cfg(test)]
        macro_rules! next_target {
            ($pair:expr) => {
                $pair.1
            };
        }
        #[cfg(not(test))]
        let annotates_iter: Vec<Uuid> = annotates.to_vec();
        #[cfg(not(test))]
        macro_rules! next_target {
            ($pair:expr) => {
                $pair
            };
        }

        for pair in annotates_iter {
            let target_id = next_target!(pair);

            // Test-only: inject a failure on the configured call index (1-based).
            #[cfg(test)]
            let injected_err: Option<RuntimeError> = {
                let call_idx = pair.0;
                LINK_FAIL_AFTER.with(|cell| {
                    let n = cell.get();
                    if n > 0 && call_idx + 1 == n {
                        cell.set(0); // reset so subsequent calls are unaffected
                        Some(RuntimeError::Internal("injected link failure".to_string()))
                    } else {
                        None
                    }
                })
            };
            #[cfg(not(test))]
            let injected_err: Option<RuntimeError> = None;

            let link_result = if let Some(e) = injected_err {
                Err(e)
            } else {
                self.link(
                    token,
                    note.id,
                    target_id,
                    EdgeRelation::Annotates,
                    1.0,
                    None,
                )
                .await
            };

            match link_result {
                Ok(edge) => created_edges.push(edge.id.into()),
                Err(e) => {
                    // Best-effort compensation — ignore cleanup errors.
                    for edge_id in created_edges {
                        let _ = self.delete_edge(token, edge_id, true).await;
                    }
                    if let Ok(store) = self.notes(token) {
                        let _ = store.delete_note(note.id, DeleteMode::Hard).await;
                    }
                    if let Ok(fts) = self.text_for_notes(token) {
                        let _ = fts.delete_document(ns, note.id).await;
                    }
                    if self.config().embedding_model.is_some() {
                        if let Ok(vs) = self.vectors(token) {
                            let _ = vs.delete(note.id).await;
                        }
                    }
                    return Err(e);
                }
            }
        }

        Ok(note)
    }

    /// List notes, optionally filtered by kind.
    pub async fn list_notes(
        &self,
        token: &NamespaceToken,
        kind: Option<&str>,
        limit: u32,
        offset: u32,
    ) -> RuntimeResult<Vec<Note>> {
        let page = self
            .notes(token)?
            .query_notes(
                token.namespace().as_str(),
                kind,
                PageRequest {
                    offset: offset.into(),
                    limit,
                },
            )
            .await?;
        Ok(page.items)
    }

    /// Search notes using a hybrid FTS5 + vector pipeline with salience weighting.
    ///
    /// Pipeline (per ADR-024):
    /// 1. FTS5 query against `notes_<namespace>`.
    /// 2. If embedding model is configured: vector search filtered to `kind="note"`.
    /// 3. RRF fusion (k=60).
    /// 4. Salience-weighted rerank: `score *= (0.5 + 0.5 * note.salience)`.
    /// 5. Filter soft-deleted notes (`deleted_at IS NOT NULL`).
    /// 6. Truncate to `limit`.
    pub async fn search_notes(
        &self,
        token: &NamespaceToken,
        query_text: &str,
        query_vector: Option<Vec<f32>>,
        limit: u32,
        note_kind: Option<&str>,
        include_superseded: bool,
    ) -> RuntimeResult<Vec<NoteSearchHit>> {
        const RRF_K: usize = 60;
        let candidates = limit.saturating_mul(4).max(limit);
        let ns = token.namespace().as_str().to_owned();

        // FTS5 over the notes index.
        let text_hits = self
            .text_for_notes(token)?
            .search(TextSearchRequest {
                query: query_text.to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(TextFilter {
                    namespaces: vec![ns.clone()],
                    ..TextFilter::default()
                }),
                top_k: candidates,
                snippet_chars: 200,
            })
            .await?;

        // Vector search filtered to notes.
        let vector_hits = if query_vector.is_some() || self.config().embedding_model.is_some() {
            self.vector_search(
                token,
                query_vector,
                Some(query_text),
                candidates,
                Some(SubstrateKind::Note),
            )
            .await?
        } else {
            vec![]
        };

        // RRF fusion.
        #[derive(Default)]
        struct Bucket {
            score: DeterministicScore,
            title: Option<String>,
            snippet: Option<String>,
        }

        let mut buckets: HashMap<Uuid, Bucket> = HashMap::new();
        for (i, hit) in text_hits.into_iter().enumerate() {
            let rank = i + 1;
            let entry = buckets.entry(hit.subject_id).or_default();
            entry.score = entry.score + rrf_score(rank, RRF_K);
            if entry.title.is_none() {
                entry.title = hit.title;
            }
            if entry.snippet.is_none() {
                entry.snippet = hit.snippet;
            }
        }
        for (i, hit) in vector_hits.into_iter().enumerate() {
            let rank = i + 1;
            let entry = buckets.entry(hit.subject_id).or_default();
            entry.score = entry.score + rrf_score(rank, RRF_K);
        }

        let candidate_ids: Vec<Uuid> = buckets.keys().copied().collect();
        if candidate_ids.is_empty() {
            return Ok(vec![]);
        }

        // Fetch each candidate note individually to get salience and apply
        // soft-delete + (optional) kind filtering. Notes whose `kind` doesn't
        // match `note_kind` are dropped post-fetch — they're a small set
        // bounded by `candidates`, so the extra read is cheap.
        let note_store = self.notes(token)?;
        let mut alive_notes: HashMap<Uuid, Note> = HashMap::new();
        for id in &candidate_ids {
            if let Some(note) = note_store.get_note(*id).await? {
                if note.deleted_at.is_some() {
                    continue;
                }
                if let Some(want_kind) = note_kind {
                    if note.kind != want_kind {
                        continue;
                    }
                }
                alive_notes.insert(*id, note);
            }
        }

        // Drop superseded notes unless include_superseded is true: any note targeted
        // by a `supersedes` edge is obsolete and excluded from default search
        // (ADR-013, ADR-024).
        if !include_superseded && !alive_notes.is_empty() {
            let graph = self.graph(token)?;
            let mut superseded: std::collections::HashSet<Uuid> = std::collections::HashSet::new();
            for &note_id in alive_notes.keys() {
                let inbound = graph
                    .neighbors(
                        note_id,
                        NeighborQuery {
                            direction: Direction::In,
                            relations: Some(vec![EdgeRelation::Supersedes]),
                            limit: Some(1),
                            min_weight: None,
                        },
                    )
                    .await?;
                if !inbound.is_empty() {
                    superseded.insert(note_id);
                }
            }
            alive_notes.retain(|id, _| !superseded.contains(id));
        }

        // Apply salience weighting and collect final hits.
        let mut hits: Vec<NoteSearchHit> = buckets
            .into_iter()
            .filter_map(|(id, bucket)| {
                let note = alive_notes.get(&id)?;
                let salience = note.salience.unwrap_or(0.5);
                let weight = 0.5 + 0.5 * salience;
                let weighted = DeterministicScore::from_f64(bucket.score.to_f64() * weight);
                Some(NoteSearchHit {
                    note_id: id,
                    score: weighted,
                    title: bucket.title.or_else(|| note_title(note)),
                    snippet: bucket.snippet.or_else(|| note_snippet(note)),
                })
            })
            .collect();

        hits.sort_by(|a, b| b.score.cmp(&a.score).then(a.note_id.cmp(&b.note_id)));
        hits.truncate(limit as usize);
        Ok(hits)
    }

    /// Resolve a short UUID prefix (8+ hex chars) to a full UUID.
    ///
    /// Searches entities, notes, and edges tables for a UUID starting with the
    /// given prefix, scoped to the caller's namespace. Returns `Ok(Some(uuid))`
    /// if exactly one match is found, `Ok(None)` if no matches, or an error if
    /// ambiguous (multiple matches).
    pub async fn resolve_prefix(
        &self,
        token: &NamespaceToken,
        prefix: &str,
    ) -> RuntimeResult<Option<Uuid>> {
        use khive_storage::types::{SqlStatement, SqlValue};

        let ns = token.namespace().as_str().to_owned();
        let pattern = format!("{}%", prefix);

        let tables = [
            ("entities", true),
            ("notes", true),
            ("events", false),
            ("graph_edges", false),
        ];

        let mut matches: Vec<String> = Vec::new();
        let mut reader = self.sql().reader().await.map_err(RuntimeError::Storage)?;

        for (table, has_deleted_at) in tables {
            let deleted_filter = if has_deleted_at {
                " AND deleted_at IS NULL"
            } else {
                ""
            };
            let sql = SqlStatement {
                sql: format!(
                    "SELECT id FROM {table} WHERE id LIKE ?1 AND namespace = ?2{deleted_filter} LIMIT 2"
                ),
                params: vec![
                    SqlValue::Text(pattern.clone()),
                    SqlValue::Text(ns.clone()),
                ],
                label: Some("resolve_prefix".into()),
            };
            match reader.query_all(sql).await {
                Ok(rows) => {
                    for row in rows {
                        if let Some(col) = row.columns.first() {
                            if let SqlValue::Text(s) = &col.value {
                                matches.push(s.clone());
                            }
                        }
                    }
                }
                Err(e) => {
                    let msg = e.to_string();
                    if msg.contains("no such table") {
                        continue;
                    }
                    return Err(RuntimeError::Storage(e));
                }
            }
            if matches.len() > 1 {
                break;
            }
        }

        match matches.len() {
            0 => Ok(None),
            1 => {
                let uuid = Uuid::from_str(&matches[0])
                    .map_err(|e| RuntimeError::Internal(format!("stored UUID is invalid: {e}")))?;
                Ok(Some(uuid))
            }
            _ => {
                let uuids: Vec<uuid::Uuid> = matches
                    .iter()
                    .filter_map(|s| Uuid::from_str(s).ok())
                    .collect();
                Err(RuntimeError::AmbiguousPrefix {
                    prefix: prefix.to_string(),
                    matches: uuids,
                })
            }
        }
    }

    /// Resolve a UUID to its substrate kind by trying entity, then note, then event stores.
    ///
    /// Returns `None` if the UUID is not found in any substrate.
    /// Cost: at most 3 store lookups per call (cheap for v0.1).
    pub async fn resolve(
        &self,
        token: &NamespaceToken,
        id: Uuid,
    ) -> RuntimeResult<Option<Resolved>> {
        let ns = token.namespace().as_str();

        // Entity: use the namespace-checked getter (errors on mismatch/absent).
        match self.get_entity(token, id).await {
            Ok(entity) => return Ok(Some(Resolved::Entity(entity))),
            Err(RuntimeError::NotFound(_) | RuntimeError::NamespaceMismatch { .. }) => {}
            Err(e) => return Err(e),
        }

        // Note: storage get_note is ID-only — verify namespace after fetch.
        if let Some(note) = self.notes(token)?.get_note(id).await? {
            if note.namespace == ns {
                return Ok(Some(Resolved::Note(note)));
            }
        }

        // Event: storage get_event is ID-only — verify namespace after fetch.
        if let Some(event) = self.events(token)?.get_event(id).await? {
            if event.namespace == ns {
                return Ok(Some(Resolved::Event(event)));
            }
        }

        Ok(None)
    }

    /// Delete a note by ID, enforcing namespace isolation.
    ///
    /// On hard delete, cascades to remove all incident edges (both inbound and
    /// outbound) and cleans up FTS and vector indexes, preventing dangling
    /// references for `annotates` edges that target this note (ADR-002, ADR-024).
    /// Soft delete also cleans FTS and vector indexes; edges are left in place.
    ///
    /// Returns `Ok(false)` if the note does not exist, or `Err(NamespaceMismatch)`
    /// if it belongs to a different namespace (ADR-007 namespace isolation).
    pub async fn delete_note(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        hard: bool,
    ) -> RuntimeResult<bool> {
        let ns = token.namespace().as_str();
        let note_store = self.notes(token)?;
        let note = match note_store.get_note(id).await? {
            Some(n) => n,
            None => return Ok(false),
        };
        if note.namespace != ns {
            return Err(RuntimeError::NamespaceMismatch { id });
        }
        let mode = if hard {
            DeleteMode::Hard
        } else {
            DeleteMode::Soft
        };

        // On hard delete, cascade-remove incident edges and clean up indexes.
        if hard {
            let graph = self.graph(token)?;
            for direction in [Direction::Out, Direction::In] {
                let hits = graph
                    .neighbors(
                        id,
                        NeighborQuery {
                            direction,
                            relations: None,
                            limit: None,
                            min_weight: None,
                        },
                    )
                    .await?;
                for hit in hits {
                    graph
                        .delete_edge(LinkId::from(hit.edge_id), DeleteMode::Hard)
                        .await?;
                }
            }
            let ns_str = ns.to_string();
            self.text_for_notes(token)?
                .delete_document(&ns_str, id)
                .await?;
            if self.config().embedding_model.is_some() {
                self.vectors(token)?.delete(id).await?;
            }
        }

        let deleted = note_store.delete_note(id, mode).await?;
        if !hard && deleted {
            let ns_str = ns.to_string();
            self.text_for_notes(token)?
                .delete_document(&ns_str, id)
                .await?;
            if self.config().embedding_model.is_some() {
                self.vectors(token)?.delete(id).await?;
            }
        }
        if deleted {
            let event_store = self.events(token)?;
            let ns_str = ns.to_string();
            let event = khive_storage::event::Event::new(
                ns_str.clone(),
                "delete",
                EventKind::NoteDeleted,
                SubstrateKind::Note,
                "",
            )
            .with_target(id)
            .with_payload(serde_json::json!({"id": id, "namespace": ns_str, "hard": hard}));
            event_store.append_event(event).await.map_err(|e| {
                RuntimeError::Internal(format!("delete_note: event store write failed: {e}"))
            })?;
        }
        Ok(deleted)
    }
}

/// Result of a GQL/SPARQL query with optional validation warnings.
#[derive(Clone, Debug, Serialize)]
pub struct QueryResult {
    pub rows: Vec<SqlRow>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

impl KhiveRuntime {
    // ---- Query operations ----

    /// Execute a GQL or SPARQL query string, returning raw SQL rows.
    ///
    /// The query is compiled to SQL with the namespace scope applied.
    /// GQL syntax: `MATCH (a:concept)-[e:extends]->(b) RETURN a, b LIMIT 10`
    /// SPARQL syntax: `SELECT ?a WHERE { ?a :kind "concept" . }`
    pub async fn query(&self, token: &NamespaceToken, query: &str) -> RuntimeResult<Vec<SqlRow>> {
        Ok(self.query_with_metadata(token, query).await?.rows)
    }

    /// Execute a GQL/SPARQL query, returning rows and any validation warnings.
    pub async fn query_with_metadata(
        &self,
        token: &NamespaceToken,
        query: &str,
    ) -> RuntimeResult<QueryResult> {
        use khive_query::QueryValue;
        use khive_storage::types::SqlValue;

        let ns = token.namespace().as_str();
        let ast = khive_query::parse_auto(query)?;
        let opts = khive_query::CompileOptions {
            scopes: vec![ns.to_string()],
            ..Default::default()
        };
        let compiled = khive_query::compile(&ast, &opts)?;
        let warnings = compiled.warnings;

        // Convert QueryValue params (query-layer type) to SqlValue (storage-layer type)
        // at the query–storage boundary (ADR-008 §"Query crate compiles against khive-types only").
        let params: Vec<SqlValue> = compiled
            .params
            .into_iter()
            .map(|qv| match qv {
                QueryValue::Null => SqlValue::Null,
                QueryValue::Integer(n) => SqlValue::Integer(n),
                QueryValue::Float(f) => SqlValue::Float(f),
                QueryValue::Text(s) => SqlValue::Text(s),
                QueryValue::Blob(b) => SqlValue::Blob(b),
            })
            .collect();

        let mut reader = self.sql().reader().await?;
        let stmt = SqlStatement {
            sql: compiled.sql,
            params,
            label: None,
        };
        let rows = reader.query_all(stmt).await?;
        Ok(QueryResult { rows, warnings })
    }

    /// Delete an entity by ID (soft delete by default).
    ///
    /// On hard delete, cascades to remove all incident edges (both inbound and
    /// outbound) to prevent dangling references. Soft delete also cleans FTS
    /// and vector indexes; edges are left in place.
    ///
    /// Returns `Err(NamespaceMismatch)` if the entity exists but belongs to a
    /// different namespace (ADR-007 namespace isolation).
    pub async fn delete_entity(
        &self,
        token: &NamespaceToken,
        id: Uuid,
        hard: bool,
    ) -> RuntimeResult<bool> {
        let entity = match self.entities(token)?.get_entity(id).await? {
            Some(e) => e,
            None => return Ok(false),
        };
        self.ensure_namespace(&entity.namespace, token, id)?;
        let mode = if hard {
            DeleteMode::Hard
        } else {
            DeleteMode::Soft
        };

        // On hard delete, cascade-remove incident edges to prevent dangling refs.
        if hard {
            let graph = self.graph(token)?;
            for direction in [Direction::Out, Direction::In] {
                let hits = graph
                    .neighbors(
                        id,
                        NeighborQuery {
                            direction,
                            relations: None,
                            limit: None,
                            min_weight: None,
                        },
                    )
                    .await?;
                for hit in hits {
                    graph
                        .delete_edge(LinkId::from(hit.edge_id), DeleteMode::Hard)
                        .await?;
                }
            }
            self.remove_from_indexes(token, id).await?;
        }

        let deleted = self.entities(token)?.delete_entity(id, mode).await?;
        if !hard && deleted {
            self.remove_from_indexes(token, id).await?;
        }
        if deleted {
            let event_store = self.events(token)?;
            let ns = entity.namespace.clone();
            let event = khive_storage::event::Event::new(
                ns.clone(),
                "delete",
                EventKind::EntityDeleted,
                SubstrateKind::Entity,
                "",
            )
            .with_target(id)
            .with_payload(serde_json::json!({"id": id, "namespace": ns, "hard": hard}));
            event_store.append_event(event).await.map_err(|e| {
                RuntimeError::Internal(format!("delete_entity: event store write failed: {e}"))
            })?;
        }
        Ok(deleted)
    }

    /// Count entities in a namespace, optionally filtered.
    pub async fn count_entities(
        &self,
        token: &NamespaceToken,
        kind: Option<&str>,
    ) -> RuntimeResult<u64> {
        let filter = EntityFilter {
            kinds: match kind {
                Some(k) => vec![k.to_string()],
                None => vec![],
            },
            ..Default::default()
        };
        Ok(self
            .entities(token)?
            .count_entities(token.namespace().as_str(), filter)
            .await?)
    }

    // ---- Edge CRUD operations ----

    /// Fetch a single edge by id. Returns `None` if the edge does not exist.
    pub async fn get_edge(
        &self,
        token: &NamespaceToken,
        edge_id: Uuid,
    ) -> RuntimeResult<Option<Edge>> {
        Ok(self.graph(token)?.get_edge(LinkId::from(edge_id)).await?)
    }

    /// List edges matching `filter`. `limit` is capped at 1000; defaults to 100.
    pub async fn list_edges(
        &self,
        token: &NamespaceToken,
        filter: crate::curation::EdgeListFilter,
        limit: u32,
    ) -> RuntimeResult<Vec<Edge>> {
        let limit = limit.clamp(1, 1000);
        let page = self
            .graph(token)?
            .query_edges(
                filter.into(),
                vec![SortOrder {
                    field: EdgeSortField::CreatedAt,
                    direction: khive_storage::types::SortDirection::Asc,
                }],
                PageRequest { offset: 0, limit },
            )
            .await?;
        Ok(page.items)
    }

    /// Patch-style edge update. Only `Some(_)` fields are applied.
    ///
    /// When `relation` is `Some(new_rel)`, validates that the edge's existing endpoints
    /// are legal for `new_rel` before persisting. Weight-only updates (`relation = None`)
    /// skip validation. Returns `InvalidInput` if the new relation would violate the
    /// ADR-002/ADR-019/ADR-024 three-case contract; the edge is NOT mutated on error.
    pub async fn update_edge(
        &self,
        token: &NamespaceToken,
        edge_id: Uuid,
        patch: crate::curation::EdgePatch,
    ) -> RuntimeResult<Edge> {
        let graph = self.graph(token)?;
        let mut edge = graph
            .get_edge(LinkId::from(edge_id))
            .await?
            .ok_or_else(|| crate::RuntimeError::NotFound(format!("edge {edge_id}")))?;

        let mut changed_fields: Vec<&'static str> = Vec::new();
        if let Some(r) = patch.relation {
            // Validate before mutating — use the existing endpoints with the new relation.
            self.validate_edge_relation_endpoints(token, edge.source_id, edge.target_id, r)
                .await?;
            edge.relation = r;
            changed_fields.push("relation");
        }
        if let Some(w) = patch.weight {
            edge.weight = w.clamp(0.0, 1.0);
            changed_fields.push("weight");
        }
        if let Some(props) = patch.properties {
            edge.metadata = Some(props);
        }

        graph.upsert_edge(edge.clone()).await?;

        let event_store = self.events(token)?;
        let ns = token.namespace().as_str().to_string();
        let event = khive_storage::event::Event::new(
            ns.clone(),
            "update",
            EventKind::EdgeUpdated,
            SubstrateKind::Entity,
            "",
        )
        .with_target(edge_id)
        .with_payload(
            serde_json::json!({"id": edge_id, "namespace": ns, "changed_fields": changed_fields}),
        );
        event_store.append_event(event).await.map_err(|e| {
            RuntimeError::Internal(format!("update_edge: event store write failed: {e}"))
        })?;

        Ok(edge)
    }

    /// Hard-delete an edge by id.
    ///
    /// Cascades to remove any `annotates` edges whose target is the deleted edge
    /// (ADR-002: `annotates` is note → anything; deleting an edge target leaves
    /// annotation edges dangling if not cleaned up). Returns `true` if the primary
    /// edge was removed.
    ///
    /// If `edge_id` does not refer to an edge (e.g. the caller passes an entity or
    /// note UUID by mistake), this method returns `Ok(false)` immediately with no
    /// side effects — it does **not** cascade inbound edges of the non-edge record.
    pub async fn delete_edge(
        &self,
        token: &NamespaceToken,
        edge_id: Uuid,
        hard: bool,
    ) -> RuntimeResult<bool> {
        let graph = self.graph(token)?;
        let mode = if hard {
            DeleteMode::Hard
        } else {
            DeleteMode::Soft
        };

        // Guard: verify `edge_id` is actually an edge before touching anything.
        // Without this check, passing an entity/note UUID would delete all inbound
        // annotates edges targeting that record and then return false — a destructive
        // side effect on an invalid call.
        if graph.get_edge(LinkId::from(edge_id)).await?.is_none() {
            return Ok(false);
        }

        // Cascade: remove annotate edges that target this edge (inbound from note sources).
        let inbound = graph
            .neighbors(
                edge_id,
                NeighborQuery {
                    direction: Direction::In,
                    relations: None,
                    limit: None,
                    min_weight: None,
                },
            )
            .await?;
        for hit in inbound {
            graph
                .delete_edge(LinkId::from(hit.edge_id), DeleteMode::Hard)
                .await?;
        }

        let deleted = graph.delete_edge(LinkId::from(edge_id), mode).await?;
        if deleted {
            let event_store = self.events(token)?;
            let ns = token.namespace().as_str().to_string();
            let event = khive_storage::event::Event::new(
                ns.clone(),
                "delete",
                EventKind::EdgeDeleted,
                SubstrateKind::Entity,
                "",
            )
            .with_target(edge_id)
            .with_payload(serde_json::json!({"id": edge_id, "namespace": ns, "hard": hard}));
            event_store.append_event(event).await.map_err(|e| {
                RuntimeError::Internal(format!("delete_edge: event store write failed: {e}"))
            })?;
        }
        Ok(deleted)
    }

    /// Count edges matching `filter`.
    pub async fn count_edges(
        &self,
        token: &NamespaceToken,
        filter: crate::curation::EdgeListFilter,
    ) -> RuntimeResult<u64> {
        Ok(self.graph(token)?.count_edges(filter.into()).await?)
    }

    /// Validate and construct an edge from a [`LinkSpec`] without writing to storage.
    ///
    /// Applies the full ADR-002 contract (endpoint validation, symmetric
    /// canonicalization, `dependency_kind` inference and metadata validation).
    /// Returns the constructed `Edge` on success; the caller is responsible for
    /// persisting it (e.g. via `upsert_edge` or `link_many`).
    ///
    /// The `token` must be a pre-authorized namespace token from the dispatch
    /// layer. If `spec.namespace` is set it must match `token.namespace()`;
    /// a mismatch returns `RuntimeError::InvalidInput` (ADR-007).
    pub async fn build_edge(&self, token: &NamespaceToken, spec: &LinkSpec) -> RuntimeResult<Edge> {
        let ns_str = match &spec.namespace {
            Some(s) => {
                let spec_ns = crate::Namespace::parse(s)
                    .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}")))?;
                if &spec_ns != token.namespace() {
                    return Err(RuntimeError::InvalidInput(
                        "LinkSpec namespace does not match token namespace".into(),
                    ));
                }
                s.as_str()
            }
            None => token.namespace().as_str(),
        };
        self.validate_edge_relation_endpoints(token, spec.source_id, spec.target_id, spec.relation)
            .await?;
        let (source_id, target_id) =
            canonical_edge_endpoints(spec.relation, spec.source_id, spec.target_id);
        let metadata = if spec.relation == EdgeRelation::DependsOn {
            match (
                self.resolve(token, source_id).await?,
                self.resolve(token, target_id).await?,
            ) {
                (Some(Resolved::Entity(src_e)), Some(Resolved::Entity(tgt_e))) => {
                    merge_dependency_kind(&src_e.kind, &tgt_e.kind, spec.metadata.clone())
                }
                _ => spec.metadata.clone(),
            }
        } else {
            spec.metadata.clone()
        };
        validate_edge_metadata(spec.relation, metadata.as_ref())?;
        let now = chrono::Utc::now();
        Ok(Edge {
            id: LinkId::from(Uuid::new_v4()),
            namespace: ns_str.to_string(),
            source_id,
            target_id,
            relation: spec.relation,
            weight: spec.weight,
            created_at: now,
            updated_at: now,
            deleted_at: None,
            metadata,
            target_backend: None,
        })
    }

    /// Validate and atomically upsert a batch of edges.
    ///
    /// All edges are validated and constructed with `build_edge` before any
    /// write. If validation fails for any entry the entire batch is rejected
    /// (no writes occur). On success, all edges are persisted in a single
    /// atomic transaction via `upsert_edges`.
    ///
    /// All specs must share the same namespace; the namespace is taken from
    /// `token` (or validated against it if `spec.namespace` is set).
    pub async fn link_many(
        &self,
        token: &NamespaceToken,
        specs: Vec<LinkSpec>,
    ) -> RuntimeResult<Vec<Edge>> {
        if specs.is_empty() {
            return Ok(vec![]);
        }
        let mut edges = Vec::with_capacity(specs.len());
        for spec in &specs {
            edges.push(self.build_edge(token, spec).await?);
        }
        self.graph(token)?.upsert_edges(edges.clone()).await?;
        Ok(edges)
    }
}

/// Fully specified edge creation request — input to [`KhiveRuntime::build_edge`]
/// and [`KhiveRuntime::link_many`].
#[derive(Clone, Debug)]
pub struct LinkSpec {
    pub namespace: Option<String>,
    pub source_id: Uuid,
    pub target_id: Uuid,
    pub relation: EdgeRelation,
    pub weight: f64,
    pub metadata: Option<serde_json::Value>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::curation::EdgeListFilter;
    use crate::runtime::{KhiveRuntime, NamespaceToken};
    use crate::Namespace;

    fn rt() -> KhiveRuntime {
        KhiveRuntime::memory().unwrap()
    }

    #[tokio::test]
    async fn update_edge_changes_weight() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let updated = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    weight: Some(0.5),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert!((updated.weight - 0.5).abs() < 0.001);
    }

    #[tokio::test]
    async fn update_edge_changes_relation() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let updated = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    relation: Some(EdgeRelation::VariantOf),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(updated.relation, EdgeRelation::VariantOf);
    }

    // ---- Round-5 tests: update_edge endpoint validation (ADR-002 bypass fix) ----

    // update_edge: note→entity annotates → set relation=Supersedes → InvalidInput (crossing).
    // Edge must NOT be mutated in the store.
    #[tokio::test]
    async fn update_edge_annotates_note_to_entity_set_supersedes_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
            .await
            .unwrap();
        let entity = rt
            .create_entity(&tok, "concept", None, "E", None, None, vec![])
            .await
            .unwrap();
        // Create a valid note→entity annotates edge.
        let edge = rt
            .link(&tok, note.id, entity.id, EdgeRelation::Annotates, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        // Attempt to change relation to Supersedes (crossing substrates → invalid).
        let result = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    relation: Some(EdgeRelation::Supersedes),
                    ..Default::default()
                },
            )
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "update to Supersedes on note→entity edge must return InvalidInput, got {result:?}"
        );

        // Edge must NOT be mutated — re-fetch and verify relation unchanged.
        let fetched = rt.get_edge(&tok, edge_id).await.unwrap().unwrap();
        assert_eq!(
            fetched.relation,
            EdgeRelation::Annotates,
            "edge relation must be unchanged after failed update"
        );
    }

    // update_edge: entity→entity extends → set relation=Annotates → InvalidInput
    // (annotates source must be a note).
    #[tokio::test]
    async fn update_edge_entity_to_entity_set_annotates_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let result = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    relation: Some(EdgeRelation::Annotates),
                    ..Default::default()
                },
            )
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "update to Annotates on entity→entity edge must return InvalidInput, got {result:?}"
        );
    }

    // update_edge: entity→entity extends → set relation=Supersedes → Ok
    // (entity→entity is valid for supersedes).
    #[tokio::test]
    async fn update_edge_entity_to_entity_set_supersedes_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let updated = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    relation: Some(EdgeRelation::Supersedes),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(updated.relation, EdgeRelation::Supersedes);

        // Verify persisted.
        let fetched = rt.get_edge(&tok, edge_id).await.unwrap().unwrap();
        assert_eq!(fetched.relation, EdgeRelation::Supersedes);
    }

    // update_edge: weight-only (relation = None) → Ok, no validation, unchanged relation.
    #[tokio::test]
    async fn update_edge_weight_only_skips_validation() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let updated = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    weight: Some(0.3),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(updated.relation, EdgeRelation::Extends);
        assert!((updated.weight - 0.3).abs() < 0.001);
    }

    // update_edge: entity→entity extends → set relation=VariantOf (same class) → Ok.
    #[tokio::test]
    async fn update_edge_same_class_relation_change_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let updated = rt
            .update_edge(
                &tok,
                edge_id,
                crate::curation::EdgePatch {
                    relation: Some(EdgeRelation::VariantOf),
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(updated.relation, EdgeRelation::VariantOf);
    }

    #[tokio::test]
    async fn list_edges_filters_by_relation() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = rt
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();

        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
            .await
            .unwrap();

        let filter = EdgeListFilter {
            relations: vec![EdgeRelation::Extends],
            ..Default::default()
        };
        let edges = rt.list_edges(&tok, filter, 100).await.unwrap();
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].relation, EdgeRelation::Extends);
    }

    #[tokio::test]
    async fn list_edges_filters_by_source() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = rt
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();
        let d = rt
            .create_entity(&tok, "concept", None, "D", None, None, vec![])
            .await
            .unwrap();

        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        rt.link(&tok, c.id, d.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();

        let filter = EdgeListFilter {
            source_id: Some(a.id),
            ..Default::default()
        };
        let edges = rt.list_edges(&tok, filter, 100).await.unwrap();
        assert_eq!(edges.len(), 1);
        let src: Uuid = edges[0].source_id;
        assert_eq!(src, a.id);
    }

    #[tokio::test]
    async fn delete_edge_removes_from_storage() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_id: Uuid = edge.id.into();

        let deleted = rt.delete_edge(&tok, edge_id, true).await.unwrap();
        assert!(deleted);

        let fetched = rt.get_edge(&tok, edge_id).await.unwrap();
        assert!(fetched.is_none(), "edge should be gone after delete");
    }

    #[tokio::test]
    async fn count_edges_matches_filter() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = rt
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();

        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
            .await
            .unwrap();

        let all = rt
            .count_edges(&tok, EdgeListFilter::default())
            .await
            .unwrap();
        assert_eq!(all, 2);

        let just_extends = rt
            .count_edges(
                &tok,
                EdgeListFilter {
                    relations: vec![EdgeRelation::Extends],
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        assert_eq!(just_extends, 1);
    }

    #[tokio::test]
    async fn get_entity_namespace_isolation() {
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
        let entity = rt
            .create_entity(&ns_a, "concept", None, "Alpha", None, None, vec![])
            .await
            .unwrap();

        // Same namespace: visible.
        let found = rt.get_entity(&ns_a, entity.id).await;
        assert!(found.is_ok(), "should be visible in its own namespace");

        // Different namespace: NamespaceMismatch error (ADR-007).
        let not_found = rt.get_entity(&ns_b, entity.id).await;
        assert!(
            not_found.is_err(),
            "should not be visible across namespaces"
        );
        // Must be the specific NamespaceMismatch variant, not generic NotFound.
        assert!(
            matches!(not_found.unwrap_err(), crate::RuntimeError::NamespaceMismatch { id } if id == entity.id),
            "cross-namespace get must return NamespaceMismatch with the entity id"
        );
    }

    #[tokio::test]
    async fn namespace_mismatch_error_message_is_opaque() {
        // ADR-007 timing-oracle mitigation: the external error message must not
        // reveal which namespace the record actually lives in.
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("secret-ns").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("other-ns").unwrap());
        let entity = rt
            .create_entity(&ns_a, "concept", None, "Hidden", None, None, vec![])
            .await
            .unwrap();

        let err = rt.get_entity(&ns_b, entity.id).await.unwrap_err();
        let msg = err.to_string();
        assert!(
            !msg.contains("secret-ns"),
            "error message must not leak the actual namespace; got: {msg}"
        );
        assert!(
            !msg.contains("other-ns"),
            "error message must not leak the requested namespace; got: {msg}"
        );
    }

    #[tokio::test]
    async fn delete_entity_namespace_isolation() {
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
        let entity = rt
            .create_entity(&ns_a, "concept", None, "Beta", None, None, vec![])
            .await
            .unwrap();

        // Delete from wrong namespace: NamespaceMismatch error (ADR-007 — no information leak).
        let cross_ns_result = rt.delete_entity(&ns_b, entity.id, true).await;
        assert!(
            cross_ns_result.is_err(),
            "cross-namespace delete must error"
        );
        assert!(
            matches!(cross_ns_result.unwrap_err(), crate::RuntimeError::NamespaceMismatch { id } if id == entity.id),
            "cross-namespace delete must return NamespaceMismatch, not a generic error"
        );

        // Entity still present in its own namespace.
        let still_there = rt.get_entity(&ns_a, entity.id).await;
        assert!(
            still_there.is_ok(),
            "entity must survive cross-ns delete attempt"
        );

        // Delete from correct namespace: succeeds.
        let deleted_ok = rt.delete_entity(&ns_a, entity.id, true).await.unwrap();
        assert!(deleted_ok, "same-namespace delete must succeed");
    }

    // ---- Note ADR-024 tests ----

    #[tokio::test]
    async fn create_note_indexes_into_fts5() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "FlashAttention reduces memory by using tiling",
                Some(0.8),
                None,
                vec![],
            )
            .await
            .unwrap();

        // FTS5 should have indexed the note content.
        let ns = tok.namespace().as_str().to_string();
        let hits = rt
            .text_for_notes(&tok)
            .unwrap()
            .search(khive_storage::types::TextSearchRequest {
                query: "FlashAttention".to_string(),
                mode: khive_storage::types::TextQueryMode::Plain,
                filter: Some(khive_storage::types::TextFilter {
                    namespaces: vec![ns],
                    ..Default::default()
                }),
                top_k: 10,
                snippet_chars: 100,
            })
            .await
            .unwrap();

        assert!(
            hits.iter().any(|h| h.subject_id == note.id),
            "note should be indexed in FTS5 after create"
        );
    }

    #[tokio::test]
    async fn create_note_with_properties() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let props = serde_json::json!({"source": "arxiv:2205.14135"});
        let note = rt
            .create_note(
                &tok,
                "insight",
                None,
                "FlashAttention is IO-aware",
                Some(0.9),
                Some(props.clone()),
                vec![],
            )
            .await
            .unwrap();

        assert_eq!(note.properties.as_ref().unwrap(), &props);
    }

    #[tokio::test]
    async fn create_note_creates_annotates_edges() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(&tok, "concept", None, "FlashAttention", None, None, vec![])
            .await
            .unwrap();

        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "FlashAttention uses SRAM tiling for memory efficiency",
                Some(0.9),
                None,
                vec![entity.id],
            )
            .await
            .unwrap();

        // The note should have an outbound `annotates` edge to the entity.
        let out_neighbors = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(out_neighbors.len(), 1);
        assert_eq!(out_neighbors[0].node_id, entity.id);
        assert_eq!(out_neighbors[0].relation, EdgeRelation::Annotates);

        // The entity should have an inbound `annotates` edge from the note.
        let in_neighbors = rt
            .neighbors(
                &tok,
                entity.id,
                Direction::In,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(in_neighbors.len(), 1);
        assert_eq!(in_neighbors[0].node_id, note.id);
    }

    #[tokio::test]
    async fn neighbors_without_relation_filter_returns_all() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = rt
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();

        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
            .await
            .unwrap();

        let all = rt
            .neighbors(&tok, a.id, Direction::Out, None, None)
            .await
            .unwrap();
        assert_eq!(all.len(), 2);
    }

    #[tokio::test]
    async fn neighbors_with_relation_filter_returns_subset() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = rt
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();

        rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        rt.link(&tok, a.id, c.id, EdgeRelation::Enables, 1.0, None)
            .await
            .unwrap();

        let filtered = rt
            .neighbors(
                &tok,
                a.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Extends]),
            )
            .await
            .unwrap();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].node_id, b.id);
        assert_eq!(filtered[0].relation, EdgeRelation::Extends);
    }

    #[tokio::test]
    async fn search_notes_returns_relevant_note() {
        let rt = rt();
        let tok = NamespaceToken::local();
        rt.create_note(
            &tok,
            "observation",
            None,
            "GQA reduces KV cache memory for large models",
            Some(0.8),
            None,
            vec![],
        )
        .await
        .unwrap();

        let results = rt
            .search_notes(&tok, "GQA KV cache", None, 10, None, false)
            .await
            .unwrap();

        assert!(!results.is_empty(), "search should return the indexed note");
        let hit = &results[0];
        assert!(
            hit.title.is_some(),
            "note hit title should be populated (falls back to content)"
        );
        assert!(
            hit.snippet.is_some(),
            "note hit snippet should be populated"
        );
    }

    #[tokio::test]
    async fn search_notes_excludes_soft_deleted() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "RoPE positional encoding rotary embeddings",
                Some(0.7),
                None,
                vec![],
            )
            .await
            .unwrap();

        // Soft-delete the note.
        rt.notes(&tok)
            .unwrap()
            .delete_note(note.id, DeleteMode::Soft)
            .await
            .unwrap();

        let results = rt
            .search_notes(&tok, "RoPE rotary positional", None, 10, None, false)
            .await
            .unwrap();

        assert!(
            results.iter().all(|h| h.note_id != note.id),
            "soft-deleted note should be excluded from search"
        );
    }

    #[tokio::test]
    async fn resolve_returns_entity() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(&tok, "concept", None, "LoRA", None, None, vec![])
            .await
            .unwrap();

        let resolved = rt.resolve(&tok, entity.id).await.unwrap();
        match resolved {
            Some(Resolved::Entity(e)) => assert_eq!(e.id, entity.id),
            other => panic!("expected Resolved::Entity, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn resolve_returns_note() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "LoRA fine-tunes LLMs with low-rank adapters",
                Some(0.85),
                None,
                vec![],
            )
            .await
            .unwrap();

        let resolved = rt.resolve(&tok, note.id).await.unwrap();
        match resolved {
            Some(Resolved::Note(n)) => assert_eq!(n.id, note.id),
            other => panic!("expected Resolved::Note, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn resolve_returns_none_for_unknown_uuid() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let unknown = Uuid::new_v4();
        let resolved = rt.resolve(&tok, unknown).await.unwrap();
        assert!(resolved.is_none(), "unknown UUID should resolve to None");
    }

    #[tokio::test]
    async fn resolve_prefix_finds_entity_in_own_namespace() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(&tok, "concept", None, "PrefixTest", None, None, vec![])
            .await
            .unwrap();
        let prefix = &entity.id.to_string()[..8];

        let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
        assert_eq!(resolved, Some(entity.id));
    }

    #[tokio::test]
    async fn resolve_prefix_invisible_across_namespaces() {
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
        let entity = rt
            .create_entity(&ns_a, "concept", None, "Invisible", None, None, vec![])
            .await
            .unwrap();
        let prefix = &entity.id.to_string()[..8];

        // From ns_b, the entity in ns_a should not be visible.
        let resolved = rt.resolve_prefix(&ns_b, prefix).await.unwrap();
        assert_eq!(resolved, None);
    }

    #[tokio::test]
    async fn resolve_prefix_ambiguous_same_namespace() {
        use khive_storage::entity::Entity;

        let rt = rt();
        let tok = NamespaceToken::local();
        // Two entities with UUIDs sharing the same 8-char prefix "aabbccdd".
        let id_a = Uuid::parse_str("aabbccdd-1111-4000-8000-000000000001").unwrap();
        let id_b = Uuid::parse_str("aabbccdd-2222-4000-8000-000000000002").unwrap();

        let mut entity_a = Entity::new("local", "concept", "AmbigA");
        entity_a.id = id_a;
        let mut entity_b = Entity::new("local", "concept", "AmbigB");
        entity_b.id = id_b;

        let store = rt.entities(&tok).unwrap();
        store.upsert_entity(entity_a).await.unwrap();
        store.upsert_entity(entity_b).await.unwrap();

        let result = rt.resolve_prefix(&tok, "aabbccdd").await;
        assert!(
            result.is_err(),
            "shared 8-char prefix must return Ambiguous error"
        );
    }

    // ---- Event resolution tests (issue #30) ----
    //
    // resolve_prefix and handle_get already include events; these tests are
    // regression coverage confirming event UUIDs are resolvable and that get()
    // returns kind="event".

    #[tokio::test]
    async fn resolve_finds_event_by_full_uuid() {
        use khive_storage::Event;
        use khive_types::{EventKind, SubstrateKind};

        let rt = rt();
        let tok = NamespaceToken::local();
        let ns = tok.namespace().as_str();
        let event = Event::new(
            ns,
            "test_verb",
            EventKind::Audit,
            SubstrateKind::Entity,
            "actor",
        );
        let event_id = event.id;
        rt.events(&tok).unwrap().append_event(event).await.unwrap();

        let resolved = rt.resolve(&tok, event_id).await.unwrap();
        assert!(
            matches!(resolved, Some(Resolved::Event(_))),
            "event UUID must resolve to Resolved::Event, got {resolved:?}"
        );
    }

    #[tokio::test]
    async fn resolve_prefix_finds_event() {
        use khive_storage::Event;
        use khive_types::{EventKind, SubstrateKind};

        let rt = rt();
        let tok = NamespaceToken::local();
        let ns = tok.namespace().as_str();
        let event = Event::new(
            ns,
            "test_verb",
            EventKind::Audit,
            SubstrateKind::Entity,
            "actor",
        );
        let event_id = event.id;
        rt.events(&tok).unwrap().append_event(event).await.unwrap();

        let prefix = &event_id.to_string()[..8];
        let resolved = rt.resolve_prefix(&tok, prefix).await.unwrap();
        assert_eq!(
            resolved,
            Some(event_id),
            "resolve_prefix must return event UUID for 8-char prefix"
        );
    }

    // ---- Referential integrity tests (fix/link-referential-integrity) ----

    #[tokio::test]
    async fn link_phantom_source_returns_not_found() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let phantom = Uuid::new_v4();

        let result = rt
            .link(&tok, phantom, b.id, EdgeRelation::Extends, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::NotFound(msg)) => {
                assert!(
                    msg.contains("source"),
                    "error message must name 'source': {msg}"
                );
            }
            other => panic!("expected NotFound for phantom source, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn link_phantom_target_returns_not_found() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let phantom = Uuid::new_v4();

        let result = rt
            .link(&tok, a.id, phantom, EdgeRelation::Extends, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::NotFound(msg)) => {
                assert!(
                    msg.contains("target"),
                    "error message must name 'target': {msg}"
                );
            }
            other => panic!("expected NotFound for phantom target, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn link_real_entities_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();

        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 0.8, None)
            .await
            .unwrap();
        assert_eq!(edge.source_id, a.id);
        assert_eq!(edge.target_id, b.id);
        assert_eq!(edge.relation, EdgeRelation::Extends);
    }

    #[tokio::test]
    async fn create_note_annotates_phantom_returns_not_found() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let phantom = Uuid::new_v4();

        let result = rt
            .create_note(
                &tok,
                "observation",
                None,
                "some content",
                Some(0.5),
                None,
                vec![phantom],
            )
            .await;
        assert!(
            matches!(result, Err(RuntimeError::NotFound(_))),
            "annotates with phantom uuid must return NotFound, got {result:?}"
        );
    }

    #[tokio::test]
    async fn create_note_annotates_real_entity_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(&tok, "concept", None, "RealTarget", None, None, vec![])
            .await
            .unwrap();

        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "content",
                Some(0.5),
                None,
                vec![entity.id],
            )
            .await
            .unwrap();

        let neighbors = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0].node_id, entity.id);
    }

    // Atomicity: multi-target annotates golden path — all edges created, note present.
    #[tokio::test]
    async fn create_note_multi_annotates_creates_all_edges() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let t1 = rt
            .create_entity(&tok, "concept", None, "Target1", None, None, vec![])
            .await
            .unwrap();
        let t2 = rt
            .create_entity(&tok, "concept", None, "Target2", None, None, vec![])
            .await
            .unwrap();

        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "content",
                Some(0.5),
                None,
                vec![t1.id, t2.id],
            )
            .await
            .unwrap();

        let neighbors = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            neighbors.len(),
            2,
            "multi-annotates note must have exactly 2 outbound annotates edges"
        );
        let target_ids: Vec<Uuid> = neighbors.iter().map(|n| n.node_id).collect();
        assert!(target_ids.contains(&t1.id));
        assert!(target_ids.contains(&t2.id));
    }

    #[tokio::test]
    async fn link_target_in_different_namespace_returns_not_found() {
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
        let a = rt
            .create_entity(&ns_a, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&ns_b, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();

        // Linking from ns-a: target b lives in ns-b — must be treated as not found.
        let result = rt
            .link(&ns_a, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await;
        assert!(
            matches!(result, Err(RuntimeError::NotFound(_))),
            "target in different namespace must return NotFound (fail-closed), got {result:?}"
        );
    }

    #[tokio::test]
    async fn link_phantom_self_loop_returns_not_found() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let phantom = Uuid::new_v4();

        let result = rt
            .link(&tok, phantom, phantom, EdgeRelation::Extends, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::NotFound(msg)) => {
                assert!(
                    msg.contains("source"),
                    "self-loop must fail on source first: {msg}"
                );
            }
            other => panic!("expected NotFound for phantom self-loop, got {other:?}"),
        }
    }

    // ---- Round-2 tests: edge target coverage + atomicity ----

    #[tokio::test]
    async fn link_note_to_edge_annotates_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        // Create a real edge between a and b, capture its UUID.
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        // Create a note and annotate the edge itself (edge is a valid substrate target per ADR-024).
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "edge note",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();

        let result = rt
            .link(&tok, note.id, edge_uuid, EdgeRelation::Annotates, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "note→edge Annotates must succeed, got {result:?}"
        );
    }

    #[tokio::test]
    async fn create_note_annotates_real_edge_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "annotating an edge",
                Some(0.5),
                None,
                vec![edge_uuid],
            )
            .await
            .unwrap();

        let neighbors = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0].node_id, edge_uuid);
    }

    #[tokio::test]
    async fn create_note_annotates_phantom_is_atomic_no_note_persisted() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let phantom = Uuid::new_v4();

        let before_count = rt.list_notes(&tok, None, 1000, 0).await.unwrap().len();

        let result = rt
            .create_note(
                &tok,
                "observation",
                None,
                "should not persist",
                Some(0.5),
                None,
                vec![phantom],
            )
            .await;
        assert!(
            matches!(result, Err(RuntimeError::NotFound(_))),
            "phantom annotates target must return NotFound, got {result:?}"
        );

        // Atomicity: the note row must NOT have been written.
        let after_count = rt.list_notes(&tok, None, 1000, 0).await.unwrap().len();
        assert_eq!(
            before_count, after_count,
            "failed create_note must not persist any note row (atomicity)"
        );

        // FTS must not contain the content either.
        let search_hits = rt
            .search_notes(&tok, "should not persist", None, 10, None, false)
            .await
            .unwrap();
        assert!(
            search_hits.is_empty(),
            "failed create_note must not index into FTS (atomicity)"
        );
        // Vector-store row: only written when an embedding model is configured; the rt()
        // harness has none, so no vector assertion is needed here.
    }

    // ---- Round-3 tests: relation-aware endpoint contract (ADR-002) ----

    // Test #2: entity→entity with non-annotates rejects an edge UUID as target.
    #[tokio::test]
    async fn link_entity_to_edge_uuid_non_annotates_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        // Create a real edge; capture its UUID as the bad target.
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        let result = rt
            .link(&tok, a.id, edge_uuid, EdgeRelation::Extends, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(
                    msg.contains("target"),
                    "error message must name 'target': {msg}"
                );
            }
            other => {
                panic!("expected InvalidInput for edge-uuid target with Extends, got {other:?}")
            }
        }
    }

    // Test #3: non-annotates rejects a note UUID as source.
    #[tokio::test]
    async fn link_note_as_source_non_annotates_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
            .await
            .unwrap();
        let entity = rt
            .create_entity(&tok, "concept", None, "E", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(&tok, note.id, entity.id, EdgeRelation::DependsOn, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(
                    msg.contains("source"),
                    "error message must name 'source': {msg}"
                );
            }
            other => panic!("expected InvalidInput for note source with DependsOn, got {other:?}"),
        }
    }

    // Test #4: annotates rejects entity as source (source must be a note).
    #[tokio::test]
    async fn link_entity_as_annotates_source_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(&tok, a.id, b.id, EdgeRelation::Annotates, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(
                    msg.contains("source") && msg.contains("note"),
                    "error must say source must be a note: {msg}"
                );
            }
            other => {
                panic!("expected InvalidInput for entity source with Annotates, got {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn link_edge_as_annotates_source_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        // An existing edge used as an annotates source: wrong kind, not absent.
        let result = rt
            .link(&tok, edge_uuid, a.id, EdgeRelation::Annotates, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(
                    msg.contains("source") && msg.contains("note"),
                    "edge-as-annotates-source must report wrong kind, not NotFound: {msg}"
                );
            }
            other => panic!("expected InvalidInput for edge source with Annotates, got {other:?}"),
        }
    }

    // Test #5: note→event with annotates succeeds (event is a valid annotates target).
    #[tokio::test]
    async fn link_note_to_event_annotates_succeeds() {
        use khive_storage::Event;
        use khive_types::{EventKind, SubstrateKind};

        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "observing an event",
                Some(0.6),
                None,
                vec![],
            )
            .await
            .unwrap();

        // Build an event directly via the store (no runtime create_event exists).
        let ns = tok.namespace().as_str();
        let event = Event::new(
            ns,
            "test_verb",
            EventKind::Audit,
            SubstrateKind::Entity,
            "test_actor",
        );
        let event_id = event.id;
        rt.events(&tok).unwrap().append_event(event).await.unwrap();

        let result = rt
            .link(&tok, note.id, event_id, EdgeRelation::Annotates, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "note→event Annotates must succeed, got {result:?}"
        );
    }

    // Test #6: create_note with event as annotates target succeeds.
    #[tokio::test]
    async fn create_note_annotates_event_succeeds() {
        use khive_storage::Event;
        use khive_types::{EventKind, SubstrateKind};

        let rt = rt();
        let tok = NamespaceToken::local();
        let ns = tok.namespace().as_str();
        let event = Event::new(
            ns,
            "test_verb",
            EventKind::Audit,
            SubstrateKind::Entity,
            "test_actor",
        );
        let event_id = event.id;
        rt.events(&tok).unwrap().append_event(event).await.unwrap();

        let result = rt
            .create_note(
                &tok,
                "observation",
                None,
                "note annotating an event",
                Some(0.5),
                None,
                vec![event_id],
            )
            .await;
        assert!(
            result.is_ok(),
            "create_note with event annotates target must succeed, got {result:?}"
        );
        // Verify the annotates edge was created.
        let note = result.unwrap();
        let neighbors = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0].node_id, event_id);
    }

    // ---- Round-4 tests: supersedes same-substrate contract (ADR-019/ADR-024) ----

    // Headline regression: note→note supersedes must succeed (was wrongly rejected before this fix).
    #[tokio::test]
    async fn link_supersedes_note_to_note_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let old_note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "old observation",
                Some(0.7),
                None,
                vec![],
            )
            .await
            .unwrap();
        let new_note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "revised observation superseding the old one",
                Some(0.9),
                None,
                vec![],
            )
            .await
            .unwrap();

        let result = rt
            .link(
                &tok,
                new_note.id,
                old_note.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        assert!(
            result.is_ok(),
            "note→note Supersedes must succeed (ADR-019 note supersession), got {result:?}"
        );
    }

    #[tokio::test]
    async fn link_supersedes_entity_to_entity_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let old_entity = rt
            .create_entity(&tok, "concept", None, "OldConcept", None, None, vec![])
            .await
            .unwrap();
        let new_entity = rt
            .create_entity(&tok, "concept", None, "NewConcept", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(
                &tok,
                new_entity.id,
                old_entity.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        assert!(
            result.is_ok(),
            "entity→entity Supersedes must succeed, got {result:?}"
        );
    }

    #[tokio::test]
    async fn link_supersedes_note_to_entity_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
            .await
            .unwrap();
        let entity = rt
            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(
                &tok,
                note.id,
                entity.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(
                    msg.contains("same substrate") || msg.contains("same-substrate"),
                    "error must name the same-substrate rule: {msg}"
                );
            }
            other => panic!(
                "expected InvalidInput for note→entity Supersedes (cross-substrate), got {other:?}"
            ),
        }
    }

    #[tokio::test]
    async fn link_supersedes_entity_to_note_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
            .await
            .unwrap();
        let note = rt
            .create_note(&tok, "observation", None, "a note", Some(0.5), None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(
                &tok,
                entity.id,
                note.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(
                    msg.contains("same substrate") || msg.contains("same-substrate"),
                    "error must name the same-substrate rule: {msg}"
                );
            }
            other => panic!(
                "expected InvalidInput for entity→note Supersedes (cross-substrate), got {other:?}"
            ),
        }
    }

    #[tokio::test]
    async fn link_supersedes_event_source_returns_invalid_input() {
        use khive_storage::Event;
        use khive_types::{EventKind, SubstrateKind};

        let rt = rt();
        let tok = NamespaceToken::local();
        let ns = tok.namespace().as_str();
        let event = Event::new(
            ns,
            "test_verb",
            EventKind::Audit,
            SubstrateKind::Entity,
            "test_actor",
        );
        let event_id = event.id;
        rt.events(&tok).unwrap().append_event(event).await.unwrap();

        let entity = rt
            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(
                &tok,
                event_id,
                entity.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(msg.contains("event"), "error must mention 'event': {msg}");
            }
            other => {
                panic!("expected InvalidInput for event source with Supersedes, got {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn link_supersedes_event_target_returns_invalid_input() {
        use khive_storage::Event;
        use khive_types::{EventKind, SubstrateKind};

        let rt = rt();
        let tok = NamespaceToken::local();
        let ns = tok.namespace().as_str();
        let event = Event::new(
            ns,
            "test_verb",
            EventKind::Audit,
            SubstrateKind::Entity,
            "test_actor",
        );
        let event_id = event.id;
        rt.events(&tok).unwrap().append_event(event).await.unwrap();

        let entity = rt
            .create_entity(&tok, "concept", None, "SomeEntity", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(
                &tok,
                entity.id,
                event_id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(msg.contains("event"), "error must mention 'event': {msg}");
            }
            other => {
                panic!("expected InvalidInput for event target with Supersedes, got {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn link_supersedes_edge_source_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        let result = rt
            .link(&tok, edge_uuid, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(msg.contains("source"), "error must name 'source': {msg}");
            }
            other => {
                panic!("expected InvalidInput for edge-uuid source with Supersedes, got {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn link_supersedes_edge_target_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        let result = rt
            .link(&tok, a.id, edge_uuid, EdgeRelation::Supersedes, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::InvalidInput(msg)) => {
                assert!(msg.contains("target"), "error must name 'target': {msg}");
            }
            other => {
                panic!("expected InvalidInput for edge-uuid target with Supersedes, got {other:?}")
            }
        }
    }

    #[tokio::test]
    async fn link_supersedes_phantom_source_returns_not_found() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "existing note",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();
        let phantom = Uuid::new_v4();

        let result = rt
            .link(&tok, phantom, note.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::NotFound(msg)) => {
                assert!(msg.contains("source"), "error must name 'source': {msg}");
            }
            other => panic!("expected NotFound for phantom source with Supersedes, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn link_supersedes_phantom_target_returns_not_found() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "existing note",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();
        let phantom = Uuid::new_v4();

        let result = rt
            .link(&tok, note.id, phantom, EdgeRelation::Supersedes, 1.0, None)
            .await;
        match result {
            Err(RuntimeError::NotFound(msg)) => {
                assert!(msg.contains("target"), "error must name 'target': {msg}");
            }
            other => panic!("expected NotFound for phantom target with Supersedes, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn link_supersedes_cross_namespace_source_returns_not_found() {
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
        let note_a = rt
            .create_note(
                &ns_a,
                "observation",
                None,
                "note in ns-a",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();
        let note_b = rt
            .create_note(
                &ns_b,
                "observation",
                None,
                "note in ns-b",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();

        // From ns-a perspective, note_b is in a different namespace — treated as not found.
        let result = rt
            .link(
                &ns_a,
                note_b.id,
                note_a.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        assert!(
            matches!(result, Err(RuntimeError::NotFound(_))),
            "cross-namespace source with Supersedes must return NotFound (fail-closed), got {result:?}"
        );
    }

    // Sanity: extends (non-annotates, non-supersedes) still requires entity→entity.
    #[tokio::test]
    async fn link_extends_note_source_still_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "a note that cannot be an extends source",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();
        let entity = rt
            .create_entity(&tok, "concept", None, "E", None, None, vec![])
            .await
            .unwrap();

        let result = rt
            .link(&tok, note.id, entity.id, EdgeRelation::Extends, 1.0, None)
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "note source with Extends must still return InvalidInput after this fix, got {result:?}"
        );
    }

    // Sanity: annotates note→edge still succeeds (unchanged path not broken by this fix).
    #[tokio::test]
    async fn link_annotates_note_to_edge_still_succeeds_after_fix() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let edge_uuid: Uuid = edge.id.into();

        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "annotating an edge",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();

        let result = rt
            .link(&tok, note.id, edge_uuid, EdgeRelation::Annotates, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "note→edge Annotates must still succeed after supersedes fix, got {result:?}"
        );
    }

    // ---- Compensation-path rollback (fix/annotates) ----

    // The compensation branch in `create_note_inner` (operations.rs) rolls back
    // a partial write — note row + first edge + FTS + vector — when a subsequent
    // link call fails. The failure trigger is a storage error (e.g. I/O failure)
    // that cannot occur in the in-memory runtime; this test instead exercises the
    // exact cleanup operations that the compensation branch performs, starting from
    // a manually-constructed partial state, and verifies the post-cleanup invariants.
    //
    // What this covers: the cleanup sequence (delete_edge, delete_note hard, FTS
    // index clean) is correct and leaves the DB in a pristine state. What it does
    // not cover: the trigger condition (second link failure). Storage-error injection
    // would require a mock GraphStore, which is beyond the current test infrastructure.
    #[tokio::test]
    async fn create_note_multi_annotates_compensation_cleanup_restores_pristine_state() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let t1 = rt
            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
            .await
            .unwrap();

        // Construct the partial state that the compensation branch would encounter:
        // note persisted + first annotates edge created.
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "partial note",
                Some(0.5),
                None,
                vec![t1.id],
            )
            .await
            .unwrap();

        // Confirm the partial state exists before compensation.
        let before_notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
        assert_eq!(before_notes.len(), 1, "note must be present before cleanup");
        let before_edges = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            before_edges.len(),
            1,
            "one annotates edge must exist before cleanup"
        );
        let edge_id: Uuid = before_edges[0].edge_id;

        // Execute the same cleanup sequence that `create_note_inner`'s Err branch runs.
        rt.delete_edge(&tok, edge_id, true).await.unwrap();
        rt.delete_note(&tok, note.id, true /* hard */)
            .await
            .unwrap();

        // Post-compensation invariants:
        let after_notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
        assert!(
            after_notes.is_empty(),
            "compensation must remove the note row; got {after_notes:?}"
        );
        let search_hits = rt
            .search_notes(&tok, "partial note", None, 10, None, false)
            .await
            .unwrap();
        assert!(
            search_hits.is_empty(),
            "compensation must clean the FTS index; got {search_hits:?}"
        );
        let after_edges = rt
            .neighbors(&tok, note.id, Direction::Out, None, None)
            .await
            .unwrap();
        assert!(
            after_edges.is_empty(),
            "compensation must remove all partial edges; got {after_edges:?}"
        );
    }

    // ---- Hard-delete cascade for note and edge annotation targets (fix/annotates) ----

    // ADR-002:73 — annotates is note → ANYTHING (entity, note, edge, event).
    // ADR-024:103 — targets may be entity, edge, event, or note.
    // Hard-deleting any of those targets must cascade incident annotates edges.
    // Soft deletes leave edges (data-vs-view rule).

    #[tokio::test]
    async fn annotated_entity_hard_delete_cascades_annotate_edge() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(&tok, "concept", None, "E", None, None, vec![])
            .await
            .unwrap();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "note about entity",
                Some(0.5),
                None,
                vec![entity.id],
            )
            .await
            .unwrap();

        // Confirm edge exists before delete.
        let before = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            before.len(),
            1,
            "annotates edge must exist before entity delete"
        );

        // Hard delete the entity.
        let deleted = rt.delete_entity(&tok, entity.id, true).await.unwrap();
        assert!(deleted, "entity hard delete must return true");

        // Annotates edge must be gone.
        let after = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert!(
            after.is_empty(),
            "annotates edge must be cascaded on entity hard delete; got {after:?}"
        );
    }

    #[tokio::test]
    async fn annotated_note_hard_delete_cascades_annotate_edge() {
        let rt = rt();
        let tok = NamespaceToken::local();
        // note_target is the thing being annotated (a note itself).
        let note_target = rt
            .create_note(
                &tok,
                "observation",
                None,
                "target note",
                Some(0.5),
                None,
                vec![],
            )
            .await
            .unwrap();
        // note_source annotates note_target.
        let note_source = rt
            .create_note(
                &tok,
                "insight",
                None,
                "annotation",
                Some(0.5),
                None,
                vec![note_target.id],
            )
            .await
            .unwrap();

        let before = rt
            .neighbors(
                &tok,
                note_source.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            before.len(),
            1,
            "annotates edge must exist before note delete"
        );

        // Hard delete the annotation TARGET note.
        let deleted = rt.delete_note(&tok, note_target.id, true).await.unwrap();
        assert!(deleted, "note hard delete must return true");

        // The annotates edge targeting note_target must be gone.
        let after = rt
            .neighbors(
                &tok,
                note_source.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert!(
            after.is_empty(),
            "annotates edge must be cascaded on note-target hard delete; got {after:?}"
        );
    }

    #[tokio::test]
    async fn annotated_edge_delete_cascades_annotate_edge() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        // Create an edge to annotate.
        let base_edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        let base_edge_uuid: Uuid = base_edge.id.into();

        // Create a note that annotates the edge.
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "note about edge",
                Some(0.5),
                None,
                vec![base_edge_uuid],
            )
            .await
            .unwrap();

        let before = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            before.len(),
            1,
            "annotates edge must exist before base edge delete"
        );

        // Delete the base edge.
        let deleted = rt.delete_edge(&tok, base_edge_uuid, true).await.unwrap();
        assert!(deleted, "edge delete must return true");

        // The annotates edge targeting base_edge must be gone.
        let after = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert!(
            after.is_empty(),
            "annotates edge must be cascaded on base edge delete; got {after:?}"
        );
    }

    #[tokio::test]
    async fn mixed_multi_annotates_partial_target_hard_delete_leaves_remaining_edges() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let t1 = rt
            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
            .await
            .unwrap();
        let t2 = rt
            .create_entity(&tok, "concept", None, "T2", None, None, vec![])
            .await
            .unwrap();

        // Note annotates both t1 and t2.
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "multi-target note",
                Some(0.5),
                None,
                vec![t1.id, t2.id],
            )
            .await
            .unwrap();

        let before = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            before.len(),
            2,
            "must have 2 annotates edges before any delete"
        );

        // Hard delete only t1.
        rt.delete_entity(&tok, t1.id, true).await.unwrap();

        // Edge to t1 must be gone, edge to t2 must remain.
        let after = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            after.len(),
            1,
            "only the edge to t1 must be cascaded; t2 edge must remain"
        );
        assert_eq!(
            after[0].node_id, t2.id,
            "remaining annotates edge must point to t2"
        );
    }

    #[tokio::test]
    async fn annotated_note_soft_delete_preserves_annotate_edge() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note_target = rt
            .create_note(&tok, "observation", None, "target", Some(0.5), None, vec![])
            .await
            .unwrap();
        let note_source = rt
            .create_note(
                &tok,
                "insight",
                None,
                "annotation",
                Some(0.5),
                None,
                vec![note_target.id],
            )
            .await
            .unwrap();

        let before = rt
            .neighbors(
                &tok,
                note_source.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(before.len(), 1);

        // Soft delete must NOT cascade edges (data-vs-view principle).
        let deleted = rt.delete_note(&tok, note_target.id, false).await.unwrap();
        assert!(deleted, "soft delete must return true");

        let after = rt
            .neighbors(
                &tok,
                note_source.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            after.len(),
            1,
            "soft delete must NOT cascade edges; got {after:?}"
        );
    }

    // ---- delete_edge public-API safety (fix/annotates round-3) ----

    // Passing an entity/note UUID to `delete_edge` must return Ok(false) with no
    // side effects — it must NOT delete inbound annotates edges targeting that record.
    // Without the get_edge guard, the old code would cascade inbound edges before
    // returning false.
    #[tokio::test]
    async fn delete_edge_non_edge_uuid_has_no_side_effects() {
        let rt = rt();
        let tok = NamespaceToken::local();

        // Create an entity that has an inbound annotates edge.
        let entity = rt
            .create_entity(&tok, "concept", None, "Target", None, None, vec![])
            .await
            .unwrap();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "annotates the entity",
                Some(0.5),
                None,
                vec![entity.id],
            )
            .await
            .unwrap();

        // Confirm the annotates edge exists.
        let before = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(before.len(), 1, "annotates edge must exist before test");
        let annotates_edge_id: Uuid = before[0].edge_id;

        // Call delete_edge with the entity UUID (NOT an edge UUID).
        let result = rt.delete_edge(&tok, entity.id, true).await;
        assert!(
            result.is_ok(),
            "delete_edge must not error on a non-edge UUID"
        );
        assert!(
            !result.unwrap(),
            "delete_edge must return false for a non-edge UUID"
        );

        // The inbound annotates edge to the entity must still exist — no side effects.
        let after = rt
            .neighbors(
                &tok,
                note.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert_eq!(
            after.len(),
            1,
            "delete_edge with a non-edge UUID must not touch inbound annotates edges"
        );
        assert_eq!(
            after[0].edge_id, annotates_edge_id,
            "the original annotates edge must be unchanged"
        );
    }

    // ---- create_note compensation branch (fix/annotates round-3) ----

    // This test injects a deterministic failure on the second `link` call inside
    // `create_note_inner` (the one that would create the second annotates edge).
    // It verifies that the compensation branch is wired — i.e. this test would
    // fail if the `Err(e)` rollback arm at operations.rs were deleted.
    //
    // Injection mechanism: LINK_FAIL_AFTER thread-local (ops.rs, cfg(test) only).
    // Setting it to 2 forces the 2nd link call to return an error.  The counter is
    // reset to 0 once triggered, so no other test is affected.
    #[tokio::test]
    async fn create_note_multi_annotates_second_link_failure_rolls_back_partial_write() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let t1 = rt
            .create_entity(&tok, "concept", None, "T1", None, None, vec![])
            .await
            .unwrap();
        let t2 = rt
            .create_entity(&tok, "concept", None, "T2", None, None, vec![])
            .await
            .unwrap();

        // Arm the injection: fail on the 2nd link (link_idx+1 == 2).
        LINK_FAIL_AFTER.with(|cell| cell.set(2));

        let result = rt
            .create_note(
                &tok,
                "observation",
                None,
                "rollback target",
                Some(0.5),
                None,
                vec![t1.id, t2.id],
            )
            .await;

        // The call must fail with the injected error.
        assert!(
            result.is_err(),
            "create_note must propagate the injected link failure"
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("injected link failure"),
            "error must carry injection message; got: {err_msg}"
        );

        // Compensation must have removed the note row.
        let notes = rt.list_notes(&tok, None, 1000, 0).await.unwrap();
        assert!(
            notes.is_empty(),
            "compensation must remove the note row; got {notes:?}"
        );

        // FTS must have no hit for the content.
        let hits = rt
            .search_notes(&tok, "rollback target", None, 10, None, false)
            .await
            .unwrap();
        assert!(
            hits.is_empty(),
            "compensation must clean FTS index; got {hits:?}"
        );

        // No partial annotates edges must remain (first edge must have been deleted).
        let edges_from_t1 = rt
            .neighbors(
                &tok,
                t1.id,
                Direction::In,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        let edges_from_t2 = rt
            .neighbors(
                &tok,
                t2.id,
                Direction::In,
                None,
                Some(vec![EdgeRelation::Annotates]),
            )
            .await
            .unwrap();
        assert!(
            edges_from_t1.is_empty(),
            "compensation must delete the first annotates edge; got {edges_from_t1:?}"
        );
        assert!(
            edges_from_t2.is_empty(),
            "no second annotates edge must exist; got {edges_from_t2:?}"
        );
    }

    // ---- #232 soft-delete index cleanup tests ----

    #[tokio::test]
    async fn soft_delete_entity_removes_indexes() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let entity = rt
            .create_entity(
                &tok,
                "concept",
                None,
                "QuantumEntanglement",
                Some("unique FTS term xzqjwv for soft delete test"),
                None,
                vec![],
            )
            .await
            .unwrap();

        let ns = tok.namespace().as_str().to_string();

        let before = rt
            .text(&tok)
            .unwrap()
            .search(TextSearchRequest {
                query: "xzqjwv".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(TextFilter {
                    namespaces: vec![ns.clone()],
                    ..Default::default()
                }),
                top_k: 10,
                snippet_chars: 100,
            })
            .await
            .unwrap();
        assert!(
            before.iter().any(|h| h.subject_id == entity.id),
            "entity must be in FTS before soft-delete"
        );

        let deleted = rt.delete_entity(&tok, entity.id, false).await.unwrap();
        assert!(deleted, "soft delete must return true");

        let after = rt
            .text(&tok)
            .unwrap()
            .search(TextSearchRequest {
                query: "xzqjwv".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(TextFilter {
                    namespaces: vec![ns],
                    ..Default::default()
                }),
                top_k: 10,
                snippet_chars: 100,
            })
            .await
            .unwrap();
        assert!(
            after.iter().all(|h| h.subject_id != entity.id),
            "soft-deleted entity must be removed from FTS index"
        );
    }

    #[tokio::test]
    async fn soft_delete_note_removes_indexes() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let note = rt
            .create_note(
                &tok,
                "observation",
                None,
                "SpectralDecomposition unique term yvwkqz for soft delete test",
                Some(0.7),
                None,
                vec![],
            )
            .await
            .unwrap();

        let before = rt
            .search_notes(&tok, "yvwkqz", None, 10, None, false)
            .await
            .unwrap();
        assert!(
            before.iter().any(|h| h.note_id == note.id),
            "note must be in FTS before soft-delete"
        );

        let deleted = rt.delete_note(&tok, note.id, false).await.unwrap();
        assert!(deleted, "soft delete must return true");

        let after = rt
            .search_notes(&tok, "yvwkqz", None, 10, None, false)
            .await
            .unwrap();
        assert!(
            after.iter().all(|h| h.note_id != note.id),
            "soft-deleted note must be removed from FTS index"
        );
    }

    // F010 (CRIT): ADR-002 base endpoint allowlist — unlisted triples must fail closed.
    // Document->Document Extends is not in the ADR-002 table; current generic fallthrough accepts it.
    #[tokio::test]
    async fn link_extends_document_to_document_returns_invalid_input() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let d1 = rt
            .create_entity(&tok, "document", None, "DocA", None, None, vec![])
            .await
            .unwrap();
        let d2 = rt
            .create_entity(&tok, "document", None, "DocB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, d1.id, d2.id, EdgeRelation::Extends, 1.0, None)
            .await;
        assert!(
            result.is_err(),
            "F010: document->document Extends must be rejected by ADR-002 allowlist; \
             current generic entity fallthrough incorrectly accepts it"
        );
    }

    // F010 happy path: Concept->Concept Extends is in the ADR-002 allowlist and must succeed.
    #[tokio::test]
    async fn link_extends_concept_to_concept_succeeds() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "CA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "CB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "F010: concept->concept Extends must be allowed (ADR-002 allowlist)"
        );
    }

    // F012 (CRIT): CompetesWith is symmetric; reversed pair must deduplicate to one canonical row.
    // Current code stores both directions as distinct rows (no canonicalization).
    #[tokio::test]
    async fn link_symmetric_relation_canonicalizes_endpoint_order() {
        use khive_storage::EdgeFilter;
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "ConceptP", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "ConceptQ", None, None, vec![])
            .await
            .unwrap();
        // Link A->B then B->A with the same symmetric relation.
        rt.link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
            .await
            .unwrap();
        rt.link(&tok, b.id, a.id, EdgeRelation::CompetesWith, 1.0, None)
            .await
            .unwrap();
        let count = rt
            .graph(&tok)
            .unwrap()
            .count_edges(EdgeFilter::default())
            .await
            .unwrap();
        assert_eq!(
            count,
            1,
            "F012: CompetesWith is symmetric; A->B and B->A must deduplicate to one canonical row; \
             found {count} rows (canonicalization not yet implemented)"
        );
    }

    // F010 (ADR-002): Supersedes — positive tests for all 5 allowed entity kinds.
    #[tokio::test]
    async fn f010_supersedes_document_to_document_allowed() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "document", None, "DocA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "document", None, "DocB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "document->document Supersedes must be allowed (ADR-002:191), got {result:?}"
        );
    }

    #[tokio::test]
    async fn f010_supersedes_artifact_to_artifact_allowed() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "artifact", None, "ArtA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "artifact", None, "ArtB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "artifact->artifact Supersedes must be allowed (ADR-002:192), got {result:?}"
        );
    }

    #[tokio::test]
    async fn f010_supersedes_service_to_service_allowed() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "service", None, "SvcA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "service", None, "SvcB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "service->service Supersedes must be allowed (ADR-002:193), got {result:?}"
        );
    }

    #[tokio::test]
    async fn f010_supersedes_dataset_to_dataset_allowed() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "dataset", None, "DataA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "dataset", None, "DataB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "dataset->dataset Supersedes must be allowed (ADR-002:194), got {result:?}"
        );
    }

    // F010 (ADR-002): Supersedes — negative tests for rejected entity kinds.
    #[tokio::test]
    async fn f010_supersedes_project_to_project_rejected() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "project", None, "ProjA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "project", None, "ProjB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "project->project Supersedes must be rejected (not in ADR-002 allowlist), got {result:?}"
        );
    }

    #[tokio::test]
    async fn f010_supersedes_person_to_person_rejected() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "person", None, "Alice", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "person", None, "Bob", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "person->person Supersedes must be rejected (not in ADR-002 allowlist), got {result:?}"
        );
    }

    #[tokio::test]
    async fn f010_supersedes_org_to_org_rejected() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "org", None, "OrgA", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "org", None, "OrgB", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "org->org Supersedes must be rejected (not in ADR-002 allowlist), got {result:?}"
        );
    }

    // Fix 1: Supersedes entity→entity — same kind (concept→concept) must be allowed.
    #[tokio::test]
    async fn f010_supersedes_same_kind_entity_allowed() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "OldV", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "NewV", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(&tok, b.id, a.id, EdgeRelation::Supersedes, 1.0, None)
            .await;
        assert!(
            result.is_ok(),
            "concept->concept Supersedes must be allowed by ADR-002 allowlist, got {result:?}"
        );
    }

    // F161: ADR-009 target_backend invariant — all edges written through link() must have
    // target_backend = None because validate_edge_relation_endpoints already ensured the
    // target exists locally.
    #[tokio::test]
    async fn f161_link_always_writes_null_target_backend() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let edge = rt
            .link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
            .await
            .unwrap();
        assert!(
            edge.target_backend.is_none(),
            "ADR-009: target_backend must be None for locally-routed edges (F161); got {:?}",
            edge.target_backend
        );
    }

    // F161: link_many must also write null target_backend for all local edges.
    #[tokio::test]
    async fn f161_link_many_always_writes_null_target_backend() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        let c = rt
            .create_entity(&tok, "concept", None, "C", None, None, vec![])
            .await
            .unwrap();
        let specs = vec![
            LinkSpec {
                namespace: None,
                source_id: a.id,
                target_id: b.id,
                relation: EdgeRelation::Extends,
                weight: 1.0,
                metadata: None,
            },
            LinkSpec {
                namespace: None,
                source_id: a.id,
                target_id: c.id,
                relation: EdgeRelation::Enables,
                weight: 1.0,
                metadata: None,
            },
        ];
        let edges = rt.link_many(&tok, specs).await.unwrap();
        for edge in &edges {
            assert!(
                edge.target_backend.is_none(),
                "ADR-009: target_backend must be None for locally-routed edges in link_many (F161); got {:?}",
                edge.target_backend
            );
        }
    }

    // F012: symmetric relation neighbors — competes_with queried from the non-canonical
    // endpoint must still return results when direction=Out is requested.
    #[tokio::test]
    async fn f012_symmetric_neighbors_visible_from_both_endpoints() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let a = rt
            .create_entity(&tok, "concept", None, "A", None, None, vec![])
            .await
            .unwrap();
        let b = rt
            .create_entity(&tok, "concept", None, "B", None, None, vec![])
            .await
            .unwrap();
        // Link A→B competes_with; if A.id > B.id the edge is stored as B→A (canonical).
        rt.link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
            .await
            .unwrap();
        // Both endpoints should see the edge regardless of direction=Out.
        let from_a = rt
            .neighbors(
                &tok,
                a.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::CompetesWith]),
            )
            .await
            .unwrap();
        let from_b = rt
            .neighbors(
                &tok,
                b.id,
                Direction::Out,
                None,
                Some(vec![EdgeRelation::CompetesWith]),
            )
            .await
            .unwrap();
        assert_eq!(
            from_a.len(),
            1,
            "node A must see competes_with neighbor from Direction::Out (F012); got {from_a:?}"
        );
        assert_eq!(
            from_b.len(),
            1,
            "node B must see competes_with neighbor from Direction::Out (F012); got {from_b:?}"
        );
    }

    // Fix 1: Supersedes entity→entity — cross-kind (concept→document) must be rejected.
    #[tokio::test]
    async fn f010_supersedes_cross_kind_entity_rejected() {
        let rt = rt();
        let tok = NamespaceToken::local();
        let concept = rt
            .create_entity(&tok, "concept", None, "MyConcept", None, None, vec![])
            .await
            .unwrap();
        let doc = rt
            .create_entity(&tok, "document", None, "MyDoc", None, None, vec![])
            .await
            .unwrap();
        let result = rt
            .link(
                &tok,
                concept.id,
                doc.id,
                EdgeRelation::Supersedes,
                1.0,
                None,
            )
            .await;
        assert!(
            matches!(result, Err(RuntimeError::InvalidInput(_))),
            "concept->document Supersedes must be rejected by ADR-002 allowlist, got {result:?}"
        );
    }

    #[tokio::test]
    async fn delete_note_cross_namespace_returns_mismatch_error() {
        let rt = rt();
        let ns_a = NamespaceToken::for_namespace(Namespace::parse("ns-a").unwrap());
        let ns_b = NamespaceToken::for_namespace(Namespace::parse("ns-b").unwrap());
        let note = rt
            .create_note(
                &ns_a,
                "observation",
                None,
                "note in ns-a",
                Some(0.8),
                None,
                vec![],
            )
            .await
            .unwrap();

        // Attempt to delete from a different namespace must return NamespaceMismatch.
        let result = rt.delete_note(&ns_b, note.id, true).await;
        assert!(
            matches!(result.unwrap_err(), crate::RuntimeError::NamespaceMismatch { id } if id == note.id),
            "cross-namespace delete_note must return NamespaceMismatch with the note id"
        );

        // Note must still exist in ns-a after the failed cross-ns delete.
        let note_store = rt.notes(&ns_a).unwrap();
        let still_there = note_store.get_note(note.id).await.unwrap();
        assert!(
            still_there.is_some(),
            "note must survive cross-ns delete attempt"
        );
    }
}