khive-runtime 0.10.0

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
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
//! Integration tests for khive-runtime.
//!
//! Tests cover entity CRUD, graph operations, note memory, GQL query,
//! and namespace isolation using an in-memory runtime.

#[path = "../src/test_process.rs"]
mod test_process;

use khive_runtime::{KhiveRuntime, Namespace, RuntimeConfig};
use khive_storage::blob::ContentRef;
use khive_storage::types::{Direction, PageRequest, TraversalOptions, TraversalRequest};
use khive_storage::{BlobStore, EdgeRelation, Event, EventFilter, NewAttachment};
use khive_types::{EventKind, SubstrateKind};
use std::collections::BTreeSet;
use uuid::Uuid;

fn rt() -> KhiveRuntime {
    KhiveRuntime::memory().expect("in-memory runtime")
}

#[tokio::test]
async fn note_supports_link_endpoints_are_observed_as_target() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let source = rt
        .create_note(&tok, "observation", None, "source", None, None, vec![])
        .await
        .unwrap();
    let target = rt
        .create_note(&tok, "insight", None, "target", None, None, vec![])
        .await
        .unwrap();
    rt.link(
        &tok,
        source.id,
        target.id,
        EdgeRelation::Supports,
        1.0,
        None,
    )
    .await
    .unwrap();

    let link_events = rt
        .list_events(
            &tok,
            EventFilter {
                kinds: vec![EventKind::LinkCreated],
                ..EventFilter::default()
            },
            PageRequest::default(),
        )
        .await
        .unwrap();
    assert_eq!(link_events.items.len(), 1);
    let link_event = &link_events.items[0];
    assert_eq!(link_event.payload["source_kind"], "note");
    assert_eq!(link_event.payload["target_kind"], "note");

    let query = format!(
        "MATCH (ev)-[:observed_as_target]->(t) WHERE ev.id = '{}' RETURN t.id",
        link_event.id
    );
    let rows = rt.query(&tok, &query).await.unwrap();
    let observed_ids: BTreeSet<_> = rows
        .iter()
        .flat_map(|row| row.columns.iter())
        .filter_map(|column| match &column.value {
            khive_storage::types::SqlValue::Text(value) => Some(value.clone()),
            _ => None,
        })
        .collect();
    assert_eq!(rows.len(), 2);
    assert_eq!(
        observed_ids,
        BTreeSet::from([source.id.to_string(), target.id.to_string()])
    );
}

#[tokio::test]
async fn annotates_event_target_has_no_phantom_target_observation() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let note = rt
        .create_note(&tok, "observation", None, "annotation", None, None, vec![])
        .await
        .unwrap();
    let note_events = rt
        .list_events(
            &tok,
            EventFilter {
                kinds: vec![EventKind::NoteCreated],
                ..EventFilter::default()
            },
            PageRequest::default(),
        )
        .await
        .unwrap();
    assert_eq!(note_events.items.len(), 1);
    let event_target = note_events.items[0].id;
    rt.link(
        &tok,
        note.id,
        event_target,
        EdgeRelation::Annotates,
        1.0,
        None,
    )
    .await
    .unwrap();

    let link_events = rt
        .list_events(
            &tok,
            EventFilter {
                kinds: vec![EventKind::LinkCreated],
                ..EventFilter::default()
            },
            PageRequest::default(),
        )
        .await
        .unwrap();
    assert_eq!(link_events.items.len(), 1);
    let link_event = &link_events.items[0];
    assert_eq!(link_event.payload["source_kind"], "note");
    assert_eq!(link_event.payload["target_kind"], "event");

    let query = format!(
        "MATCH (ev)-[:observed_as_target]->(t) WHERE ev.id = '{}' RETURN t.id",
        link_event.id
    );
    let rows = rt.query(&tok, &query).await.unwrap();
    assert_eq!(rows.len(), 1);
    assert!(rows[0].columns.iter().any(|column| {
        matches!(&column.value, khive_storage::types::SqlValue::Text(value) if value == &note.id.to_string())
    }));
}

// =============================================================================
// Entity operations
// =============================================================================

#[tokio::test]
async fn entity_create_and_get_roundtrip() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let entity = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "LoRA",
            Some("Low-Rank Adaptation"),
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    let fetched = rt.get_entity(&tok, entity.id).await.unwrap();
    assert_eq!(fetched.id, entity.id);
    assert_eq!(fetched.name, "LoRA");
    assert_eq!(fetched.kind, "concept");
    assert_eq!(fetched.description.as_deref(), Some("Low-Rank Adaptation"));
}

#[tokio::test]
async fn entity_create_with_properties_and_tags() {
    let rt = rt();
    let research_tok = rt.authorize(Namespace::parse("research").unwrap()).unwrap();

    let props = serde_json::json!({"domain": "fine-tuning", "type": "technique"});
    let entity = rt
        .create_entity_with_embedding_report(
            &research_tok,
            "concept",
            None,
            "QLoRA",
            Some("Quantized LoRA"),
            Some(props.clone()),
            vec!["fine-tuning".to_string(), "quantization".to_string()],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    let fetched = rt.get_entity(&research_tok, entity.id).await.unwrap();
    assert_eq!(fetched.properties, Some(props));
    assert_eq!(fetched.tags, vec!["fine-tuning", "quantization"]);
}

#[tokio::test]
async fn entity_create_with_content_attachment_roundtrip() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let temp = tempfile::tempdir().unwrap();
    let blob_store = std::sync::Arc::new(
        khive_db::stores::blob::FsBlobStore::new(temp.path().to_path_buf(), 0).unwrap(),
    );
    rt.install_blob_store(blob_store.clone())
        .expect("install blob store");
    let content_ref = blob_store.put(b"asset bytes".to_vec()).await.unwrap();

    let entity = rt
        .create_entity_with_attachments(
            &tok,
            "artifact",
            Some("visual_asset"),
            "asset",
            None,
            None,
            vec![],
            vec![NewAttachment {
                role: "content".to_string(),
                content_ref: content_ref.clone(),
                media_type: None,
                size_bytes: Some(11),
            }],
        )
        .await
        .unwrap();

    let fetched = rt.get_entity(&tok, entity.id).await.unwrap();
    assert_eq!(fetched.content_ref.as_deref(), Some(content_ref.as_str()));
}

#[tokio::test]
async fn entity_create_with_content_attachment_rejects_unpublished_blob() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let temp = tempfile::tempdir().unwrap();
    rt.install_blob_store(std::sync::Arc::new(
        khive_db::stores::blob::FsBlobStore::new(temp.path().to_path_buf(), 0).unwrap(),
    ))
    .expect("install blob store");
    let missing = ContentRef::from_digest_bytes(&[7; 32]);

    let error = rt
        .create_entity_with_attachments(
            &tok,
            "artifact",
            Some("visual_asset"),
            "asset",
            None,
            None,
            vec![],
            vec![NewAttachment {
                role: "content".to_string(),
                content_ref: missing,
                media_type: None,
                size_bytes: None,
            }],
        )
        .await
        .expect_err("unpublished ref must fail");

    assert!(error.to_string().contains("requires a published blob"));
    assert!(rt
        .list_entities(&tok, None, None, 10, 0)
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn entity_list_by_kind() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    rt.create_entity_with_embedding_report(
        &tok,
        "concept",
        None,
        "FlashAttention",
        None,
        None,
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();
    rt.create_entity_with_embedding_report(&tok, "concept", None, "GQA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.create_entity_with_embedding_report(
        &tok,
        "document",
        None,
        "Attention Is All You Need",
        None,
        None,
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let concepts = rt
        .list_entities(&tok, Some("concept"), None, 50, 0)
        .await
        .unwrap();
    assert_eq!(concepts.len(), 2);
    assert!(concepts.iter().any(|e| e.name == "FlashAttention"));
    assert!(concepts.iter().any(|e| e.name == "GQA"));

    let docs = rt
        .list_entities(&tok, Some("document"), None, 50, 0)
        .await
        .unwrap();
    assert_eq!(docs.len(), 1);
    assert_eq!(docs[0].name, "Attention Is All You Need");

    let all = rt.list_entities(&tok, None, None, 50, 0).await.unwrap();
    assert_eq!(all.len(), 3);
}

#[tokio::test]
async fn entity_delete_soft() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let entity = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "to-delete", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    let deleted = rt.delete_entity(&tok, entity.id, false).await.unwrap();
    assert!(deleted);

    // Soft-deleted entity is not found via get_entity
    let fetched = rt.get_entity(&tok, entity.id).await;
    assert!(fetched.is_err());
}

#[tokio::test]
async fn entity_count_by_kind() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    for _ in 0..3 {
        rt.create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "concept-X",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    }
    for _ in 0..2 {
        rt.create_entity_with_embedding_report(&tok, "document", None, "doc-Y", None, None, vec![])
            .await
            .map(|(record, _report)| record)
            .unwrap();
    }

    let concept_count = rt.count_entities(&tok, Some("concept")).await.unwrap();
    let doc_count = rt.count_entities(&tok, Some("document")).await.unwrap();
    let total = rt.count_entities(&tok, None).await.unwrap();

    assert_eq!(concept_count, 3);
    assert_eq!(doc_count, 2);
    assert_eq!(total, 5);
}

// =============================================================================
// Graph operations
// =============================================================================

#[tokio::test]
async fn link_and_neighbors() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let lora = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "LoRA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let qlora = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "QLoRA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    rt.link(&tok, qlora.id, lora.id, EdgeRelation::VariantOf, 1.0, None)
        .await
        .unwrap();

    let hits = rt
        .neighbors(&tok, qlora.id, Direction::Out, None, None)
        .await
        .unwrap();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].node_id, lora.id);
    assert_eq!(hits[0].relation, EdgeRelation::VariantOf);
}

#[tokio::test]
async fn traverse_multi_hop() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "A", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "B", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let c = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "C", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

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

    let request = TraversalRequest {
        roots: vec![a.id],
        options: TraversalOptions {
            max_depth: 2,
            direction: Direction::Out,
            relations: Some(vec![EdgeRelation::Extends]),
            ..Default::default()
        },
        include_roots: false,
        include_properties: false,
        execution_budget: Default::default(),
    };

    let paths = rt.traverse(&tok, request).await.unwrap();
    assert!(!paths.is_empty());

    // All traversed nodes should be reachable from a
    let reachable_ids: Vec<Uuid> = paths
        .iter()
        .flat_map(|p| p.nodes.iter().map(|n| n.node_id))
        .collect();
    assert!(reachable_ids.contains(&b.id));
    assert!(reachable_ids.contains(&c.id));
}

/// The soft-deleted-node screen removes nodes after storage has already
/// summarised the path, so `total_weight` must be recomputed over what
/// survives. Here the heaviest neighbour is the one soft-deleted: the
/// response must not keep reporting a weight that only a screened-out node
/// ever had.
#[tokio::test]
async fn traverse_total_weight_excludes_soft_deleted_nodes() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "A", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let light = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "light", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let heavy = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "heavy", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    rt.link(&tok, a.id, light.id, EdgeRelation::Extends, 0.25, None)
        .await
        .unwrap();
    rt.link(&tok, a.id, heavy.id, EdgeRelation::Extends, 0.9, None)
        .await
        .unwrap();

    let request = || TraversalRequest {
        roots: vec![a.id],
        options: TraversalOptions {
            max_depth: 1,
            direction: Direction::Out,
            relations: Some(vec![EdgeRelation::Extends]),
            ..Default::default()
        },
        include_roots: false,
        include_properties: false,
        execution_budget: Default::default(),
    };

    let before = rt.traverse(&tok, request()).await.unwrap();
    assert_eq!(before.len(), 1);
    assert_eq!(
        before[0].total_weight, 0.9,
        "baseline: the heavy neighbour sets total_weight while it is visible"
    );

    rt.delete_entity(&tok, heavy.id, false).await.unwrap(); // soft delete

    let after = rt.traverse(&tok, request()).await.unwrap();
    assert_eq!(after.len(), 1);
    let ids: Vec<Uuid> = after[0].nodes.iter().map(|n| n.node_id).collect();
    assert!(
        !ids.contains(&heavy.id),
        "soft-deleted node must be screened"
    );
    assert_eq!(
        after[0].total_weight, 0.25,
        "total_weight must fall to the surviving neighbour's weight, not stay \
         at the soft-deleted node's 0.9"
    );
}

// =============================================================================
// Note (memory) operations
// =============================================================================

#[tokio::test]
async fn create_note_and_list_notes() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    rt.create_note(
        &tok,
        "observation",
        None,
        "LoRA is a fine-tuning technique",
        Some(0.9),
        None,
        vec![],
    )
    .await
    .unwrap();
    rt.create_note(
        &tok,
        "observation",
        None,
        "QLoRA uses quantization",
        Some(0.8),
        None,
        vec![],
    )
    .await
    .unwrap();
    rt.create_note(
        &tok,
        "question",
        None,
        "Review LoRA paper",
        Some(0.7),
        None,
        vec![],
    )
    .await
    .unwrap();

    let observations = rt
        .list_notes(&tok, Some("observation"), 50, 0)
        .await
        .unwrap();
    assert_eq!(observations.len(), 2);

    let questions = rt.list_notes(&tok, Some("question"), 50, 0).await.unwrap();
    assert_eq!(questions.len(), 1);
    assert_eq!(questions[0].content, "Review LoRA paper");

    let all = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert_eq!(all.len(), 3);
}

#[tokio::test]
async fn create_all_note_kinds() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    for kind in [
        "observation",
        "insight",
        "question",
        "decision",
        "reference",
        "head",
    ] {
        let content = if kind == "head" { "{}" } else { "content" };
        rt.create_note(&tok, kind, None, content, Some(0.5), None, vec![])
            .await
            .unwrap();
    }
    let all = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert_eq!(all.len(), 6);
}

// =============================================================================
// GQL query
// =============================================================================

#[tokio::test]
async fn query_via_gql() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Set up entities and edges
    let lora = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "LoRA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let qlora = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "QLoRA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, qlora.id, lora.id, EdgeRelation::VariantOf, 1.0, None)
        .await
        .unwrap();

    // Run a GQL traversal query
    let rows = rt
        .query(
            &tok,
            "MATCH (a:concept)-[e:variant_of]->(b:concept) RETURN a, e, b LIMIT 10",
        )
        .await
        .unwrap();

    assert_eq!(rows.len(), 1);
    // Verify row contains the expected column names
    let first_row = &rows[0];
    assert!(first_row.get("a_name").is_some() || first_row.get("a_kind").is_some());
}

// =============================================================================
// GQL inline property-map integer literals (issue #755)
//
// Properties are stored as JSON values; `number: 54` in the entity's props
// blob is a JSON number, so `json_extract` returns SQLite's INTEGER/REAL
// storage class for it. An inline `{number: 54}` match must bind a numeric
// parameter so the comparison actually compares equal; a quoted `{number:
// '54'}` is a deliberate string literal and must keep comparing against JSON
// strings only (it must not start matching the JSON number).
// =============================================================================

#[tokio::test]
async fn query_via_gql_inline_property_map_integer_literal_matches_json_number() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let props = serde_json::json!({"number": 54});
    rt.create_entity_with_embedding_report(
        &tok,
        "artifact",
        None,
        "PR #54",
        None,
        Some(props),
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let rows = rt
        .query(&tok, "MATCH (n:artifact {number: 54}) RETURN n")
        .await
        .unwrap();

    assert_eq!(
        rows.len(),
        1,
        "unquoted integer literal must match the JSON-number property"
    );
}

#[tokio::test]
async fn query_via_gql_inline_property_map_quoted_number_does_not_match_json_number() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let props = serde_json::json!({"number": 54});
    rt.create_entity_with_embedding_report(
        &tok,
        "artifact",
        None,
        "PR #54",
        None,
        Some(props),
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let rows = rt
        .query(&tok, "MATCH (n:artifact {number: '54'}) RETURN n")
        .await
        .unwrap();

    assert_eq!(
        rows.len(),
        0,
        "quoted string literal must not match a JSON-number property; \
         this is the decided behavior, not a residual bug"
    );
}

// =============================================================================
// GQL integer literal precision against real SQLite (issue #832)
//
// f64 cannot represent every i64 exactly past 2^53: 9007199254740993 (2^53+1)
// rounds to 9007199254740992.0 as a float. A JSON-number property storing the
// exact large value must still be matched by an inline-map or WHERE-equality
// integer literal, both of which now bind QueryValue::Integer instead of a
// lossy QueryValue::Float.
// =============================================================================

#[tokio::test]
async fn query_via_gql_inline_property_map_large_integer_matches_exact_json_number() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let props = serde_json::json!({"number": 9007199254740993i64});
    rt.create_entity_with_embedding_report(
        &tok,
        "artifact",
        None,
        "big",
        None,
        Some(props),
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let rows = rt
        .query(
            &tok,
            "MATCH (n:artifact {number: 9007199254740993}) RETURN n",
        )
        .await
        .unwrap();

    assert_eq!(
        rows.len(),
        1,
        "2^53+1 integer literal must match the exact JSON-number property, not round to 2^53"
    );
}

#[tokio::test]
async fn query_via_gql_where_equality_large_integer_matches_exact_json_number() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let props = serde_json::json!({"number": 9007199254740993i64});
    rt.create_entity_with_embedding_report(
        &tok,
        "artifact",
        None,
        "big",
        None,
        Some(props),
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let rows = rt
        .query(
            &tok,
            "MATCH (n:artifact) WHERE n.properties.number = 9007199254740993 RETURN n",
        )
        .await
        .unwrap();

    assert_eq!(rows.len(), 1);
}

#[tokio::test]
async fn query_via_gql_inline_property_map_i64_bounds_match_exact_json_number() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    for bound in [i64::MIN, i64::MAX] {
        let props = serde_json::json!({"number": bound});
        rt.create_entity_with_embedding_report(
            &tok,
            "artifact",
            None,
            "bound",
            None,
            Some(props),
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

        let rows = rt
            .query(
                &tok,
                &format!("MATCH (n:artifact {{number: {bound}}}) RETURN n"),
            )
            .await
            .unwrap();

        assert_eq!(
            rows.len(),
            1,
            "i64 bound {bound} must match its exact JSON-number property"
        );
    }
}

#[tokio::test]
async fn query_via_gql_where_equality_i64_bounds_match_exact_json_number() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    for bound in [i64::MIN, i64::MAX] {
        let props = serde_json::json!({"number": bound});
        rt.create_entity_with_embedding_report(
            &tok,
            "artifact",
            None,
            "bound",
            None,
            Some(props),
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

        let rows = rt
            .query(
                &tok,
                &format!("MATCH (n:artifact) WHERE n.properties.number = {bound} RETURN n"),
            )
            .await
            .unwrap();

        assert_eq!(
            rows.len(),
            1,
            "i64 bound {bound} must match its exact JSON-number property via WHERE equality"
        );
    }
}

// =============================================================================
// GQL query truncation warning (issue #777)
//
// The compiler cannot infer truncation from the requested LIMIT alone — it
// must observe whether a real (max_limit + 1)-th match exists. These tests
// exercise the full compile -> execute -> strip-sentinel -> warn pipeline
// against real result sets straddling the default 500-row cap.
// =============================================================================

/// Seed `n` concept entities into a fresh namespace and return the token.
async fn seed_concepts(rt: &KhiveRuntime, ns: &str, n: usize) -> khive_runtime::NamespaceToken {
    let tok = rt.authorize(Namespace::parse(ns).unwrap()).unwrap();
    for i in 0..n {
        rt.create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            &format!("seed-{i}"),
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    }
    tok
}

async fn gql_page(
    rt: &KhiveRuntime,
    token: &khive_runtime::NamespaceToken,
    query: &str,
    page_size: usize,
) -> khive_runtime::QueryResult {
    rt.query_with_metadata(
        token,
        query,
        khive_query::CompileOptions {
            max_limit: page_size,
            ..Default::default()
        },
    )
    .await
    .unwrap()
}

#[tokio::test]
async fn no_explicit_limit_under_and_at_cap_emits_no_warning() {
    let rt = rt();

    // 499 matches, no explicit LIMIT: below the cap, all rows returned, no warning.
    let tok_499 = seed_concepts(&rt, "trunc-499", 499).await;
    let result_499 = rt
        .query_with_metadata(
            &tok_499,
            "MATCH (a:concept) RETURN a",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(result_499.rows.len(), 499);
    assert!(
        result_499.warnings.is_empty(),
        "499 matches under the cap must not warn: {:?}",
        result_499.warnings
    );
    assert!(
        !result_499.truncated,
        "#1247: under the cap is not truncated"
    );

    // Exactly 500 matches, no explicit LIMIT: right at the cap, no truncation, no warning.
    let tok_500 = seed_concepts(&rt, "trunc-500", 500).await;
    let result_500 = rt
        .query_with_metadata(
            &tok_500,
            "MATCH (a:concept) RETURN a",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(result_500.rows.len(), 500);
    assert!(
        result_500.warnings.is_empty(),
        "exactly 500 matches must not warn (nothing was dropped): {:?}",
        result_500.warnings
    );
    assert!(
        !result_500.truncated,
        "#1247: exactly at the cap is not truncated (nothing was dropped)"
    );
}

#[tokio::test]
async fn no_explicit_limit_over_cap_warns_and_strips_sentinel() {
    let rt = rt();

    // 501 matches, no explicit LIMIT — this is issue #777's original silent-
    // truncation case: the cap is the only bound, and the compiler cannot know
    // ahead of time that a 501st row exists.
    let tok = seed_concepts(&rt, "trunc-501", 501).await;
    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(
        result.rows.len(),
        500,
        "sentinel row must be stripped; exactly max_limit rows must be returned"
    );
    assert_eq!(result.warnings.len(), 1, "warnings: {:?}", result.warnings);
    assert!(result.warnings[0].contains("500"), "{}", result.warnings[0]);
    assert!(
        result.warnings[0].contains("SKIP 500") && result.warnings[0].contains("next_offset"),
        "#1601: the warning must agree with the machine-readable GQL continuation: {}",
        result.warnings[0]
    );
    assert!(result.has_more);
    assert_eq!(result.next_offset, Some(500));
    assert!(
        result.truncated,
        "#1247: truncated must be the structural signal, independent of warnings text"
    );

    // The sentinel row must not leak into the returned set: every row must be
    // a distinct seeded entity.
    let names: std::collections::HashSet<_> = result
        .rows
        .iter()
        .filter_map(|r| match r.get("a_name") {
            Some(khive_storage::types::SqlValue::Text(s)) => Some(s.clone()),
            _ => None,
        })
        .collect();
    assert_eq!(names.len(), 500, "sentinel row must not leak into results");

    let final_page = gql_page(&rt, &tok, "MATCH (a:concept) RETURN a SKIP 500", 500).await;
    assert_eq!((final_page.offset, final_page.page_size), (500, 500));
    assert_eq!(
        final_page.rows.len(),
        1,
        "SKIP 500 must retrieve the 501st match"
    );
    assert!(!final_page.has_more && !final_page.truncated);
    assert_eq!(final_page.next_offset, None);
    let final_name = match final_page.rows[0].get("a_name") {
        Some(khive_storage::types::SqlValue::Text(name)) => name,
        other => panic!("final page must project the remaining entity name, got {other:?}"),
    };
    assert!(
        !names.contains(final_name),
        "the final page must not overlap the first 500 rows"
    );
}

#[tokio::test]
async fn explicit_limit_variants_against_501_matches() {
    let rt = rt();
    let tok = seed_concepts(&rt, "trunc-501-limits", 501).await;

    // LIMIT above the cap: the cap still binds, warning fires, sentinel stripped.
    let above_cap = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a LIMIT 600",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(above_cap.rows.len(), 500);
    assert_eq!(
        above_cap.warnings.len(),
        1,
        "LIMIT above cap with 501 real matches must warn: {:?}",
        above_cap.warnings
    );
    assert!(above_cap.warnings[0].contains("600"));
    assert!(above_cap.warnings[0].contains("500"));
    assert!(
        above_cap.truncated,
        "#1247: LIMIT above cap must set truncated"
    );

    // LIMIT exactly at the cap: the cap never binds (requested <= max_limit),
    // so no sentinel is fetched and no warning fires, even though 501 rows
    // actually match — the caller asked for exactly 500 and got exactly 500.
    let at_cap = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a LIMIT 500",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(at_cap.rows.len(), 500);
    assert!(
        at_cap.warnings.is_empty(),
        "LIMIT == cap must not warn: {:?}",
        at_cap.warnings
    );
    assert!(
        !at_cap.truncated,
        "#1247: an explicit LIMIT the caller chose is not server-side truncation"
    );

    // LIMIT below the cap: this is the false-positive regression
    // case (LIMIT above the requested value but under real matches would have
    // wrongly warned under the old requested-limit-only inference). Here the
    // requested LIMIT is under the cap, so it must never warn regardless of
    // how many rows actually match.
    let below_cap = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a LIMIT 100",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(below_cap.rows.len(), 100);
    assert!(
        below_cap.warnings.is_empty(),
        "LIMIT below cap must not warn: {:?}",
        below_cap.warnings
    );
    assert!(
        !below_cap.truncated,
        "#1247: LIMIT below cap is not truncated"
    );
}

#[tokio::test]
async fn explicit_limit_over_cap_with_few_real_matches_emits_no_warning() {
    let rt = rt();

    // Only 20 real matches, but the explicit LIMIT (600) exceeds the cap
    // (500). This is the false-positive regression case: the old
    // warn-whenever-LIMIT-exceeds-cap inference would have fired here even
    // though nothing was actually truncated. All 20 rows must come back and
    // no warning must fire.
    let tok = seed_concepts(&rt, "trunc-20-limit-over-cap", 20).await;
    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a LIMIT 600",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(result.rows.len(), 20);
    assert!(
        result.warnings.is_empty(),
        "LIMIT above cap with fewer real matches than the cap must not warn: {:?}",
        result.warnings
    );
    assert!(
        !result.truncated,
        "#1247: fewer real matches than the cap is not truncation"
    );
}

#[tokio::test]
async fn gql_skip_pages_are_deterministic_complete_and_machine_continuable() {
    let rt = rt();
    let tok = seed_concepts(&rt, "gql-pages-12", 12).await;

    let names = |result: &khive_runtime::QueryResult| {
        result
            .rows
            .iter()
            .filter_map(|row| match row.get("a_name") {
                Some(khive_storage::types::SqlValue::Text(name)) => Some(name.clone()),
                _ => None,
            })
            .collect::<Vec<_>>()
    };

    let first = gql_page(&rt, &tok, "MATCH (a:concept) RETURN a", 5).await;
    let first_repeat = gql_page(&rt, &tok, "MATCH (a:concept) RETURN a", 5).await;
    let second = gql_page(&rt, &tok, "MATCH (a:concept) RETURN a SKIP 5", 5).await;
    let third = gql_page(&rt, &tok, "MATCH (a:concept) RETURN a SKIP 10", 5).await;

    assert_eq!(
        names(&first),
        names(&first_repeat),
        "page order must be stable"
    );
    assert_eq!((first.offset, first.page_size), (0, 5));
    assert!(first.has_more && first.truncated);
    assert_eq!(first.next_offset, Some(5));
    assert!(
        first
            .warnings
            .iter()
            .any(|warning| warning.contains("SKIP 5")),
        "human guidance must agree with next_offset: {:?}",
        first.warnings
    );

    assert_eq!((second.offset, second.page_size), (5, 5));
    assert!(second.has_more && second.truncated);
    assert_eq!(second.next_offset, Some(10));

    assert_eq!((third.offset, third.page_size), (10, 5));
    assert!(!third.has_more && !third.truncated);
    assert_eq!(third.next_offset, None);
    assert_eq!(third.rows.len(), 2);

    let all_names = names(&first)
        .into_iter()
        .chain(names(&second))
        .chain(names(&third))
        .collect::<std::collections::HashSet<_>>();
    assert_eq!(
        all_names.len(),
        12,
        "paging must retrieve the full match set"
    );
}

#[tokio::test]
async fn gql_query_limit_composes_with_page_size() {
    let rt = rt();
    let tok = seed_concepts(&rt, "gql-page-limit-composition", 8).await;

    let caller_bounded = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a LIMIT 3",
            khive_query::CompileOptions {
                max_limit: 5,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(caller_bounded.rows.len(), 3);
    assert_eq!(caller_bounded.page_size, 3);
    assert!(!caller_bounded.has_more);
    assert_eq!(caller_bounded.next_offset, None);

    let server_bounded = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a LIMIT 8",
            khive_query::CompileOptions {
                max_limit: 5,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(server_bounded.rows.len(), 5);
    assert_eq!(server_bounded.page_size, 5);
    assert!(server_bounded.has_more);
    assert_eq!(server_bounded.next_offset, Some(5));

    // Continue to the terminal page: only 8 real matches exist and LIMIT is 8,
    // so SKIP 5 must return the remaining 3 rows and terminate.
    let terminal = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept) RETURN a SKIP 5 LIMIT 8",
            khive_query::CompileOptions {
                max_limit: 5,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(terminal.rows.len(), 3);
    assert!(!terminal.has_more);
    assert_eq!(terminal.next_offset, None);
}

/// Regression test for the round-1 review defect: an explicit query-text LIMIT
/// must compose with page_size as a TOTAL bound across every SKIP page, not a
/// page-local one (ADR-008 §"query LIMIT and page_size composition"). Seeds
/// more real matches than LIMIT so a page-local limit would leak rows past
/// LIMIT and keep reporting has_more=true, which is exactly the bug this test
/// pins down.
#[tokio::test]
async fn gql_query_limit_is_a_total_bound_across_skip_pages() {
    let rt = rt();
    let tok = seed_concepts(&rt, "gql-page-limit-total-bound", 20).await;

    let mut collected_ids = std::collections::HashSet::new();
    let mut page_counts = Vec::new();
    let mut offset = 0usize;
    loop {
        let page = gql_page(
            &rt,
            &tok,
            &format!("MATCH (a:concept) RETURN a SKIP {offset} LIMIT 8"),
            5,
        )
        .await;
        page_counts.push(page.rows.len());
        for row in &page.rows {
            if let Some(khive_storage::types::SqlValue::Text(id)) = row.get("a_id") {
                assert!(
                    collected_ids.insert(id.clone()),
                    "row {id} returned on more than one page"
                );
            }
        }
        match page.next_offset {
            Some(next) => {
                assert!(page.has_more);
                offset = next;
            }
            None => {
                assert!(!page.has_more, "terminal page must not claim has_more");
                break;
            }
        }
        assert!(
            page_counts.len() <= 10,
            "paging did not terminate: {page_counts:?}"
        );
    }

    assert_eq!(
        collected_ids.len(),
        8,
        "exactly LIMIT rows must be returned across all pages, not the 20 real matches"
    );
    assert_eq!(
        page_counts,
        vec![5, 3],
        "page sizes must respect the remaining LIMIT allowance, not a flat page_size"
    );

    // An offset at or beyond the query's own LIMIT is a terminal empty page,
    // never an error and never has_more.
    let past_limit = gql_page(&rt, &tok, "MATCH (a:concept) RETURN a SKIP 8 LIMIT 8", 5).await;
    assert_eq!(past_limit.rows.len(), 0);
    assert!(!past_limit.has_more);
    assert_eq!(past_limit.next_offset, None);

    let well_past_limit =
        gql_page(&rt, &tok, "MATCH (a:concept) RETURN a SKIP 20 LIMIT 8", 5).await;
    assert_eq!(well_past_limit.rows.len(), 0);
    assert!(!well_past_limit.has_more);
    assert_eq!(well_past_limit.next_offset, None);
}

// =============================================================================
// GQL static edge-pattern schema-mismatch hint (issue #593)
//
// A MATCH pattern that names an explicit relation and explicit entity kinds
// on both endpoints can be *statically* impossible under the composed edge
// endpoint contract (base allowlist + pack EDGE_RULES) — e.g. `precedes`
// never accepts concept->concept endpoints. Executed unchanged, this always
// returns zero rows, indistinguishable from "no data yet". These tests cover
// the warning that distinguishes the two cases, scoped to the exact cases
// where the emptiness is statically knowable.
// =============================================================================

#[tokio::test]
async fn query_static_impossible_pattern_precedes_concept_concept_warns_and_returns_empty() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Real `precedes` edges exist — just never between two concepts (issue
    // #593's repro: 3445 `precedes` edges in the wild, all document/project/etc).
    let d1 = rt
        .create_entity_with_embedding_report(&tok, "document", None, "Doc1", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let d2 = rt
        .create_entity_with_embedding_report(&tok, "document", None, "Doc2", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, d1.id, d2.id, EdgeRelation::Precedes, 1.0, None)
        .await
        .unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (n:concept)-[:precedes]->(m:concept) RETURN n.name, m.name LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert!(
        result.rows.is_empty(),
        "no concept->concept precedes edges exist: {:?}",
        result.rows
    );
    assert_eq!(result.warnings.len(), 1, "warnings: {:?}", result.warnings);
    let w = &result.warnings[0];
    assert!(w.contains("precedes"), "{w}");
    assert!(w.contains("concept"), "{w}");
    assert!(
        w.contains("document->document"),
        "must name an accepted pair for the relation: {w}"
    );
}

#[tokio::test]
async fn query_static_possible_pattern_extends_concept_concept_no_warning() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "LoRA2", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "QLoRA2", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, b.id, a.id, EdgeRelation::Extends, 1.0, None)
        .await
        .unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (n:concept)-[:extends]->(m:concept) RETURN n, m LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(
        result.rows.len(),
        1,
        "concept->concept is a valid base-contract pair for extends"
    );
    assert!(
        result.warnings.is_empty(),
        "a statically-valid pattern must not warn: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_check_skips_unlabeled_source_node() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // The source node is unlabeled — no static (kind, relation, kind) triple
    // is named, so this must never warn regardless of what `precedes` accepts.
    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (n)-[:precedes]->(m:document) RETURN n, m LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert!(
        result.warnings.is_empty(),
        "an unlabeled endpoint names no static triple to test: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_check_honors_pack_extended_endpoint_rules() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Mirrors khive-pack-kg's KG_EDGE_RULES: `person part_of org` is valid
    // only via a pack-declared rule, never the base allowlist alone. The hint
    // must consult the exact same composed rule set the link validator does.
    rt.install_edge_rules(vec![khive_types::EdgeEndpointRule {
        relation: EdgeRelation::PartOf,
        source: khive_types::EndpointKind::EntityOfKind("person"),
        target: khive_types::EndpointKind::EntityOfKind("org"),
    }]);

    let p = rt
        .create_entity_with_embedding_report(&tok, "person", None, "Ada", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let o = rt
        .create_entity_with_embedding_report(&tok, "org", None, "Acme", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, p.id, o.id, EdgeRelation::PartOf, 1.0, None)
        .await
        .unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (n:person)-[:part_of]->(m:org) RETURN n, m LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(result.rows.len(), 1);
    assert!(
        result.warnings.is_empty(),
        "a pack-declared endpoint rule must not be falsely flagged as impossible: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn link_and_hint_agree_special_relation_pack_rules_never_enforced() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // supersedes is a SPECIAL_RELATIONS entry (pack.rs): the live validator
    // resolves it in a dedicated branch (operations.rs) that only consults
    // base_entity_rule_allows, never pack_rule_allows. A pack rule for it must
    // therefore be inert on both paths: `link` must still reject the pair, and
    // the GQL static hint must still warn, even with the rule installed.
    rt.install_edge_rules(vec![khive_types::EdgeEndpointRule {
        relation: EdgeRelation::Supersedes,
        source: khive_types::EndpointKind::EntityOfKind("person"),
        target: khive_types::EndpointKind::EntityOfKind("person"),
    }]);

    let p1 = rt
        .create_entity_with_embedding_report(&tok, "person", None, "Old Ada", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let p2 = rt
        .create_entity_with_embedding_report(&tok, "person", None, "New Ada", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    let link_result = rt
        .link(&tok, p1.id, p2.id, EdgeRelation::Supersedes, 1.0, None)
        .await;
    assert!(
        link_result.is_err(),
        "person->person supersedes must be rejected: the special-relation branch \
         never consults the installed pack rule; got {link_result:?}"
    );

    let query_result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:person)-[:supersedes]->(b:person) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();
    assert_eq!(
        query_result.warnings.len(),
        1,
        "the hint must agree with the validator and warn even though a pack rule \
         is installed for this special relation: {:?}",
        query_result.warnings
    );
}

#[tokio::test]
async fn query_static_possible_pattern_inbound_introduced_by_no_warning() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let doc = rt
        .create_entity_with_embedding_report(&tok, "document", None, "Paper", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let author = rt
        .create_entity_with_embedding_report(&tok, "person", None, "Author", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(
        &tok,
        doc.id,
        author.id,
        EdgeRelation::IntroducedBy,
        1.0,
        None,
    )
    .await
    .unwrap();

    // Same (document, introduced_by, person) triple as the base allowlist, but
    // expressed with an inbound (`<-`) arrow instead of the outbound (`->`)
    // form used elsewhere: source is the right-hand node (document), target is
    // the left-hand node (person).
    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (p:person)<-[:introduced_by]-(d:document) RETURN d, p LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(result.rows.len(), 1);
    assert!(
        result.warnings.is_empty(),
        "an inbound-arrow pattern naming a valid base-contract triple must not warn: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_possible_pattern_entity_of_type_pack_rule_no_false_warning() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // theorem depends_on definition has no base-contract row (concept->concept
    // depends_on is not in BASE_ENTITY_ENDPOINT_RULES) — only the installed
    // EntityOfType pack rule makes it possible.
    rt.install_edge_rules(vec![khive_types::EdgeEndpointRule {
        relation: EdgeRelation::DependsOn,
        source: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "theorem",
        },
        target: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "definition",
        },
    }]);

    let thm = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            Some("theorem"),
            "T1",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let def = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            Some("definition"),
            "D1",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, thm.id, def.id, EdgeRelation::DependsOn, 1.0, None)
        .await
        .unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept {entity_type: 'theorem'})-[:depends_on]->\
             (b:concept {entity_type: 'definition'}) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(result.rows.len(), 1);
    assert!(
        result.warnings.is_empty(),
        "the hint must consult the pack's EntityOfType rule (matched against \
         each node's entity_type, not just its base kind) so this must not be \
         falsely flagged: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_possible_pattern_untyped_endpoints_with_entity_of_type_rule_no_false_warning()
{
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Same EntityOfType rule as the typed-pattern test above, but the pattern
    // here names no `entity_type` on either endpoint — just the base kind.
    // An untyped pattern endpoint has not ruled out any subtype, so the
    // installed theorem->definition rule still makes concept->concept
    // depends_on possible and this must not warn.
    rt.install_edge_rules(vec![khive_types::EdgeEndpointRule {
        relation: EdgeRelation::DependsOn,
        source: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "theorem",
        },
        target: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "definition",
        },
    }]);

    let thm = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            Some("theorem"),
            "T1",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let def = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            Some("definition"),
            "D1",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, thm.id, def.id, EdgeRelation::DependsOn, 1.0, None)
        .await
        .unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept)-[:depends_on]->(b:concept) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(
        result.rows.len(),
        1,
        "the stored theorem->definition edge must be returned: {:?}",
        result.rows
    );
    assert!(
        result.warnings.is_empty(),
        "an untyped pattern endpoint has not ruled out any entity_type, so it must not \
         be falsely flagged as impossible just because it names no entity_type filter: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_pattern_mismatching_entity_type_still_warns() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Same EntityOfType rule, but the pattern names an entity_type that does
    // NOT match the rule's source subtype ("lemma" vs the rule's "theorem")
    // — exact-match semantics must still apply and this must warn.
    rt.install_edge_rules(vec![khive_types::EdgeEndpointRule {
        relation: EdgeRelation::DependsOn,
        source: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "theorem",
        },
        target: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "definition",
        },
    }]);

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept {entity_type: 'lemma'})-[:depends_on]->\
             (b:concept {entity_type: 'definition'}) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(
        result.warnings.len(),
        1,
        "a pattern entity_type that mismatches the installed rule's subtype must still \
         be flagged as impossible: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_warning_accepted_pairs_include_entity_of_type_only_relation() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // depends_on has no base-contract person->person row (the base allowlist
    // only grants project/service/artifact/document pairs); the only way
    // concept->concept becomes accepted is the installed EntityOfType rule.
    // person->person stays impossible and must still warn, and the
    // accepted-pairs list in the warning text must surface the
    // EntityOfType-derived concept->concept pair rather than omitting it.
    rt.install_edge_rules(vec![khive_types::EdgeEndpointRule {
        relation: EdgeRelation::DependsOn,
        source: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "theorem",
        },
        target: khive_types::EndpointKind::EntityOfType {
            kind: "concept",
            entity_type: "definition",
        },
    }]);

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:person)-[:depends_on]->(b:person) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(result.warnings.len(), 1, "warnings: {:?}", result.warnings);
    assert!(
        result.warnings[0].contains("concept->concept"),
        "the accepted-pairs list must include the EntityOfType-derived concept->concept \
         pair for depends_on, not just base-allowlist pairs: {}",
        result.warnings[0]
    );
}

#[tokio::test]
async fn query_static_impossible_chained_pattern_warns_once_per_edge() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Two chained edges sharing node `b`, both statically impossible
    // (concept->concept precedes is never in the composed contract). Each
    // edge is scanned independently, so both must warn.
    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept)-[:precedes]->(b:concept)-[:precedes]->(c:concept) RETURN a, b, c LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert_eq!(
        result.warnings.len(),
        2,
        "a chained pattern with two statically-impossible edges sharing a node \
         must warn once per edge: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_check_skips_multi_relation_edge() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Two relations named on one edge — no single static triple to test, so
    // this must never warn even though neither relation accepts concept->concept.
    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept)-[:precedes|contains]->(b:concept) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert!(
        result.warnings.is_empty(),
        "a multi-relation edge names no single static triple to test: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_check_skips_variable_length_edge() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept)-[:precedes*1..2]->(b:concept) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert!(
        result.warnings.is_empty(),
        "a variable-length hop is not a single mandatory hop and must not warn: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_check_skips_undirected_edge() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (a:concept)-[:precedes]-(b:concept) RETURN a, b LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert!(
        result.warnings.is_empty(),
        "an undirected edge names no fixed (source, target) triple and must not warn: {:?}",
        result.warnings
    );
}

#[tokio::test]
async fn query_static_impossible_pattern_warning_exact_message() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let result = rt
        .query_with_metadata(
            &tok,
            "MATCH (n:concept)-[:precedes]->(m:concept) RETURN n, m LIMIT 10",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    // Exact-message pin (issue #593's public contract): this is a load-bearing
    // string once callers script against it, so pin the full text, not just a
    // substring, catching any accidental wording/ordering drift.
    assert_eq!(
        result.warnings,
        vec![
            "pattern (concept)-[:precedes]->(concept) can never match: 'precedes' does not \
             accept concept->concept endpoints; accepted source->target kinds for 'precedes': \
             document->document, dataset->dataset, project->project, artifact->artifact, \
             service->service"
                .to_string()
        ]
    );
}

#[tokio::test]
async fn query_static_impossible_check_skips_sparql() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let d1 = rt
        .create_entity_with_embedding_report(&tok, "document", None, "Doc1", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let d2 = rt
        .create_entity_with_embedding_report(&tok, "document", None, "Doc2", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok, d1.id, d2.id, EdgeRelation::Precedes, 1.0, None)
        .await
        .unwrap();

    // Same statically-impossible shape as the GQL case above (precedes
    // concept->concept), expressed in SPARQL — must never receive the hint.
    let result = rt
        .query_with_metadata(
            &tok,
            "SELECT ?a ?b WHERE { ?a :precedes ?b . ?a a :concept . ?b a :concept . }",
            khive_query::CompileOptions::default(),
        )
        .await
        .unwrap();

    assert!(
        result.warnings.is_empty(),
        "SPARQL must never receive the static GQL-pattern hint: {:?}",
        result.warnings
    );
}

// =============================================================================
// Namespace isolation
// =============================================================================

#[tokio::test]
async fn namespace_isolation() {
    let rt = rt();
    let ns_a_tok = rt.authorize(Namespace::parse("ns-a").unwrap()).unwrap();
    let ns_b_tok = rt.authorize(Namespace::parse("ns-b").unwrap()).unwrap();

    rt.create_entity_with_embedding_report(
        &ns_a_tok,
        "concept",
        None,
        "EntityA",
        None,
        None,
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();
    rt.create_entity_with_embedding_report(
        &ns_b_tok,
        "concept",
        None,
        "EntityB",
        None,
        None,
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let a_entities = rt
        .list_entities(&ns_a_tok, None, None, 50, 0)
        .await
        .unwrap();
    assert_eq!(a_entities.len(), 1);
    assert_eq!(a_entities[0].name, "EntityA");

    let b_entities = rt
        .list_entities(&ns_b_tok, None, None, 50, 0)
        .await
        .unwrap();
    assert_eq!(b_entities.len(), 1);
    assert_eq!(b_entities[0].name, "EntityB");
}

// =============================================================================
// Hybrid search indexing
// =============================================================================

#[tokio::test]
async fn create_entity_indexes_into_text_search() {
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "FlashAttention",
            Some("efficient attention mechanism"),
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let hits = rt
        .hybrid_search(&tok, "FlashAttention", None, 10, None, None, &[], None)
        .await
        .unwrap();
    assert!(
        hits.iter().any(|h| h.entity_id == entity.id),
        "newly created entity should be findable via hybrid_search (text path)"
    );
}

#[tokio::test]
async fn create_entity_no_embedding_model_does_not_propagate_vector_error() {
    // KhiveRuntime::memory() has embedding_model: None — vector indexing is silently skipped.
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let result = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "SilentVectorSkip",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record);
    assert!(
        result.is_ok(),
        "create_entity must not propagate Unconfigured from vector store"
    );
}

// =============================================================================
// Soft-delete visibility
// =============================================================================

/// Soft-deleted entities must not appear in hybrid_search results.
#[tokio::test]
async fn hybrid_search_excludes_soft_deleted_entities() {
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "SoftDeleteMe",
            Some("entity that will be soft-deleted"),
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // Confirm the entity is visible before deletion.
    let hits_before = rt
        .hybrid_search(&tok, "SoftDeleteMe", None, 10, None, None, &[], None)
        .await
        .unwrap();
    assert!(
        hits_before.iter().any(|h| h.entity_id == entity.id),
        "entity should appear in hybrid_search before soft-delete"
    );

    rt.delete_entity(&tok, entity.id, false).await.unwrap(); // soft delete

    let hits_after = rt
        .hybrid_search(&tok, "SoftDeleteMe", None, 10, None, None, &[], None)
        .await
        .unwrap();
    assert!(
        !hits_after.iter().any(|h| h.entity_id == entity.id),
        "soft-deleted entity must not appear in hybrid_search"
    );
}

/// Hard-deleted entities are gone from storage entirely and never appear in hybrid_search.
#[tokio::test]
async fn hybrid_search_excludes_hard_deleted_entities() {
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "HardDeleteMe",
            Some("entity that will be hard-deleted"),
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    let hits_before = rt
        .hybrid_search(&tok, "HardDeleteMe", None, 10, None, None, &[], None)
        .await
        .unwrap();
    assert!(
        hits_before.iter().any(|h| h.entity_id == entity.id),
        "entity should appear in hybrid_search before hard-delete"
    );

    rt.delete_entity(&tok, entity.id, true).await.unwrap(); // hard delete

    // Hard-deleted rows are gone from the entity store; the FTS/vector indexes may still
    // have stale entries. The soft-delete filter sees no alive entity and drops the hit.
    let hits_after = rt
        .hybrid_search(&tok, "HardDeleteMe", None, 10, None, None, &[], None)
        .await
        .unwrap();
    assert!(
        !hits_after.iter().any(|h| h.entity_id == entity.id),
        "hard-deleted entity must not appear in hybrid_search"
    );
}

/// Soft-deleted notes must not appear in list_notes results.
#[tokio::test]
async fn list_notes_excludes_soft_deleted() {
    use khive_storage::types::DeleteMode;

    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let note = rt
        .create_note(
            &tok,
            "observation",
            None,
            "soft-delete-test",
            Some(0.9),
            None,
            vec![],
        )
        .await
        .unwrap();

    let notes_before = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert!(
        notes_before.iter().any(|n| n.id == note.id),
        "note should appear before soft-delete"
    );

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

    let notes_after = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert!(
        !notes_after.iter().any(|n| n.id == note.id),
        "soft-deleted note must not appear in list"
    );
}

// =============================================================================
// File-backed runtime
// =============================================================================

#[tokio::test]
async fn file_backed_runtime_persists() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("persist.db");

    {
        let config = RuntimeConfig {
            wal_ceiling_bytes: 0,
            wal_ceiling_configured_bytes: 0,
            wal_ceiling_source: Default::default(),
            wal_ceiling_env_raw: None,
            web: Default::default(),
            telemetry: Default::default(),
            mounts: Vec::new(),
            brain: Default::default(),
            git_write: Default::default(),
            display_timezone: chrono_tz::Tz::UTC,
            events_split: None,
            db_path: Some(path.clone()),
            blob_hydration_bytes: khive_runtime::DEFAULT_BLOB_HYDRATION_BYTES,
            default_namespace: Namespace::local(),
            embedding_model: None,
            gate: std::sync::Arc::new(khive_runtime::AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            additional_embedding_models: vec![],
            brain_profile: None,
            visible_namespaces: vec![],
            allowed_outbound_namespaces: vec![],
            actor_id: None,
            exec: Default::default(),
            ..khive_runtime::RuntimeConfig::no_embeddings()
        };
        let rt = KhiveRuntime::new_for_test(config).unwrap();
        let tok = rt.authorize(Namespace::local()).unwrap();
        rt.create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Persistent",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    }

    // Re-open the same file
    {
        let config = RuntimeConfig {
            wal_ceiling_bytes: 0,
            wal_ceiling_configured_bytes: 0,
            wal_ceiling_source: Default::default(),
            wal_ceiling_env_raw: None,
            web: Default::default(),
            telemetry: Default::default(),
            mounts: Vec::new(),
            brain: Default::default(),
            git_write: Default::default(),
            display_timezone: chrono_tz::Tz::UTC,
            events_split: None,
            db_path: Some(path.clone()),
            blob_hydration_bytes: khive_runtime::DEFAULT_BLOB_HYDRATION_BYTES,
            default_namespace: Namespace::local(),
            embedding_model: None,
            gate: std::sync::Arc::new(khive_runtime::AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            additional_embedding_models: vec![],
            brain_profile: None,
            visible_namespaces: vec![],
            allowed_outbound_namespaces: vec![],
            actor_id: None,
            exec: Default::default(),
            ..khive_runtime::RuntimeConfig::no_embeddings()
        };
        let rt = KhiveRuntime::new_for_test(config).unwrap();
        let tok = rt.authorize(Namespace::local()).unwrap();
        let entities = rt.list_entities(&tok, None, None, 50, 0).await.unwrap();
        assert_eq!(entities.len(), 1);
        assert_eq!(entities[0].name, "Persistent");
    }
}

// =============================================================================
// F218 integration: synthetic observed_as_* edge end-to-end (CRIT-1 regression)
// =============================================================================

/// This test is the ONLY test that would have caught CRIT-1 (wrong JOIN target).
///
/// It seeds a real event + event_observations row and executes the canonical
/// ADR-041 §11 synthetic-edge GQL query end-to-end against an in-memory SQLite
/// database.  The old code joined `event_observations.event_id = entities.id`,
/// which can never match because the two ID spaces are disjoint.
#[tokio::test]
async fn synthetic_edge_observed_as_selected_returns_memory_note() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let ns = "local";

    // Step 1: create a memory note (the observed entity).
    let memory_note = rt
        .create_note(
            &tok,
            "memory",
            None,
            "recalled memory content",
            Some(0.9),
            None,
            vec![],
        )
        .await
        .unwrap();
    let memory_id = memory_note.id;

    // Step 2: create an event of kind SearchExecuted with a payload that
    // includes `selected: [memory_id]`.  The storage layer's `append_event`
    // routes `SearchExecuted` to `decode_search_observations`, which requires
    // the `result_kind` discriminator (`entity` | `note`) to identify which
    // substrate owns every UUID in `candidates` and `selected`, then inserts a
    // row into `event_observations` with role="selected" and
    // entity_id=memory_id. (`selected` is part of `SearchExecuted`/
    // `RecallExecuted`'s ADR-041 projection contract; `RecallExecuted` still
    // decodes via `decode_recall_observations` from flat note UUID lists,
    // unlike `RerankExecuted`, which projects `selected` rows from
    // `final_scores`/`reranked` instead, since its typed payload has no
    // `selected` field.)
    let event_store = rt.events(&tok).unwrap();
    let mut event = Event::new(
        ns,
        "search",
        EventKind::SearchExecuted,
        SubstrateKind::Note,
        "agent:test",
    );
    event.payload = serde_json::json!({
        "result_kind": "note",
        "candidates": [],
        "selected": [memory_id.to_string()]
    });
    event_store.append_event(event).await.unwrap();

    // Step 3: execute the canonical ADR-041 §11 GQL query.
    // Before CRIT-1 fix: `FROM entities n0 JOIN event_observations e0 ON e0.event_id = n0.id`
    //   — IDs are disjoint, so zero rows returned.
    // After fix: `FROM events n0 JOIN event_observations e0 ON e0.event_id = n0.id`
    //   — correct join; the memory note is returned.
    let rows = rt
        .query(
            &tok,
            "MATCH (ev)-[:observed_as_selected]->(m:memory) RETURN m",
        )
        .await
        .unwrap();

    assert!(
        !rows.is_empty(),
        "CRIT-1: synthetic edge query must return at least one row (memory note was seeded); \
         got 0 rows — event_observations join is broken"
    );

    // Verify the returned row contains our memory note's UUID.
    let memory_id_str = memory_id.to_string();
    let found = rows.iter().any(|row| {
        row.columns.iter().any(|col| {
            if let khive_storage::types::SqlValue::Text(s) = &col.value {
                s.contains(&memory_id_str)
            } else {
                false
            }
        })
    });
    assert!(
        found,
        "CRIT-1: returned rows must include the seeded memory note id {}; columns: {:?}",
        memory_id,
        rows.iter()
            .map(|r| r
                .columns
                .iter()
                .map(|c| (&c.name, &c.value))
                .collect::<Vec<_>>())
            .collect::<Vec<_>>()
    );
}

// =============================================================================
// update_edge conflict handling regression tests
// =============================================================================

/// Regression for Bug 1: when update_edge absorbs a conflict (the requested edge
/// is deleted and the existing canonical row is preserved unchanged, ADR-039 DO
/// NOTHING), the returned edge must carry the SURVIVING canonical row's id — not
/// the id of the deleted edge.
///
/// Setup: pre-create canonical A→B competes_with (E1), create A→B extends (E2).
/// Update E2's relation to competes_with. The returned id must be E1, not E2.
/// A subsequent get(returned_id) must succeed.
#[tokio::test]
async fn update_edge_returns_surviving_canonical_id_on_conflict() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "SurvA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "SurvB", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // E1: canonical competes_with between A and B (runtime canonicalises order).
    let e1 = rt
        .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
        .await
        .unwrap();

    // E2: non-symmetric extends edge, using the higher-uuid as source so that
    // updating to competes_with will trigger a flip (endpoints_flipped=true path).
    let (src, tgt) = if a.id > b.id {
        (a.id, b.id)
    } else {
        (b.id, a.id)
    };
    let e2 = rt
        .link(&tok, src, tgt, EdgeRelation::Extends, 0.5, None)
        .await
        .unwrap();

    // E1 and E2 must be different edges.
    assert_ne!(
        e1.id, e2.id,
        "pre-condition: E1 and E2 must be distinct edges"
    );

    // Update E2 to competes_with → conflict with E1 must be absorbed.
    let returned = rt
        .update_edge(
            &tok,
            e2.id.into(),
            EdgePatch {
                relation: Some(EdgeRelation::CompetesWith),
                weight: Some(0.9),
                ..Default::default()
            },
        )
        .await
        .expect("update_edge must succeed even when conflict is absorbed");

    // Bug 1 assertion: returned id must be E1 (surviving canonical row), not E2 (deleted).
    assert_eq!(
        returned.id, e1.id,
        "Bug 1: update_edge must return the SURVIVING canonical row id (E1={:?}), \
         got E2={:?}",
        e1.id, returned.id
    );

    // get(returned.id) must succeed — it must not 404.
    let fetched = rt
        .get_edge(&tok, returned.id.into())
        .await
        .expect("get_edge on returned id must not error")
        .expect("get_edge on returned id must find a row (not 404)");
    assert_eq!(
        fetched.id, e1.id,
        "fetched row id must match E1 (surviving canonical)"
    );

    // E2 must no longer exist.
    let e2_lookup = rt
        .get_edge(&tok, e2.id.into())
        .await
        .expect("get_edge on deleted id must not error");
    assert!(
        e2_lookup.is_none(),
        "Bug 1: deleted edge E2 must not be findable after conflict absorption"
    );
}

/// Regression for Bug 2: when an edge's relation is updated to a symmetric relation
/// and the endpoints are ALREADY in canonical order (endpoints_flipped=false),
/// a pre-existing canonical row with the same natural key must still be detected and
/// absorbed — no UNIQUE-constraint error, no duplicate row.
///
/// Setup: ensure A < B (canonical order). Pre-create canonical A→B competes_with (E1).
/// Create A→B extends (E2, already canonical since A < B and extends is non-symmetric).
/// Update E2's relation to competes_with (endpoints_flipped=false because A < B).
/// Assert: exactly one live competes_with edge remains between A and B.
#[tokio::test]
async fn update_edge_canonical_orientation_conflict() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "CanOrA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "CanOrB", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // Determine canonical order: canon_lo < canon_hi.
    let (canon_lo, canon_hi) = if a.id < b.id {
        (a.id, b.id)
    } else {
        (b.id, a.id)
    };

    // E1: canonical competes_with (lower → higher, which is canonical).
    let e1 = rt
        .link(
            &tok,
            canon_lo,
            canon_hi,
            EdgeRelation::CompetesWith,
            1.0,
            None,
        )
        .await
        .unwrap();

    // E2: extends in the same canonical direction (lower → higher).
    // endpoints_flipped will be false when we update to competes_with.
    let e2 = rt
        .link(&tok, canon_lo, canon_hi, EdgeRelation::Extends, 0.5, None)
        .await
        .unwrap();

    assert_ne!(
        e1.id, e2.id,
        "pre-condition: E1 and E2 must be distinct edges"
    );

    // Update E2's relation to competes_with — must not produce UNIQUE-constraint error.
    // Bug 2: the non-flipped path used to call upsert_edge which only checked ON CONFLICT(id),
    // missing the natural-key duplicate with a different id.
    rt.update_edge(
        &tok,
        e2.id.into(),
        EdgePatch {
            relation: Some(EdgeRelation::CompetesWith),
            ..Default::default()
        },
    )
    .await
    .expect("Bug 2: update_edge on canonical-orientation conflict must not error");

    // Verify exactly one live competes_with edge exists between canon_lo and canon_hi.
    let edges = rt
        .list_edges(
            &tok,
            khive_runtime::EdgeListFilter {
                source_id: Some(canon_lo),
                target_id: Some(canon_hi),
                relations: vec![EdgeRelation::CompetesWith],
                ..Default::default()
            },
            100,
            0,
        )
        .await
        .expect("list_edges must succeed");

    assert_eq!(
        edges.len(),
        1,
        "Bug 2: exactly one competes_with edge must exist after non-flipped conflict absorption; \
         found {} edges: {edges:?}",
        edges.len()
    );
}

// =============================================================================
// Secret gate: structured-field bypass regression (#83)
// =============================================================================

#[tokio::test]
async fn entity_create_blocks_secret_in_properties() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    // A fake AWS key embedded in entity properties — must be blocked.
    let props = serde_json::json!({ "api_key": "AKIAFAKEKEY1234567890" });
    let result = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "TestEntity",
            None,
            Some(props),
            vec![],
        )
        .await
        .map(|(record, _report)| record);
    assert!(
        result.is_err(),
        "entity create with secret in properties must be blocked"
    );
    assert!(
        matches!(
            result.unwrap_err(),
            khive_runtime::RuntimeError::SecretDetected(_)
        ),
        "error must be SecretDetected"
    );
}

#[tokio::test]
async fn entity_create_blocks_secret_in_tags() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let tags = vec![
        "type:concept".to_string(),
        "AKIAFAKEKEY1234567890".to_string(),
    ];
    let result = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "TestEntity", None, None, tags)
        .await
        .map(|(record, _report)| record);
    assert!(
        result.is_err(),
        "entity create with secret in tags must be blocked"
    );
    assert!(
        matches!(
            result.unwrap_err(),
            khive_runtime::RuntimeError::SecretDetected(_)
        ),
        "error must be SecretDetected"
    );
}

#[tokio::test]
async fn note_create_blocks_secret_in_properties() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let props = serde_json::json!({ "api_key": "AKIAFAKEKEY1234567890" });
    let result = rt
        .create_note(
            &tok,
            "observation",
            None,
            "Safe content",
            None,
            Some(props),
            vec![],
        )
        .await;
    assert!(
        result.is_err(),
        "note create with secret in properties must be blocked"
    );
    assert!(
        matches!(
            result.unwrap_err(),
            khive_runtime::RuntimeError::SecretDetected(_)
        ),
        "error must be SecretDetected"
    );
}

// Regression: pure-hex credential in trigger context must be blocked.
// Pure hex cannot reach entropy threshold (hex max 4.0 < 4.5), so the
// secret gate must detect it via the hex-credential-token path.  This
// test exercises the MCP-reachable write path (create_note → create_note_inner
// → secret_gate::check) to confirm persistence is blocked end-to-end.
#[tokio::test]
async fn note_create_blocks_hex_credential_in_content() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    // 32-char pure hex near the phrase "api key" in the note body.
    let content = "api key 4f9c2e8a1d3b5c7e9f0a2b4d6e8c0a2b"; // gitleaks:allow
    let result = rt
        .create_note(&tok, "observation", None, content, None, None, vec![])
        .await;
    assert!(
        result.is_err(),
        "note create with hex credential in content must be blocked; got Ok"
    );
    assert!(
        matches!(
            result.unwrap_err(),
            khive_runtime::RuntimeError::SecretDetected(_)
        ),
        "error must be SecretDetected"
    );
}

#[tokio::test]
async fn note_create_allows_source_path_near_ordinary_key_prose() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let content = "see <a/path/to/file.py>:~97-103 lists it as a real checkpoint-supplied key";

    rt.create_note(&tok, "question", None, content, None, None, vec![])
        .await
        .expect("source path in technical prose must be stored");
}

#[tokio::test]
async fn note_create_allows_git_revision_near_ordinary_token_prose() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let content = "revision d362950a3c9b1a4cb47d97f1623e38f1a1e6bcdf emits one extra token";

    rt.create_note(&tok, "question", None, content, None, None, vec![])
        .await
        .expect("git revision in technical prose must be stored");
}

#[tokio::test]
async fn note_create_blocks_forty_hex_in_value_syntax_behind_vcs_marker() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let content = "api key value is commit d362950a3c9b1a4cb47d97f1623e38f1a1e6bcdf";

    let result = rt
        .create_note(&tok, "question", None, content, None, None, vec![])
        .await;
    assert!(
        matches!(
            result.unwrap_err(),
            khive_runtime::RuntimeError::SecretDetected(_)
        ),
        "a credential phrase must not be rescued by a VCS marker at the write path"
    );
}

#[tokio::test]
async fn note_create_blocks_path_dressed_base64_credential_in_value_syntax() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let content = "api key value is <Xk9mZ2vQpLrT8nJwYuA/HfBsDcGiONvMabcdefgh>:~97-103";

    let result = rt
        .create_note(&tok, "question", None, content, None, None, vec![])
        .await;
    assert!(
        matches!(
            result.unwrap_err(),
            khive_runtime::RuntimeError::SecretDetected(_)
        ),
        "path dressing must not rescue a credential in value syntax at the write path"
    );
}

// =============================================================================
// EmbedderRegistry integration tests
// =============================================================================

mod embedder_registry_tests {
    use async_trait::async_trait;
    use khive_gate::AllowAllGate;
    use khive_runtime::{
        EmbedderProvider, KhiveRuntime, NamespaceToken, PackRuntime, RequestIdentity,
        RuntimeConfig, RuntimeError, VerbRegistry, VerbRegistryBuilder,
    };
    use khive_types::{HandlerDef, Namespace, Pack, VerbCategory, Visibility};
    use lattice_embed::{EmbeddingModel, EmbeddingService};
    use serde_json::Value;
    use std::sync::Arc;

    // ── MockEmbedderProvider ─────────────────────────────────────────────────

    /// A synthetic embedding provider that returns a fixed vector of `42.0` values.
    ///
    /// Used to verify that custom providers are reachable via
    /// `KhiveRuntime::embedder` after registration.
    struct MockEmbedderProvider {
        name: String,
        dims: usize,
    }

    impl MockEmbedderProvider {
        fn new(name: &str, dims: usize) -> Self {
            Self {
                name: name.to_owned(),
                dims,
            }
        }
    }

    struct MockEmbeddingService {
        dims: usize,
    }

    #[async_trait]
    impl EmbeddingService for MockEmbeddingService {
        async fn embed(
            &self,
            texts: &[String],
            _model: EmbeddingModel,
        ) -> Result<Vec<Vec<f32>>, lattice_embed::EmbedError> {
            Ok(texts.iter().map(|_| vec![42.0_f32; self.dims]).collect())
        }

        fn supports_model(&self, _model: EmbeddingModel) -> bool {
            true
        }

        fn name(&self) -> &'static str {
            "mock-embedding-service"
        }
    }

    #[async_trait]
    impl EmbedderProvider for MockEmbedderProvider {
        fn name(&self) -> &str {
            &self.name
        }

        fn dimensions(&self) -> usize {
            self.dims
        }

        async fn build(&self) -> Result<Arc<dyn EmbeddingService>, RuntimeError> {
            tokio::time::sleep(std::time::Duration::from_millis(1)).await;
            Ok(Arc::new(MockEmbeddingService { dims: self.dims }))
        }
    }

    struct EmbedderInitPack {
        runtime: KhiveRuntime,
    }

    impl Pack for EmbedderInitPack {
        const NAME: &'static str = "embedder-init-test";
        const NOTE_KINDS: &'static [&'static str] = &[];
        const ENTITY_KINDS: &'static [&'static str] = &["concept"];
        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
            name: "initialize_embedder",
            description: "initialize the test embedder",
            visibility: Visibility::Verb,
            category: VerbCategory::Commissive,
            params: &[],
        }];
    }

    #[async_trait]
    impl PackRuntime for EmbedderInitPack {
        fn name(&self) -> &str {
            Self::NAME
        }

        fn note_kinds(&self) -> &'static [&'static str] {
            Self::NOTE_KINDS
        }

        fn entity_kinds(&self) -> &'static [&'static str] {
            Self::ENTITY_KINDS
        }

        fn handlers(&self) -> &'static [HandlerDef] {
            Self::HANDLERS
        }

        async fn dispatch(
            &self,
            _verb: &str,
            _params: Value,
            _registry: &VerbRegistry,
            token: &NamespaceToken,
        ) -> Result<Value, RuntimeError> {
            self.runtime
                .create_entity_with_embedding_report(
                    token,
                    "concept",
                    None,
                    "embedder initialization trigger",
                    None,
                    None,
                    vec![],
                )
                .await
                .map(|(record, _report)| record)?;
            Ok(Value::Null)
        }
    }

    fn memory_rt_no_model() -> KhiveRuntime {
        KhiveRuntime::new(RuntimeConfig {
            wal_ceiling_bytes: 0,
            wal_ceiling_configured_bytes: 0,
            wal_ceiling_source: Default::default(),
            wal_ceiling_env_raw: None,
            web: Default::default(),
            telemetry: Default::default(),
            mounts: Vec::new(),
            brain: Default::default(),
            git_write: Default::default(),
            display_timezone: chrono_tz::Tz::UTC,
            events_split: None,
            db_path: None,
            blob_hydration_bytes: khive_runtime::DEFAULT_BLOB_HYDRATION_BYTES,
            default_namespace: Namespace::local(),
            embedding_model: None,
            additional_embedding_models: vec![],
            gate: Arc::new(AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            brain_profile: None,
            visible_namespaces: vec![],
            allowed_outbound_namespaces: vec![],
            actor_id: None,
            exec: Default::default(),
            ..khive_runtime::RuntimeConfig::no_embeddings()
        })
        .expect("in-memory runtime")
    }

    // ── Test: register + embedder round-trip ─────────────────────────────────

    #[tokio::test]
    async fn register_embedder_and_retrieve_via_embedder_method() {
        let rt = memory_rt_no_model();
        rt.register_embedder(MockEmbedderProvider::new("mock", 384));

        let service = rt
            .embedder("mock")
            .await
            .expect("embedder lookup must succeed after registration");

        let texts = vec!["hello world".to_string()];
        let vecs = service
            .embed(&texts, EmbeddingModel::AllMiniLmL6V2)
            .await
            .expect("mock service must embed successfully");

        assert_eq!(vecs.len(), 1);
        assert_eq!(vecs[0].len(), 384);
        assert!(
            vecs[0].iter().all(|&v| (v - 42.0_f32).abs() < 1e-6),
            "mock service must return constant 42.0 vector"
        );
    }

    // ── Test: registered names include custom provider ────────────────────────

    #[tokio::test]
    async fn embedder_initialization_writes_event() {
        let rt = memory_rt_no_model();
        let token = rt
            .authorize(Namespace::local())
            .expect("authorize local namespace");
        let event_store = rt.events(&token).expect("event store must be available");
        rt.register_embedder(MockEmbedderProvider::new("event-test-encoder", 64));

        rt.embedder("event-test-encoder")
            .await
            .expect("embedder initialization must succeed");

        let page = event_store
            .query_events(
                khive_storage::EventFilter::default(),
                khive_storage::PageRequest {
                    limit: 10,
                    offset: 0,
                },
            )
            .await
            .expect("query embedder initialization event");
        let event = page
            .items
            .iter()
            .find(|event| event.verb == "embedder.init")
            .expect("embedder initialization event must be written");

        assert_eq!(event.kind, khive_types::EventKind::EmbedderInitialized);
        assert_eq!(event.payload["model_name"], "event-test-encoder");
        let duration_us = event.payload["duration_us"]
            .as_i64()
            .expect("duration_us must be an integer");
        assert!(duration_us > 0);
        assert_eq!(event.duration_us, duration_us);
    }

    #[tokio::test]
    async fn embedder_initialization_uses_triggering_request_identity() {
        let rt = memory_rt_no_model();
        rt.register_embedder(MockEmbedderProvider::new("request-identity-encoder", 64));
        let tenant = Namespace::parse("tenant-request").expect("valid tenant namespace");
        let event_store = rt
            .events(&rt.authorize(tenant.clone()).expect("authorize tenant"))
            .expect("event store must be available");

        let mut builder = VerbRegistryBuilder::new();
        builder.register(EmbedderInitPack {
            runtime: rt.clone(),
        });
        builder.with_default_namespace("baked-namespace");
        builder.with_actor_id(Some("baked-actor".to_string()));
        let registry = builder.build().expect("registry builds");

        registry
            .dispatch_with_identity(
                "initialize_embedder",
                serde_json::json!({"namespace": tenant.as_str()}),
                Some(RequestIdentity {
                    namespace: tenant.as_str().to_string(),
                    actor_id: Some("request-actor".to_string()),
                    visible_namespaces: vec![],
                    process_ref: None,
                    request_id: None,
                }),
            )
            .await
            .expect("request-triggered embedder initialization must succeed");

        let page = event_store
            .query_events(
                khive_storage::EventFilter::default(),
                khive_storage::PageRequest {
                    limit: 10,
                    offset: 0,
                },
            )
            .await
            .expect("query embedder initialization event");
        let event = page
            .items
            .iter()
            .find(|event| event.verb == "embedder.init")
            .expect("embedder initialization event must be written");

        assert_eq!(event.namespace, tenant.as_str());
        assert_eq!(event.actor, "actor:request-actor");
    }

    #[tokio::test]
    async fn registered_names_includes_custom_provider() {
        let rt = memory_rt_no_model();
        rt.register_embedder(MockEmbedderProvider::new("my-encoder", 128));

        let names = rt.registered_embedding_model_names();
        assert!(
            names.contains(&"my-encoder".to_string()),
            "registered_embedding_model_names must include custom provider 'my-encoder'; got {names:?}"
        );
    }

    // ── Test: dual-embedding regression — both MiniLM and paraphrase reachable ─

    #[tokio::test]
    async fn dual_embedding_regression_both_models_registered() {
        use khive_runtime::RuntimeConfig;
        let rt = KhiveRuntime::new(RuntimeConfig {
            wal_ceiling_bytes: 0,
            wal_ceiling_configured_bytes: 0,
            wal_ceiling_source: Default::default(),
            wal_ceiling_env_raw: None,
            web: Default::default(),
            telemetry: Default::default(),
            mounts: Vec::new(),
            brain: Default::default(),
            git_write: Default::default(),
            display_timezone: chrono_tz::Tz::UTC,
            events_split: None,
            db_path: None,
            blob_hydration_bytes: khive_runtime::DEFAULT_BLOB_HYDRATION_BYTES,
            default_namespace: Namespace::local(),
            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
            additional_embedding_models: vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2],
            gate: Arc::new(AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            brain_profile: None,
            visible_namespaces: vec![],
            allowed_outbound_namespaces: vec![],
            actor_id: None,
            exec: Default::default(),
            ..khive_runtime::RuntimeConfig::no_embeddings()
        })
        .expect("runtime with two models");

        let names = rt.registered_embedding_model_names();

        assert!(
            names.contains(&"all-minilm-l6-v2".to_string()),
            "MiniLM must be registered; names: {names:?}"
        );
        assert!(
            names.contains(&"paraphrase-multilingual-minilm-l12-v2".to_string()),
            "paraphrase must be registered; names: {names:?}"
        );

        // Verify resolve_embedding_model works for both.
        rt.resolve_embedding_model(Some("all-minilm-l6-v2"))
            .expect("MiniLM must resolve");
        rt.resolve_embedding_model(Some("paraphrase"))
            .expect("paraphrase alias must resolve");
    }

    // ── Test: unknown embedder returns UnknownModel ───────────────────────────

    #[tokio::test]
    async fn embedder_unknown_name_returns_error() {
        let rt = memory_rt_no_model();
        let err = rt
            .embedder("no-such-model")
            .await
            .err()
            .expect("expected Err for unknown embedder name, got Ok");
        assert!(
            matches!(err, RuntimeError::UnknownModel(ref n) if n == "no-such-model"),
            "expected UnknownModel for unregistered name; got {err:?}"
        );
    }

    // ── Test: custom provider registered via pack hook is reachable end-to-end ─
    //
    // This is the integration counterpart to the unit tests in
    // `embedder_registry.rs`. It verifies the full stack: a pack overrides
    // `register_embedders`, the transport calls `VerbRegistry::call_register_embedders`,
    // and the custom provider can be resolved and used via `rt.embedder(name)`.

    #[tokio::test]
    async fn pack_register_embedders_hook_makes_provider_reachable() {
        use async_trait::async_trait;
        use khive_runtime::pack::HandlerDef;
        use khive_runtime::NamespaceToken;
        use khive_runtime::{PackRuntime, VerbRegistry, VerbRegistryBuilder};
        use khive_types::Pack;
        use serde_json::Value;

        struct EmbedderPack;

        impl Pack for EmbedderPack {
            const NAME: &'static str = "embedder-test-pack";
            const NOTE_KINDS: &'static [&'static str] = &[];
            const ENTITY_KINDS: &'static [&'static str] = &[];
            const HANDLERS: &'static [HandlerDef] = &[];
        }

        #[async_trait]
        impl PackRuntime for EmbedderPack {
            fn name(&self) -> &str {
                Self::NAME
            }
            fn note_kinds(&self) -> &'static [&'static str] {
                Self::NOTE_KINDS
            }
            fn entity_kinds(&self) -> &'static [&'static str] {
                Self::ENTITY_KINDS
            }
            fn handlers(&self) -> &'static [HandlerDef] {
                Self::HANDLERS
            }
            fn register_embedders(&self, runtime: &KhiveRuntime) {
                runtime.register_embedder(MockEmbedderProvider::new("pack-custom-encoder", 256));
            }
            async fn dispatch(
                &self,
                _verb: &str,
                _params: Value,
                _registry: &VerbRegistry,
                _token: &NamespaceToken,
            ) -> Result<Value, khive_runtime::RuntimeError> {
                Ok(Value::Null)
            }
        }

        let rt = memory_rt_no_model();
        // Simulate what the transport does: build the registry, then call the hook.
        let mut builder = VerbRegistryBuilder::new();
        builder.register(EmbedderPack);
        let registry = builder.build().expect("registry builds");
        registry.call_register_embedders(&rt);

        // After the hook fires, the custom provider must be reachable.
        let service = rt
            .embedder("pack-custom-encoder")
            .await
            .expect("pack-contributed provider must be reachable after call_register_embedders");

        let texts = vec!["test sentence".to_string()];
        let vecs = service
            .embed(&texts, EmbeddingModel::AllMiniLmL6V2)
            .await
            .expect("custom service must embed without error");
        assert_eq!(vecs.len(), 1);
        assert_eq!(
            vecs[0].len(),
            256,
            "dims must match provider declaration (256)"
        );
    }

    // ── Test: failing provider build() returns Err instead of panicking ───────

    #[tokio::test]
    async fn failing_provider_build_returns_err_not_panic() {
        struct FailingProvider;

        #[async_trait]
        impl EmbedderProvider for FailingProvider {
            fn name(&self) -> &str {
                "failing-provider"
            }
            fn dimensions(&self) -> usize {
                128
            }
            async fn build(&self) -> Result<Arc<dyn EmbeddingService>, RuntimeError> {
                Err(RuntimeError::Internal(
                    "simulated provider construction failure".into(),
                ))
            }
        }

        let rt = memory_rt_no_model();
        rt.register_embedder(FailingProvider);

        let result = rt.embedder("failing-provider").await;
        assert!(
            result.is_err(),
            "embedder() must return Err when build() fails, not panic; got Ok"
        );
        let err = result.err().expect("checked above");
        let msg = err.to_string();
        assert!(
            msg.contains("simulated provider construction failure")
                || msg.contains("build() failed")
                || msg.contains("Internal"),
            "error must carry build failure context; got: {msg}"
        );
    }
}

// =============================================================================
// Epistemic endpoint tests (ADR-055 Phase 2+3)
// =============================================================================

// --- Entity→Entity ACCEPT cases ---

/// Concept→Concept supports: base allowlist row.
#[tokio::test]
async fn link_concept_concept_supports_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let a = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Finding A", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Claim B", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, a.id, b.id, EdgeRelation::Supports, 0.8, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Supports);
    assert_eq!(edge.source_id, a.id);
    assert_eq!(edge.target_id, b.id);
}

/// Document→Concept supports: base allowlist row.
#[tokio::test]
async fn link_document_concept_supports_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let doc = rt
        .create_entity_with_embedding_report(&tok, "document", None, "Paper X", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Hypothesis Y",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, doc.id, claim.id, EdgeRelation::Supports, 0.9, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Supports);
}

/// Concept→Concept refutes: base allowlist row.
#[tokio::test]
async fn link_concept_concept_refutes_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let a = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Counter-evidence",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Claim B", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, a.id, b.id, EdgeRelation::Refutes, 0.7, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Refutes);
}

/// Document→Concept refutes: base allowlist row.
#[tokio::test]
async fn link_document_concept_refutes_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let doc = rt
        .create_entity_with_embedding_report(
            &tok,
            "document",
            None,
            "Negative study",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Claim C", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, doc.id, claim.id, EdgeRelation::Refutes, 0.85, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Refutes);
}

// --- Note→Note ACCEPT cases ---

/// Note→Note supports: same substrate, any note kind allowed.
#[tokio::test]
async fn link_note_note_supports_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let finding = rt
        .create_note(
            &tok,
            "observation",
            Some("Finding note"),
            "experiment shows positive result",
            Some(0.8),
            None,
            vec![],
        )
        .await
        .unwrap();
    let claim = rt
        .create_note(
            &tok,
            "question",
            Some("Claim note"),
            "does intervention work?",
            Some(0.7),
            None,
            vec![],
        )
        .await
        .unwrap();
    let edge = rt
        .link(
            &tok,
            finding.id,
            claim.id,
            EdgeRelation::Supports,
            0.9,
            None,
        )
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Supports);
    assert_eq!(edge.source_id, finding.id);
    assert_eq!(edge.target_id, claim.id);
}

/// Note→Note refutes: same substrate allowed.
#[tokio::test]
async fn link_note_note_refutes_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let counter = rt
        .create_note(
            &tok,
            "observation",
            Some("Counter finding"),
            "null result from replication",
            Some(0.6),
            None,
            vec![],
        )
        .await
        .unwrap();
    let hypothesis = rt
        .create_note(
            &tok,
            "insight",
            Some("Hypothesis"),
            "the intervention increases outcome",
            Some(0.7),
            None,
            vec![],
        )
        .await
        .unwrap();
    let edge = rt
        .link(
            &tok,
            counter.id,
            hypothesis.id,
            EdgeRelation::Refutes,
            0.75,
            None,
        )
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Refutes);
}

// --- Cross-substrate REJECT cases ---

/// Note→Entity supports: cross-substrate, must error.
#[tokio::test]
async fn link_note_entity_supports_rejected() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let note = rt
        .create_note(
            &tok,
            "observation",
            None,
            "finding note",
            Some(0.5),
            None,
            vec![],
        )
        .await
        .unwrap();
    let entity = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Some concept",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let result = rt
        .link(&tok, note.id, entity.id, EdgeRelation::Supports, 0.8, None)
        .await;
    assert!(
        matches!(result, Err(khive_runtime::RuntimeError::InvalidInput(_))),
        "note→entity supports must be rejected (cross-substrate); got {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("supports"),
        "error message must name the relation 'supports'; got: {msg}"
    );
}

/// Entity→Note refutes: cross-substrate, must error.
#[tokio::test]
async fn link_entity_note_refutes_rejected() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "A concept", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let note = rt
        .create_note(
            &tok,
            "observation",
            None,
            "some note",
            Some(0.5),
            None,
            vec![],
        )
        .await
        .unwrap();
    let result = rt
        .link(&tok, entity.id, note.id, EdgeRelation::Refutes, 0.5, None)
        .await;
    assert!(
        matches!(result, Err(khive_runtime::RuntimeError::InvalidInput(_))),
        "entity→note refutes must be rejected (cross-substrate); got {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("refutes"),
        "error message must name the relation 'refutes'; got: {msg}"
    );
}

// --- Disallowed entity pair REJECT case ---

/// Person→Concept supports: not in base allowlist, must error naming the relation.
#[tokio::test]
async fn link_person_concept_supports_rejected_with_relation_name() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let person = rt
        .create_entity_with_embedding_report(
            &tok,
            "person",
            None,
            "Researcher A",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Hypothesis Z",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let result = rt
        .link(&tok, person.id, claim.id, EdgeRelation::Supports, 0.5, None)
        .await;
    assert!(
        matches!(result, Err(khive_runtime::RuntimeError::InvalidInput(_))),
        "person→concept supports is not in base allowlist; got {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("supports"),
        "error message must name the relation 'supports'; got: {msg}"
    );
}

// --- Remaining allowlist source kinds ---

/// Dataset→Concept supports: base allowlist row (previously untested source kind).
#[tokio::test]
async fn link_dataset_concept_supports_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let ds = rt
        .create_entity_with_embedding_report(&tok, "dataset", None, "Bench-X", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Hypothesis Q",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, ds.id, claim.id, EdgeRelation::Supports, 0.8, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Supports);
}

/// Artifact→Concept refutes: base allowlist row (previously untested source kind).
#[tokio::test]
async fn link_artifact_concept_refutes_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let art = rt
        .create_entity_with_embedding_report(
            &tok,
            "artifact",
            None,
            "Checkpoint-v1",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Claim R", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, art.id, claim.id, EdgeRelation::Refutes, 0.7, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Refutes);
}

/// Artifact→Concept supports: base allowlist row (previously untested combination).
#[tokio::test]
async fn link_artifact_concept_supports_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let art = rt
        .create_entity_with_embedding_report(
            &tok,
            "artifact",
            None,
            "Checkpoint-v2",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Claim T", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, art.id, claim.id, EdgeRelation::Supports, 0.8, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Supports);
    assert_eq!(edge.source_id, art.id);
    assert_eq!(edge.target_id, claim.id);
}

/// Dataset→Concept refutes: base allowlist row (previously untested combination).
#[tokio::test]
async fn link_dataset_concept_refutes_accepted() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let ds = rt
        .create_entity_with_embedding_report(&tok, "dataset", None, "Bench-Y", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Hypothesis W",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok, ds.id, claim.id, EdgeRelation::Refutes, 0.75, None)
        .await
        .unwrap();
    assert_eq!(edge.relation, EdgeRelation::Refutes);
    assert_eq!(edge.source_id, ds.id);
    assert_eq!(edge.target_id, claim.id);
}

// --- update_edge parity tests ---

/// (a) update_edge legal entity edge → Supports on allowlist pair: accepted.
/// Uses concept→concept: start with Extends, update to Supports.
#[tokio::test]
async fn update_edge_to_supports_on_legal_entity_pair_accepted() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let evidence = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Evidence concept",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let claim = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Hypothesis H",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    // Start with Extends (legal for concept→concept).
    let edge = rt
        .link(
            &tok,
            evidence.id,
            claim.id,
            EdgeRelation::Extends,
            0.9,
            None,
        )
        .await
        .unwrap();
    // Update the relation to Supports — concept→concept is in the Supports allowlist.
    let updated = rt
        .update_edge(
            &tok,
            edge.id.into(),
            EdgePatch {
                relation: Some(EdgeRelation::Supports),
                ..Default::default()
            },
        )
        .await
        .expect("update_edge to supports on concept→concept must be accepted");
    assert_eq!(updated.relation, EdgeRelation::Supports);
}

/// (b) update_edge entity edge → Supports on off-allowlist pair: rejected.
#[tokio::test]
async fn update_edge_to_supports_on_disallowed_entity_pair_rejected() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let person = rt
        .create_entity_with_embedding_report(
            &tok,
            "person",
            None,
            "Researcher B",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let concept = rt
        .create_entity_with_embedding_report(&tok, "concept", None, "Claim S", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    // Person→Concept with a relation that IS legal to start (introduced_by is
    // illegal for person→concept too — use enables which IS legal for person
    // is also illegal, use instance_of which allows *→concept).
    // Simplest: use instance_of (valid for *→concept) to create the edge first.
    let edge = rt
        .link(
            &tok,
            person.id,
            concept.id,
            EdgeRelation::InstanceOf,
            1.0,
            None,
        )
        .await
        .unwrap();
    // Now update to Supports — person is not in the allowlist for supports.
    let result = rt
        .update_edge(
            &tok,
            edge.id.into(),
            EdgePatch {
                relation: Some(EdgeRelation::Supports),
                ..Default::default()
            },
        )
        .await;
    assert!(
        matches!(result, Err(khive_runtime::RuntimeError::InvalidInput(_))),
        "update_edge to supports on person→concept must be rejected; got {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("supports"),
        "error message must name the relation 'supports'; got: {msg}"
    );
    assert!(
        msg.contains(
            "currently legal relations for person -> concept under the loaded endpoint rules: instance_of"
        ),
        "error message must expose the derived legal-relations set from the shared validator \
         update_edge reaches at operations.rs; got: {msg}"
    );
}

/// (c) update_edge note→entity annotates edge → Supports: rejected (cross-substrate).
#[tokio::test]
async fn update_edge_annotates_to_supports_rejected_cross_substrate() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity_with_embedding_report(
            &tok,
            "concept",
            None,
            "Target concept",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let note = rt
        .create_note(
            &tok,
            "observation",
            None,
            "some observation",
            Some(0.5),
            None,
            vec![],
        )
        .await
        .unwrap();
    // Create note→entity annotates edge (the only legal cross-substrate relation).
    let edge = rt
        .link(&tok, note.id, entity.id, EdgeRelation::Annotates, 1.0, None)
        .await
        .unwrap();
    // Update to Supports → must fail (note→entity is cross-substrate for supports).
    let result = rt
        .update_edge(
            &tok,
            edge.id.into(),
            EdgePatch {
                relation: Some(EdgeRelation::Supports),
                ..Default::default()
            },
        )
        .await;
    assert!(
        matches!(result, Err(khive_runtime::RuntimeError::InvalidInput(_))),
        "update_edge note→entity annotates → supports must be rejected; got {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("supports"),
        "error message must name the relation 'supports'; got: {msg}"
    );
}

/// (d) update_edge note→note edge → Refutes: accepted (same substrate).
#[tokio::test]
async fn update_edge_note_note_to_refutes_accepted() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let note_a = rt
        .create_note(
            &tok,
            "observation",
            None,
            "prior finding",
            Some(0.6),
            None,
            vec![],
        )
        .await
        .unwrap();
    let note_b = rt
        .create_note(
            &tok,
            "insight",
            None,
            "derived claim",
            Some(0.7),
            None,
            vec![],
        )
        .await
        .unwrap();
    // Create a note→note edge with Supports first.
    let edge = rt
        .link(
            &tok,
            note_a.id,
            note_b.id,
            EdgeRelation::Supports,
            0.8,
            None,
        )
        .await
        .unwrap();
    // Update to Refutes — note→note same-substrate, must be accepted.
    let updated = rt
        .update_edge(
            &tok,
            edge.id.into(),
            EdgePatch {
                relation: Some(EdgeRelation::Refutes),
                ..Default::default()
            },
        )
        .await
        .expect("update_edge note→note supports → refutes must be accepted");
    assert_eq!(updated.relation, EdgeRelation::Refutes);
}

// =============================================================================
// Multi-namespace read visibility (visible-set tokens)
// =============================================================================

/// ADR-007 PR-A1: visible-set enforcement on by-ID ops is removed.
/// list_entities / list_notes still filter by visible_namespaces (PR-B collapses that).
/// get_entity and get_note_including_deleted now return any record by UUID regardless
/// of the token's visible set.  Writes still land in the primary namespace only.
#[tokio::test]
async fn visible_set_reads_primary_and_extra_not_third() {
    let rt = rt();

    // Mint single-namespace write tokens for three isolated namespaces.
    let tok_a = rt.authorize(Namespace::parse("vis-a").unwrap()).unwrap();
    let tok_b = rt.authorize(Namespace::parse("vis-b").unwrap()).unwrap();
    let tok_c = rt.authorize(Namespace::parse("vis-c").unwrap()).unwrap();

    // Write one entity and one note in each namespace.
    let entity_a = rt
        .create_entity_with_embedding_report(&tok_a, "concept", None, "EntityA", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let entity_b = rt
        .create_entity_with_embedding_report(&tok_b, "concept", None, "EntityB", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let entity_c = rt
        .create_entity_with_embedding_report(&tok_c, "concept", None, "EntityC", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    let note_a = rt
        .create_note(&tok_a, "observation", None, "NoteA", None, None, vec![])
        .await
        .unwrap();
    let note_b = rt
        .create_note(&tok_b, "observation", None, "NoteB", None, None, vec![])
        .await
        .unwrap();
    let note_c = rt
        .create_note(&tok_c, "observation", None, "NoteC", None, None, vec![])
        .await
        .unwrap();

    // Mint a visible-set token: primary=vis-a, visible=[vis-a, vis-b].
    let vis_tok = rt
        .authorize_with_visibility(
            Namespace::parse("vis-a").unwrap(),
            vec![Namespace::parse("vis-b").unwrap()],
        )
        .unwrap();

    // --- list_entities sees a+b, not c ---
    let visible_entities = rt.list_entities(&vis_tok, None, None, 50, 0).await.unwrap();
    let entity_names: Vec<&str> = visible_entities.iter().map(|e| e.name.as_str()).collect();
    assert!(entity_names.contains(&"EntityA"), "EntityA must be visible");
    assert!(entity_names.contains(&"EntityB"), "EntityB must be visible");
    assert!(
        !entity_names.contains(&"EntityC"),
        "EntityC must NOT be visible"
    );

    // --- list_notes sees a+b, not c ---
    let visible_notes = rt.list_notes(&vis_tok, None, 50, 0).await.unwrap();
    let note_contents: Vec<&str> = visible_notes.iter().map(|n| n.content.as_str()).collect();
    assert!(note_contents.contains(&"NoteA"), "NoteA must be visible");
    assert!(note_contents.contains(&"NoteB"), "NoteB must be visible");
    assert!(
        !note_contents.contains(&"NoteC"),
        "NoteC must NOT be visible"
    );

    // --- get_entity: all three succeed by UUID (PR-A1: visible-set gate removed) ---
    rt.get_entity(&vis_tok, entity_a.id)
        .await
        .expect("get entity_a must succeed");
    rt.get_entity(&vis_tok, entity_b.id)
        .await
        .expect("get entity_b (visible non-primary) must succeed");
    rt.get_entity(&vis_tok, entity_c.id)
        .await
        .expect("get entity_c by UUID succeeds — visible-set gate removed in PR-A1");

    // --- get_note: all three returned by UUID (PR-A1: visible-set gate removed) ---
    let fetched_note_a = rt
        .get_note_including_deleted(&vis_tok, note_a.id)
        .await
        .expect("call must not error");
    assert!(
        fetched_note_a.is_some(),
        "note_a (primary namespace) must be returned"
    );

    let fetched_note_b = rt
        .get_note_including_deleted(&vis_tok, note_b.id)
        .await
        .expect("call must not error");
    assert!(
        fetched_note_b.is_some(),
        "note_b (visible non-primary) must be returned"
    );

    let fetched_note_c = rt
        .get_note_including_deleted(&vis_tok, note_c.id)
        .await
        .expect("call must not error");
    // PR-A1: by-ID get returns the note regardless of visible set (list_notes still filters — PR-B).
    assert!(
        fetched_note_c.is_some(),
        "note_c (outside visible set) must be returned by UUID via PR-A1 by-ID contract"
    );
    assert_eq!(
        fetched_note_c.as_ref().unwrap().namespace.as_str(),
        "vis-c",
        "fetched note_c must preserve its stored namespace"
    );

    // --- WRITE via vis_tok lands in primary (vis-a) only, not in vis-b ---
    let written = rt
        .create_entity_with_embedding_report(
            &vis_tok,
            "concept",
            None,
            "WrittenViaVisToken",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    assert_eq!(
        written.namespace.as_str(),
        "vis-a",
        "write must stamp primary namespace, not any extra-visible one"
    );

    // Verify vis-b does not contain the newly written entity.
    let b_entities = rt.list_entities(&tok_b, None, None, 50, 0).await.unwrap();
    let b_names: Vec<&str> = b_entities.iter().map(|e| e.name.as_str()).collect();
    assert!(
        !b_names.contains(&"WrittenViaVisToken"),
        "write must NOT appear in vis-b"
    );

    // Suppress unused-variable warnings for IDs we intentionally only inserted.
    let _ = note_a;
    let _ = note_c;
    let _ = entity_c;
}

/// Backward compatibility: a token minted via `authorize()` (no visibility)
/// behaves exactly as before — single namespace, strict equality on reads/writes.
/// This is the original namespace_isolation test reproduced verbatim to confirm
/// nothing regressed.
#[tokio::test]
async fn namespace_isolation_backward_compat() {
    let rt = rt();
    let ns_a_tok = rt.authorize(Namespace::parse("bc-a").unwrap()).unwrap();
    let ns_b_tok = rt.authorize(Namespace::parse("bc-b").unwrap()).unwrap();

    rt.create_entity_with_embedding_report(
        &ns_a_tok,
        "concept",
        None,
        "EntityA",
        None,
        None,
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();
    rt.create_entity_with_embedding_report(
        &ns_b_tok,
        "concept",
        None,
        "EntityB",
        None,
        None,
        vec![],
    )
    .await
    .map(|(record, _report)| record)
    .unwrap();

    let a_entities = rt
        .list_entities(&ns_a_tok, None, None, 50, 0)
        .await
        .unwrap();
    assert_eq!(a_entities.len(), 1);
    assert_eq!(a_entities[0].name, "EntityA");

    let b_entities = rt
        .list_entities(&ns_b_tok, None, None, 50, 0)
        .await
        .unwrap();
    assert_eq!(b_entities.len(), 1);
    assert_eq!(b_entities[0].name, "EntityB");
}

// =============================================================================
// Fix 4: visible-set token invariants (primary always included, no duplicates)
// =============================================================================

/// No extra-visible namespaces → visible set contains only the primary.
#[test]
fn mint_with_visibility_empty_extra_yields_primary_only() {
    let rt = rt();
    let tok = rt
        .authorize_with_visibility(Namespace::parse("ns-primary-only").unwrap(), vec![])
        .unwrap();

    let vis = tok.visible_namespaces();
    assert_eq!(vis.len(), 1, "primary only when no extras given");
    assert_eq!(vis[0].as_str(), "ns-primary-only");
    assert_eq!(tok.namespace().as_str(), "ns-primary-only");
}

/// When the primary is repeated in the extra list it must not appear twice.
#[test]
fn mint_with_visibility_deduplicates_primary_in_extras() {
    let rt = rt();
    let tok = rt
        .authorize_with_visibility(
            Namespace::parse("ns-dedup").unwrap(),
            vec![
                Namespace::parse("ns-dedup").unwrap(),
                Namespace::parse("ns-extra").unwrap(),
            ],
        )
        .unwrap();

    let vis = tok.visible_namespaces();
    assert_eq!(vis.len(), 2, "primary counted once, one distinct extra");
    assert_eq!(vis[0].as_str(), "ns-dedup");
    assert_eq!(vis[1].as_str(), "ns-extra");
}

// =============================================================================
// Fix 1: mutations confined to primary namespace; reads use visible set
// =============================================================================

/// A note written into an extra-visible namespace can be read back through
/// the visible-set token (resolve uses the visible set for notes).
#[tokio::test]
async fn resolve_uses_visible_set_for_note_in_extra_namespace() {
    let rt = rt();
    let _tok_a = rt.authorize(Namespace::parse("res-a").unwrap()).unwrap();
    let tok_b = rt.authorize(Namespace::parse("res-b").unwrap()).unwrap();

    let note_b = rt
        .create_note(&tok_b, "observation", None, "NoteInB", None, None, vec![])
        .await
        .unwrap();

    // visible-set token: primary=res-a, sees res-b too.
    let vis_tok = rt
        .authorize_with_visibility(
            Namespace::parse("res-a").unwrap(),
            vec![Namespace::parse("res-b").unwrap()],
        )
        .unwrap();

    // get_note_including_deleted uses resolve() which should honour visible set.
    let fetched = rt
        .get_note_including_deleted(&vis_tok, note_b.id)
        .await
        .expect("call must not error");
    assert!(
        fetched.is_some(),
        "note in extra-visible namespace must be readable via visible-set token"
    );
    assert_eq!(fetched.unwrap().content, "NoteInB");
}

/// A link whose target lives in the extra-visible (but not primary) namespace
/// must succeed — endpoint existence is a by-ID check, and by-ID ops are
/// namespace-agnostic regardless of the caller's primary/visible-set distinction
/// (ADR-007 Rule 2; #631). This supersedes the prior
/// `link_refuses_target_in_visible_but_not_primary_namespace` expectation, which
/// asserted the pre-#631 bug (endpoint existence gated on `token.namespace()`) as
/// intentional mutation-safety behavior.
#[tokio::test]
async fn link_target_in_visible_but_not_primary_namespace_succeeds() {
    let rt = rt();
    let tok_a = rt
        .authorize(Namespace::parse("link-mut-a").unwrap())
        .unwrap();
    let tok_b = rt
        .authorize(Namespace::parse("link-mut-b").unwrap())
        .unwrap();

    let entity_a = rt
        .create_entity_with_embedding_report(
            &tok_a,
            "concept",
            None,
            "SrcEntity",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let entity_b = rt
        .create_entity_with_embedding_report(
            &tok_b,
            "concept",
            None,
            "TgtEntity",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // primary=link-mut-a, visible=[link-mut-a, link-mut-b].
    // entity_b lives in link-mut-b (visible, not primary).
    let vis_tok = rt
        .authorize_with_visibility(
            Namespace::parse("link-mut-a").unwrap(),
            vec![Namespace::parse("link-mut-b").unwrap()],
        )
        .unwrap();

    let result = rt
        .link(
            &vis_tok,
            entity_a.id,
            entity_b.id,
            EdgeRelation::Extends,
            1.0,
            None,
        )
        .await;
    assert!(
        result.is_ok(),
        "link with target in visible-only namespace must succeed (#631), got {result:?}"
    );
}

/// An annotates note whose annotated target lives in the extra-visible (but not
/// primary) namespace must succeed — same by-ID, namespace-agnostic contract as
/// `link` (ADR-007 Rule 2; #631). This supersedes the prior
/// `create_note_annotates_refuses_target_in_visible_only_namespace` expectation.
#[tokio::test]
async fn create_note_annotates_target_in_visible_only_namespace_succeeds() {
    let rt = rt();
    let _tok_a = rt
        .authorize(Namespace::parse("ann-mut-a").unwrap())
        .unwrap();
    let tok_b = rt
        .authorize(Namespace::parse("ann-mut-b").unwrap())
        .unwrap();

    let entity_b = rt
        .create_entity_with_embedding_report(
            &tok_b,
            "concept",
            None,
            "AnnotTarget",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // primary=ann-mut-a, visible=[ann-mut-a, ann-mut-b].
    // entity_b lives in ann-mut-b (visible, not primary).
    let vis_tok = rt
        .authorize_with_visibility(
            Namespace::parse("ann-mut-a").unwrap(),
            vec![Namespace::parse("ann-mut-b").unwrap()],
        )
        .unwrap();

    let result = rt
        .create_note(
            &vis_tok,
            "observation",
            None,
            "AnnotNote",
            None,
            None,
            vec![entity_b.id],
        )
        .await;
    assert!(
        result.is_ok(),
        "annotates with target in visible-only namespace must succeed (#631), got {result:?}"
    );
}

// =============================================================================
// hybrid_search cross-namespace Option B limitation documented and tested
// =============================================================================

/// Verifies that `hybrid_search` with a visible-set token returns entities from
/// ALL visible namespaces (not just the primary namespace).
///
/// After FTS+ANN consolidation, `fts_entities` is a single shared table with a
/// `namespace` column. `hybrid_search` passes `visible_ns` as a `TextFilter`
/// so entities from any visible namespace are surfaced in one query pass.
#[tokio::test]
async fn hybrid_search_surfaces_all_visible_namespaces() {
    let rt = rt();

    let ns_primary = Namespace::parse("hs-primary-ns").unwrap();
    let ns_extra = Namespace::parse("hs-extra-ns").unwrap();

    let tok_primary = rt.authorize(ns_primary.clone()).unwrap();
    let tok_extra = rt.authorize(ns_extra.clone()).unwrap();

    // Create an entity in primary namespace with a distinctive term.
    let entity_in_primary = rt
        .create_entity_with_embedding_report(
            &tok_primary,
            "concept",
            None,
            "StellarPrimary",
            Some("unique stellar primary concept"),
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // Create an entity in the extra namespace with the same distinctive term.
    let entity_in_extra = rt
        .create_entity_with_embedding_report(
            &tok_extra,
            "concept",
            None,
            "StellarExtra",
            Some("unique stellar extra concept"),
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // Visible-set token: primary = hs-primary-ns, also sees hs-extra-ns.
    let vis_tok = rt
        .authorize_with_visibility(ns_primary.clone(), vec![ns_extra.clone()])
        .unwrap();

    // Search: FTS-only (no embedding model in test runtime).
    // With consolidated fts_entities, both namespace entities should surface.
    let hits = rt
        .hybrid_search(&vis_tok, "stellar", None, 20, None, None, &[], None)
        .await
        .unwrap();

    let hit_ids: Vec<Uuid> = hits.iter().map(|h| h.entity_id).collect();

    // Primary entity must surface.
    assert!(
        hit_ids.contains(&entity_in_primary.id),
        "hybrid_search must return entity from primary namespace; \
         expected entity_id={}, got: {hit_ids:?}",
        entity_in_primary.id,
    );

    // Extra-namespace entity must also surface (Phase-1.5 limitation lifted).
    // The consolidated fts_entities table + namespace column filter enables cross-namespace FTS.
    assert!(
        hit_ids.contains(&entity_in_extra.id),
        "hybrid_search must return entity from visible extra namespace; \
         entity_id={} missing from: {hit_ids:?}",
        entity_in_extra.id,
    );

    // Direct read of the extra-namespace entity via get_entity must still work.
    let fetched = rt
        .get_entity(&vis_tok, entity_in_extra.id)
        .await
        .expect("get_entity via visible-set token must return extra-namespace entity");
    assert_eq!(
        fetched.id, entity_in_extra.id,
        "visible-set read of extra-namespace entity must succeed"
    );
}

// =============================================================================
// PR-A1: cross-namespace note by-ID operations (update_note / delete_note)
// =============================================================================

/// update_note via a foreign-namespace token must succeed (PR-A1).
/// Non-vacuity: this test FAILS if the old visible-set guard is restored.
#[tokio::test]
async fn update_note_cross_namespace_succeeds() {
    use khive_runtime::NotePatch;

    let rt = rt();
    let tok_a = rt
        .authorize(Namespace::parse("note-ns-a").unwrap())
        .unwrap();
    let tok_b = rt
        .authorize(Namespace::parse("note-ns-b").unwrap())
        .unwrap();

    let note = rt
        .create_note(
            &tok_a,
            "observation",
            None,
            "original content",
            Some(0.5),
            None,
            vec![],
        )
        .await
        .unwrap();
    assert_eq!(note.namespace.as_str(), "note-ns-a");

    // Update from a different token — must succeed.
    let patch = NotePatch::new(None, Some("updated content".to_string()), None, None, None);
    let updated = rt
        .update_note_with_embedding_report(&tok_b, note.id, patch)
        .await
        .map(|(record, _report)| record);
    assert!(
        updated.is_ok(),
        "update_note from foreign token must succeed; got {:?}",
        updated
    );
    let updated = updated.unwrap();
    assert_eq!(updated.content, "updated content");
    // Namespace on the record must NOT change to tok_b's namespace.
    assert_eq!(
        updated.namespace.as_str(),
        "note-ns-a",
        "namespace must remain the record's stored namespace after cross-ns update"
    );
}

/// delete_note (soft and hard) via a foreign-namespace token must succeed (PR-A1).
/// Non-vacuity: this test FAILS if the old ensure_namespace guard is restored.
#[tokio::test]
async fn delete_note_cross_namespace_succeeds() {
    let rt = rt();
    let tok_a = rt.authorize(Namespace::parse("del-ns-a").unwrap()).unwrap();
    let tok_b = rt.authorize(Namespace::parse("del-ns-b").unwrap()).unwrap();

    // --- soft delete from foreign token ---
    let note_soft = rt
        .create_note(
            &tok_a,
            "observation",
            None,
            "soft target",
            Some(0.5),
            None,
            vec![],
        )
        .await
        .unwrap();
    let soft_result = rt.delete_note(&tok_b, note_soft.id, false).await;
    assert!(
        soft_result.unwrap(),
        "cross-namespace soft delete_note must return true"
    );
    // Confirm gone via live query.
    let after_soft = rt
        .get_note_including_deleted(&tok_a, note_soft.id)
        .await
        .unwrap();
    assert!(
        after_soft.is_some(),
        "soft-deleted note must still appear in including_deleted"
    );

    // --- hard delete from foreign token ---
    let note_hard = rt
        .create_note(
            &tok_a,
            "observation",
            None,
            "hard target",
            Some(0.5),
            None,
            vec![],
        )
        .await
        .unwrap();
    let hard_result = rt.delete_note(&tok_b, note_hard.id, true).await;
    assert!(
        hard_result.unwrap(),
        "cross-namespace hard delete_note must return true"
    );
    let after_hard = rt
        .get_note_including_deleted(&tok_a, note_hard.id)
        .await
        .unwrap();
    assert!(
        after_hard.is_none(),
        "hard-deleted note must not appear even via including_deleted"
    );
}

// =============================================================================
// PR-A1: delete_edge cross-namespace audit-namespace tests
// =============================================================================

/// Soft-delete an edge via a foreign-namespace token.
///
/// Asserts: (1) the row is soft-deleted, (2) the EdgeDeleted audit event's
/// namespace == the record's own namespace (not the caller's).
///
/// Non-vacuity: this test FAILS (RC 101) if `delete_edge` uses the caller token
/// for event attribution instead of the record token derived from edge.namespace.
#[tokio::test]
async fn delete_edge_cross_namespace_audit_uses_record_namespace_soft() {
    let rt = rt();
    let tok_owner = rt.authorize(Namespace::parse("ns-owner").unwrap()).unwrap();
    let tok_caller = rt
        .authorize(Namespace::parse("ns-caller").unwrap())
        .unwrap();

    // Create two entities in ns-owner and link them.
    let src = rt
        .create_entity_with_embedding_report(
            &tok_owner,
            "concept",
            None,
            "AuditSrcSoft",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let tgt = rt
        .create_entity_with_embedding_report(
            &tok_owner,
            "concept",
            None,
            "AuditTgtSoft",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok_owner, src.id, tgt.id, EdgeRelation::Extends, 0.5, None)
        .await
        .unwrap();
    let edge_id: Uuid = edge.id.into();

    // Soft-delete via a foreign-namespace caller token — must succeed.
    let deleted = rt.delete_edge(&tok_caller, edge_id, false).await.unwrap();
    assert!(deleted, "cross-namespace soft delete_edge must return true");

    // Row must be soft-deleted (gone from live query, present via including_deleted).
    let live = rt.get_edge(&tok_owner, edge_id).await.unwrap();
    assert!(
        live.is_none(),
        "soft-deleted edge must not appear in live get_edge"
    );
    let incl = rt
        .get_edge_including_deleted(&tok_owner, edge_id)
        .await
        .unwrap();
    assert!(
        incl.is_some(),
        "soft-deleted edge must appear via get_edge_including_deleted"
    );

    // Audit event namespace must be the record's namespace (ns-owner), not the caller's (ns-caller).
    let events = rt
        .list_events(
            &tok_owner,
            EventFilter {
                kinds: vec![EventKind::EdgeDeleted],
                ..Default::default()
            },
            PageRequest::default(),
        )
        .await
        .unwrap();
    let delete_event = events
        .items
        .iter()
        .find(|e| e.target_id == Some(edge_id))
        .expect("EdgeDeleted event must exist for the deleted edge");
    assert_eq!(
        delete_event.namespace, "ns-owner",
        "EdgeDeleted event namespace must be the record's namespace (ns-owner), not the caller's"
    );
    assert_eq!(
        delete_event
            .payload
            .get("namespace")
            .and_then(|v| v.as_str()),
        Some("ns-owner"),
        "EdgeDeleted payload.namespace must be the record's namespace (ns-owner)"
    );
}

/// Hard-delete an edge via a foreign-namespace token.
///
/// Asserts: (1) the row is hard-removed, (2) the EdgeDeleted audit event's
/// namespace == the record's own namespace (not the caller's).
///
/// Non-vacuity: this test FAILS (RC 101) if `delete_edge` uses the caller token
/// for event attribution instead of the record token derived from edge.namespace.
#[tokio::test]
async fn delete_edge_cross_namespace_audit_uses_record_namespace_hard() {
    let rt = rt();
    let tok_owner = rt
        .authorize(Namespace::parse("ns-owner-hard").unwrap())
        .unwrap();
    let tok_caller = rt
        .authorize(Namespace::parse("ns-caller-hard").unwrap())
        .unwrap();

    // Create two entities in ns-owner-hard and link them.
    let src = rt
        .create_entity_with_embedding_report(
            &tok_owner,
            "concept",
            None,
            "AuditSrcHard",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let tgt = rt
        .create_entity_with_embedding_report(
            &tok_owner,
            "concept",
            None,
            "AuditTgtHard",
            None,
            None,
            vec![],
        )
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let edge = rt
        .link(&tok_owner, src.id, tgt.id, EdgeRelation::Extends, 0.6, None)
        .await
        .unwrap();
    let edge_id: Uuid = edge.id.into();

    // Hard-delete via a foreign-namespace caller token — must succeed.
    let deleted = rt.delete_edge(&tok_caller, edge_id, true).await.unwrap();
    assert!(deleted, "cross-namespace hard delete_edge must return true");

    // Row must be hard-removed (not present even via including_deleted).
    let incl = rt
        .get_edge_including_deleted(&tok_owner, edge_id)
        .await
        .unwrap();
    assert!(
        incl.is_none(),
        "hard-deleted edge must not appear via get_edge_including_deleted"
    );

    // Audit event namespace must be the record's namespace (ns-owner-hard), not the caller's.
    let events = rt
        .list_events(
            &tok_owner,
            EventFilter {
                kinds: vec![EventKind::EdgeDeleted],
                ..Default::default()
            },
            PageRequest::default(),
        )
        .await
        .unwrap();
    let delete_event = events
        .items
        .iter()
        .find(|e| e.target_id == Some(edge_id))
        .expect("EdgeDeleted event must exist for the hard-deleted edge");
    assert_eq!(
        delete_event.namespace, "ns-owner-hard",
        "EdgeDeleted event namespace must be record's namespace (ns-owner-hard), not caller's"
    );
    assert_eq!(
        delete_event
            .payload
            .get("namespace")
            .and_then(|v| v.as_str()),
        Some("ns-owner-hard"),
        "EdgeDeleted payload.namespace must be the record's namespace (ns-owner-hard)"
    );
}

// =============================================================================
// #711: stats() must aggregate over the caller's visible namespaces, matching
// the scope a full `list` keyset walk computes over — not just token.namespace().
// =============================================================================

/// Batched stats counts must match both a full multi-namespace `list` walk and
/// the sum of the corresponding per-namespace counts, excluding soft-deleted
/// rows from every path.
#[tokio::test]
async fn stats_totals_match_list_walk_across_visible_namespaces() {
    use khive_runtime::EdgeListFilter;

    // Identity-bearing caller: actor_id configured (not anonymous).
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        packs: vec!["kg".to_string()],
        brain_profile: None,
        actor_id: Some("lambda:stats-711-test".to_string()),
        ..RuntimeConfig::no_embeddings()
    })
    .expect("in-memory runtime with actor identity");

    let ns_a = Namespace::parse("stats-711-a").unwrap();
    let ns_b = Namespace::parse("stats-711-b").unwrap();
    let tok_a = rt.authorize(ns_a.clone()).unwrap();
    let tok_b = rt.authorize(ns_b.clone()).unwrap();

    // Entities: 2 in ns_a, 2 in ns_b (b2 created below, alongside the edges).
    let a1 = rt
        .create_entity_with_embedding_report(&tok_a, "concept", None, "StatsA1", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let a2 = rt
        .create_entity_with_embedding_report(&tok_a, "concept", None, "StatsA2", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    let b1 = rt
        .create_entity_with_embedding_report(&tok_b, "concept", None, "StatsB1", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();

    // Edges: two `extends` in ns_a, one `enables` in ns_b.
    rt.link(&tok_a, a1.id, a2.id, EdgeRelation::Extends, 1.0, None)
        .await
        .unwrap();
    rt.link(&tok_a, a2.id, a1.id, EdgeRelation::Extends, 1.0, None)
        .await
        .unwrap();
    let b2 = rt
        .create_entity_with_embedding_report(&tok_b, "concept", None, "StatsB2", None, None, vec![])
        .await
        .map(|(record, _report)| record)
        .unwrap();
    rt.link(&tok_b, b1.id, b2.id, EdgeRelation::Enables, 1.0, None)
        .await
        .unwrap();
    let deleted_edge = rt
        .link(&tok_b, b2.id, b1.id, EdgeRelation::Extends, 1.0, None)
        .await
        .unwrap();
    assert!(rt
        .delete_edge(&tok_b, deleted_edge.id.into(), false)
        .await
        .unwrap());

    // Notes: one in each namespace.
    rt.create_note(&tok_a, "observation", None, "NoteInA", None, None, vec![])
        .await
        .unwrap();
    rt.create_note(&tok_b, "observation", None, "NoteInB", None, None, vec![])
        .await
        .unwrap();
    let deleted_note = rt
        .create_note(
            &tok_a,
            "observation",
            None,
            "DeletedNoteInA",
            None,
            None,
            vec![],
        )
        .await
        .unwrap();
    assert!(rt
        .delete_note(&tok_a, deleted_note.id, false)
        .await
        .unwrap());

    let per_namespace_edges = rt
        .count_edges(&tok_a, EdgeListFilter::default())
        .await
        .unwrap()
        + rt.count_edges(&tok_b, EdgeListFilter::default())
            .await
            .unwrap();
    let mut per_namespace_relations = rt.count_edges_by_relation(&tok_a).await.unwrap();
    for (relation, count) in rt.count_edges_by_relation(&tok_b).await.unwrap() {
        *per_namespace_relations.entry(relation).or_insert(0) += count;
    }
    let per_namespace_notes =
        rt.count_notes(&tok_a, None).await.unwrap() + rt.count_notes(&tok_b, None).await.unwrap();

    // Identity-bearing frame whose visible set spans both namespaces.
    let vis_tok = rt
        .authorize_with_visibility(ns_a.clone(), vec![ns_b.clone()])
        .unwrap();

    let full_entities = rt
        .list_entities(&vis_tok, None, None, 500, 0)
        .await
        .unwrap();
    let stats_entities = rt.count_entities(&vis_tok, None).await.unwrap();
    assert_eq!(
        stats_entities,
        full_entities.len() as u64,
        "stats() entity total must equal a full list keyset walk under the same identity"
    );
    assert_eq!(stats_entities, 4);

    let full_edges = rt
        .list_edges(&vis_tok, EdgeListFilter::default(), 1000, 0)
        .await
        .unwrap();
    let stats_edges = rt
        .count_edges(&vis_tok, EdgeListFilter::default())
        .await
        .unwrap();
    assert_eq!(
        stats_edges,
        full_edges.len() as u64,
        "stats() edge total must equal a full list keyset walk under the same identity"
    );
    assert_eq!(stats_edges, per_namespace_edges);
    assert_eq!(stats_edges, 3);

    let edges_by_relation = rt.count_edges_by_relation(&vis_tok).await.unwrap();
    assert_eq!(edges_by_relation, per_namespace_relations);
    let relation_sum: u64 = edges_by_relation.values().sum();
    assert_eq!(
        relation_sum, stats_edges,
        "edges_by_relation must sum to the edges scalar under all identities"
    );

    let full_notes = rt.list_notes(&vis_tok, None, 200, 0).await.unwrap();
    let stats_notes = rt.count_notes(&vis_tok, None).await.unwrap();
    assert_eq!(
        stats_notes,
        full_notes.len() as u64,
        "stats() note total must equal a full list keyset walk under the same identity"
    );
    assert_eq!(stats_notes, per_namespace_notes);
    assert_eq!(stats_notes, 2);
}

#[test]
#[serial_test::serial]
fn test_harness_refuses_runtime_default_store() {
    if test_process::run_in_child() {
        return;
    }

    struct HomeGuard(Option<std::ffi::OsString>);

    impl Drop for HomeGuard {
        fn drop(&mut self) {
            match self.0.take() {
                Some(home) => std::env::set_var("HOME", home),
                None => std::env::remove_var("HOME"),
            }
        }
    }

    assert_eq!(
        std::env::var("KHIVE_TEST_HARNESS").as_deref(),
        Ok("1"),
        "the workspace Cargo harness must mark integration-test processes"
    );
    let fake_home = tempfile::tempdir().expect("temporary HOME");
    let _home_guard = HomeGuard(std::env::var_os("HOME"));
    std::env::set_var("HOME", fake_home.path());
    let expected_path = fake_home.path().join(".khive/khive.db");
    let config = RuntimeConfig::no_embeddings();
    assert_eq!(config.db_path.as_deref(), Some(expected_path.as_path()));

    let error = match KhiveRuntime::new(config) {
        Ok(_) => panic!("test harness opened the default home-directory store"),
        Err(error) => error,
    };
    assert!(
        error.to_string().contains("test harness refused"),
        "unexpected guard error: {error}"
    );
    assert!(
        !expected_path.exists(),
        "the guarded runtime must refuse the path before SQLite creates it"
    );
}