mushroomdb-server 0.2.0

HTTP/WebSocket server and MCP adapter for mushroomdb
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
#![allow(deprecated)] // serve() used for test convenience; production code uses serve_with_role_tokens
use arrow_array::{Array, StringArray};
use arrow_ipc::reader::StreamReader;
use axum::body::{to_bytes, Body};
use axum::http::{Request, StatusCode};
use axum::Router;
use core_api::{
    json_to_value, schema::Schema, Explanation, FkSkip, IngestReport, Predicate, PredicateSummary,
    RoleDef, RuleDef, RuleStats, SharedDb, Stats, Value,
};
use serde_json::{json, Value as Json};
#[cfg(feature = "embed-ui")]
use server::router_with_embedded_ui;
use server::{router, router_with_auth, router_with_role_tokens, router_with_ui, serve};
use std::io::Cursor;
use std::path::PathBuf;
use tower::ServiceExt;

fn tmp(name: &str) -> PathBuf {
    let d = std::env::temp_dir().join(format!("graphdb-http-{}-{}", name, std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    d
}

fn open(name: &str) -> (Router, SharedDb) {
    let db = SharedDb::open(&tmp(name)).unwrap();
    (router(db.clone()), db)
}

async fn send(app: Router, req: Request<Body>) -> (StatusCode, Vec<u8>, Option<String>) {
    let res = app.oneshot(req).await.unwrap();
    let status = res.status();
    let ctype = res
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .map(str::to_string);
    let body = to_bytes(res.into_body(), usize::MAX)
        .await
        .unwrap()
        .to_vec();
    (status, body, ctype)
}

fn json_req(method: &str, uri: &str, body: Json) -> Request<Body> {
    Request::builder()
        .method(method)
        .uri(uri)
        .header(axum::http::header::CONTENT_TYPE, "application/json")
        .body(Body::from(body.to_string()))
        .unwrap()
}

fn get(uri: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .body(Body::empty())
        .unwrap()
}

fn seed_person(db: &SharedDb, key: &str) {
    db.write()
        .insert_node("Person", key, vec![("id".into(), Value::Str(key.into()))])
        .unwrap();
}

fn parse_json(bytes: &[u8]) -> Json {
    serde_json::from_slice(bytes)
        .unwrap_or_else(|e| panic!("json: {e}: {}", String::from_utf8_lossy(bytes)))
}

#[tokio::test]
async fn health_is_unauthenticated() {
    // boot with token Some("t"); GET /health must 200 without Authorization
    let db = SharedDb::open(&tmp("health-unauth")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let (status, body, _) = send(app, get("/health")).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["ok"], json!(true));
    assert_eq!(v["nodes"], json!(0));
    assert_eq!(v["edges"], json!(0));
    assert_eq!(v["addr"], json!("127.0.0.1:8080"));
}

#[tokio::test]
async fn health_reports_counts() {
    let (app, db) = open("health-counts");
    seed_person(&db, "a");
    seed_person(&db, "b");
    db.write().insert_edge("KNOWS", "a", "b").unwrap();
    let (status, body, _) = send(app, get("/health")).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["ok"], json!(true));
    assert_eq!(v["nodes"], json!(2));
    assert_eq!(v["edges"], json!(1));
    assert_eq!(v["addr"], json!("127.0.0.1:8080"));
}

#[tokio::test]
async fn query_without_bearer_is_401_when_token_configured() {
    // POST /query with no header → 401 {"error":"..."}
    let db = SharedDb::open(&tmp("query-no-bearer")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let (status, body, _) = send(
        app,
        json_req("POST", "/query", json!({"cypher": "MATCH (n) RETURN n"})),
    )
    .await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    let v = parse_json(&body);
    assert!(
        v["error"].as_str().is_some_and(|s| !s.is_empty()),
        "401 body must be {{\"error\":\"...\"}}, got {v}"
    );
}

#[tokio::test]
async fn query_with_bearer_succeeds_when_token_configured() {
    // Authorization: Bearer t → 200
    let db = SharedDb::open(&tmp("query-bearer")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let req = Request::builder()
        .method("POST")
        .uri("/query?format=json")
        .header(axum::http::header::CONTENT_TYPE, "application/json")
        .header(axum::http::header::AUTHORIZATION, "Bearer t")
        .body(Body::from(
            json!({"cypher": "MATCH (n) RETURN n"}).to_string(),
        ))
        .unwrap();
    let (status, _, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn query_with_query_token_succeeds_when_token_configured() {
    let db = SharedDb::open(&tmp("query-qs-token")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let (status, _, _) = send(
        app,
        json_req(
            "POST",
            "/query?token=t&format=json",
            json!({"cypher": "MATCH (n) RETURN n"}),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn query_with_wrong_query_token_is_401() {
    let db = SharedDb::open(&tmp("query-qs-wrong")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/query?token=wrong",
            json!({"cypher": "MATCH (n) RETURN n"}),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    let v = parse_json(&body);
    assert!(
        v["error"].as_str().is_some_and(|s| !s.is_empty()),
        "401 body must be {{\"error\":\"...\"}}, got {v}"
    );
}

#[tokio::test]
async fn watch_with_query_token_is_not_401_when_token_configured() {
    let db = SharedDb::open(&tmp("watch-qs-token")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let (status, _, _) = send(app, get("/watch?token=t")).await;
    assert_ne!(
        status,
        StatusCode::UNAUTHORIZED,
        "GET /watch?token=t must pass auth (upgrade may still fail without WS headers)"
    );
}

#[tokio::test]
async fn query_token_percent_decoded_matches_configured_token() {
    let db = SharedDb::open(&tmp("query-qs-encoded-slash")).unwrap();
    let app = router_with_auth(db, Some("a/b".into()));
    let (status, _, _) = send(
        app,
        json_req(
            "POST",
            "/query?token=a%2Fb&format=json",
            json!({"cypher": "MATCH (n) RETURN n"}),
        ),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::OK,
        "configured token \"a/b\" must match URL-encoded ?token=a%2Fb"
    );

    let db = SharedDb::open(&tmp("query-qs-encoded-plus")).unwrap();
    let app = router_with_auth(db, Some("a+b".into()));
    let (status, _, _) = send(
        app,
        json_req(
            "POST",
            "/query?token=a%2Bb&format=json",
            json!({"cypher": "MATCH (n) RETURN n"}),
        ),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::OK,
        "configured token \"a+b\" must match URL-encoded ?token=a%2Bb"
    );
}

#[tokio::test]
async fn watch_with_url_encoded_query_token_is_not_401() {
    let db = SharedDb::open(&tmp("watch-qs-encoded")).unwrap();
    let app = router_with_auth(db, Some("a/b".into()));
    let (status, _, _) = send(app, get("/watch?token=a%2Fb")).await;
    assert_ne!(
        status,
        StatusCode::UNAUTHORIZED,
        "GET /watch?token=a%2Fb must pass auth for configured token \"a/b\""
    );
}

async fn send_headers(
    app: Router,
    req: Request<Body>,
) -> (StatusCode, Vec<u8>, axum::http::HeaderMap) {
    let res = app.oneshot(req).await.unwrap();
    let status = res.status();
    let headers = res.headers().clone();
    let body = to_bytes(res.into_body(), usize::MAX)
        .await
        .unwrap()
        .to_vec();
    (status, body, headers)
}

#[tokio::test]
async fn html_query_token_sets_auth_cookie() {
    let ui = tmp("ui-cookie");
    std::fs::create_dir_all(&ui).unwrap();
    std::fs::write(
        ui.join("index.html"),
        "<!doctype html><title>graph-db</title>",
    )
    .unwrap();
    let db = SharedDb::open(&tmp("ui-cookie-db")).unwrap();
    let app = router_with_ui(db, &ui, Some("t".into()));
    let (status, _, headers) = send_headers(app, get("/?token=t")).await;
    assert_eq!(status, StatusCode::OK);
    let cookie = headers
        .get(axum::http::header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        cookie.contains("mushroomdb_token=t"),
        "Set-Cookie must include mushroomdb_token=, got {cookie:?}"
    );
    assert!(
        cookie.contains("Path=/"),
        "Set-Cookie Path=/, got {cookie:?}"
    );
    assert!(
        cookie.contains("SameSite=Lax"),
        "Set-Cookie SameSite=Lax, got {cookie:?}"
    );
    assert!(
        cookie.contains("HttpOnly"),
        "Set-Cookie HttpOnly, got {cookie:?}"
    );
}

#[tokio::test]
async fn missing_asset_with_cookie_is_404_not_401() {
    let db = SharedDb::open(&tmp("asset-cookie")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let req = Request::builder()
        .method("GET")
        .uri("/no-such.js")
        .header(axum::http::header::COOKIE, "mushroomdb_token=t")
        .body(Body::empty())
        .unwrap();
    let (status, _, _) = send(app, req).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn missing_asset_without_auth_is_401() {
    let db = SharedDb::open(&tmp("asset-noauth")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let (status, _, _) = send(app, get("/no-such.js")).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn stats_with_cookie_succeeds_when_token_configured() {
    let db = SharedDb::open(&tmp("stats-cookie")).unwrap();
    let app = router_with_auth(db, Some("t".into()));
    let req = Request::builder()
        .method("GET")
        .uri("/stats")
        .header(axum::http::header::COOKIE, "mushroomdb_token=t")
        .body(Body::empty())
        .unwrap();
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert!(v.get("nodes_live").is_some(), "/stats JSON, got {v}");
}

/// Binding: POST /query default is Arrow IPC stream; StreamReader reads the batch.
#[tokio::test]
async fn query_default_returns_arrow_ipc() {
    let (app, db) = open("query-arrow");
    seed_person(&db, "p1");

    let (status, body, ctype) = send(
        app,
        json_req(
            "POST",
            "/query",
            json!({"cypher": "MATCH (t:Person {id: $tid}) RETURN t", "params": {"tid": "p1"}}),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        ctype.as_deref(),
        Some("application/vnd.apache.arrow.stream")
    );

    let mut reader = StreamReader::try_new(Cursor::new(body), None).unwrap();
    let batch = reader.next().expect("one batch").unwrap();
    assert!(reader.next().is_none(), "single batch stream");
    assert_eq!(batch.num_rows(), 1);
    assert_eq!(batch.schema().field(0).name(), "t");
    let col = batch
        .column(0)
        .as_any()
        .downcast_ref::<StringArray>()
        .unwrap();
    assert_eq!(col.value(0), "p1");
}

/// Binding: ?format=json is columns + rows of JSON scalars, field-by-field.
#[tokio::test]
async fn query_format_json_matches_columns_and_rows() {
    let (app, db) = open("query-json");
    seed_person(&db, "p1");

    let (status, body, ctype) = send(
        app,
        json_req(
            "POST",
            "/query?format=json",
            json!({
                "cypher": "MATCH (t:Person {id: $tid}) RETURN t",
                "params": {"tid": "p1"}
            }),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(v["columns"], json!(["t"]));
    assert_eq!(v["rows"], json!([["p1"]]));
}

/// Binding: COUNT(*) via ?format=json → {"columns":["COUNT(*)"],"rows":[[n]]}.
#[tokio::test]
async fn query_count_star_format_json_wire_shape() {
    let (app, db) = open("query-count-star");
    seed_person(&db, "p1");
    seed_person(&db, "p2");
    seed_person(&db, "p3");

    let (status, body, ctype) = send(
        app,
        json_req(
            "POST",
            "/query?format=json",
            json!({"cypher": "MATCH (p:Person) RETURN COUNT(*)"}),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(
        v["columns"],
        json!(["COUNT(*)"]),
        "column name must be COUNT(*)"
    );
    assert_eq!(
        v["rows"],
        json!([[3]]),
        "three Person nodes must be counted"
    );
}

/// Binding: bad Cypher is 400 {"error": detail} with a parse:-prefixed detail.
#[tokio::test]
async fn query_bad_cypher_is_400_with_parse_prefix() {
    let (app, _) = open("query-bad");

    let (status, body, _) = send(
        app,
        json_req("POST", "/query", json!({"cypher": "MATCH (n)"})),
    )
    .await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().expect("error string");
    assert!(
        err.starts_with("parse:"),
        "expected parse:-prefixed detail, got {err}"
    );
}

/// Binding: GET /stats is Stats JSON; Serialize round-trips field-by-field.
#[tokio::test]
async fn stats_round_trips_serialize() {
    let (app, db) = open("stats");
    seed_person(&db, "p1");

    let (status, body, ctype) = send(app, get("/stats")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(v["nodes_live"], json!(1));
    assert_eq!(v["nodes_tombstoned"], json!(0));
    assert_eq!(v["edges"], json!(0));
    assert_eq!(v["rules"], json!([]));

    let live = Stats {
        nodes_live: 1,
        nodes_tombstoned: 2,
        edges: 3,
        rules: vec![RuleStats {
            name: "r".into(),
            edges: 4,
            tripped: true,
            fires: 5,
            approximate: false,
        }],
    };
    let encoded = serde_json::to_value(&live).expect("Stats: Serialize");
    assert_eq!(encoded["nodes_live"], json!(1));
    assert_eq!(encoded["nodes_tombstoned"], json!(2));
    assert_eq!(encoded["edges"], json!(3));
    assert_eq!(encoded["rules"][0]["name"], json!("r"));
    assert_eq!(encoded["rules"][0]["edges"], json!(4));
    assert_eq!(encoded["rules"][0]["tripped"], json!(true));
    assert_eq!(encoded["rules"][0]["fires"], json!(5));
    assert_eq!(encoded["rules"][0]["approximate"], json!(false));
}

/// Binding: POST /ingest converts parsed rows and returns IngestReport JSON.
#[tokio::test]
async fn ingest_happy_path() {
    let (app, db) = open("ingest-ok");
    db.write().insert_node("Org", "acme", vec![]).unwrap();

    let (status, body, ctype) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({
                "label": "Person",
                "rows": [{"id": "p1", "org_id": "acme", "name": "ada"}],
                "options": {}
            }),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(v["inserted"], json!(1));
    assert_eq!(v["row_errors"], json!([]));
    assert_eq!(v["rules_created"], json!(["auto_fk_person_org_id"]));
    assert_eq!(v["skipped_fk_fields"], json!([]));
    assert!(db.read().has_node("p1"));
}

/// Binding: HTTP /ingest is one WAL commit, not a loop of insert_node.
#[tokio::test]
async fn ingest_many_rows_is_one_wal_commit() {
    let dir = tmp("ingest-one-wal");
    let db = SharedDb::open(&dir).unwrap();
    let app = router(db.clone());
    let (status, _, _) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({
                "label": "Person",
                "rows": [{"id": "a"}, {"id": "b"}, {"id": "c"}],
                "options": {"auto_fk": "off"}
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(core_api::wal_commit_count_at(&dir).unwrap(), 1);
    assert_eq!(db.read().node_count(), 3);
}

/// Binding: ingest shape failures (not an array of objects) are 400 {"error": ...}.
#[tokio::test]
async fn ingest_shape_error_is_400() {
    let (app, _) = open("ingest-shape");

    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({"label": "Person", "rows": {"id": "p1"}}),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().expect("error string");
    assert!(
        err.contains("array of objects"),
        "expected ingest shape detail, got {err}"
    );
}

/// Binding: GET /explain?a=&b= is a JSON array of Explanation.
#[tokio::test]
async fn explain_happy_path() {
    let (app, db) = open("explain-ok");
    {
        let mut w = db.write();
        w.insert_node("Org", "o1", vec![]).unwrap();
        w.create_rule(RuleDef {
            name: "works_at".into(),
            src_label: "Person".into(),
            dst_label: "Org".into(),
            predicate: Predicate::KeyMatch {
                field: "org_id".into(),
            },
            edge_type: "WORKS_AT".into(),
            weight_prop: None,
            max_edges: None,
            approximate: false,
            via_label: None,
            via_edge: None,
            via_dir: None,
        })
        .unwrap();
        w.insert_node(
            "Person",
            "p1",
            vec![("org_id".into(), Value::Str("o1".into()))],
        )
        .unwrap();
    }

    let (status, body, ctype) = send(app, get("/explain?a=p1&b=o1")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert!(v.is_array());
    assert_eq!(v[0]["rule"], json!("works_at"));
    assert_eq!(v[0]["edge_type"], json!("WORKS_AT"));
    assert_eq!(v[0]["src_key"], json!("p1"));
    assert_eq!(v[0]["dst_key"], json!("o1"));
    assert_eq!(v[0]["weight"], Json::Null);
    assert_eq!(v[0]["predicate"]["kind"], json!("key_match"));
    assert_eq!(v[0]["predicate"]["fields"], json!(["org_id"]));
    let pred = v[0]["predicate"].as_object().expect("predicate object");
    for key in ["min", "tolerance", "km", "parts"] {
        assert!(
            pred.contains_key(key),
            "leaf JSON must present {key} as null, not omit it"
        );
        assert_eq!(pred[key], Json::Null);
    }
}

/// Binding: /explain JSON includes `predicate` with snake_case kind and parts.
#[tokio::test]
async fn explain_predicate_all_json_shape() {
    let (app, db) = open("explain-all");
    {
        let mut w = db.write();
        w.insert_node(
            "Org",
            "o1",
            vec![
                ("ind".into(), Value::Str("arch".into())),
                ("tags".into(), Value::List(vec![Value::Str("x".into())])),
            ],
        )
        .unwrap();
        w.create_rule(RuleDef {
            name: "both".into(),
            src_label: "Person".into(),
            dst_label: "Org".into(),
            predicate: Predicate::All(vec![
                Predicate::FieldEqual {
                    field: "ind".into(),
                },
                Predicate::Overlap {
                    field: "tags".into(),
                    min: 0.5,
                },
            ]),
            edge_type: "BOTH".into(),
            weight_prop: Some("score".into()),
            max_edges: None,
            approximate: false,
            via_label: None,
            via_edge: None,
            via_dir: None,
        })
        .unwrap();
        w.insert_node(
            "Person",
            "p1",
            vec![
                ("ind".into(), Value::Str("arch".into())),
                ("tags".into(), Value::List(vec![Value::Str("x".into())])),
            ],
        )
        .unwrap();
    }

    let (status, body, _) = send(app, get("/explain?a=p1&b=o1")).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v[0]["predicate"]["kind"], json!("all"));
    assert_eq!(v[0]["predicate"]["fields"], json!(["ind", "tags"]));
    assert_eq!(v[0]["predicate"]["parts"][0]["kind"], json!("field_equal"));
    assert_eq!(v[0]["predicate"]["parts"][1]["kind"], json!("overlap"));
    assert_eq!(v[0]["predicate"]["parts"][1]["min"], json!(0.5));
}

/// Binding: unknown explain key is 400 {"error": ...}.
#[tokio::test]
async fn explain_unknown_key_is_400() {
    let (app, db) = open("explain-miss");
    seed_person(&db, "p1");

    let (status, body, _) = send(app, get("/explain?a=p1&b=ghost")).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().expect("error string");
    assert!(
        err.contains("ghost"),
        "expected unknown key in detail, got {err}"
    );
}

/// Binding: neighborhood honors depth and dir; JSON is the ResultSet shape.
#[tokio::test]
async fn neighborhood_depth_and_dir() {
    let (app, db) = open("nbhd");
    {
        let mut w = db.write();
        w.insert_node("Person", "a", vec![]).unwrap();
        w.insert_node("Person", "b", vec![]).unwrap();
        w.insert_node("Person", "c", vec![]).unwrap();
        w.insert_edge("KNOWS", "a", "b").unwrap();
        w.insert_edge("KNOWS", "b", "c").unwrap();
    }

    let (status, body, ctype) =
        send(app.clone(), get("/node/a/neighborhood?depth=1&dir=out")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let hop1 = parse_json(&body);
    assert_eq!(hop1["columns"], json!(["key", "label", "depth"]));
    assert_eq!(hop1["rows"], json!([["b", "Person", 1]]));

    let (_, body, _) = send(app.clone(), get("/node/a/neighborhood?depth=2&dir=out")).await;
    let hop2 = parse_json(&body);
    assert_eq!(
        hop2["rows"],
        json!([["b", "Person", 1], ["c", "Person", 2]])
    );

    let (_, body, _) = send(app, get("/node/b/neighborhood?depth=1&dir=in")).await;
    let incoming = parse_json(&body);
    assert_eq!(incoming["rows"], json!([["a", "Person", 1]]));
}

/// Binding: optional `edge_types` (comma-separated) filters like the MCP tool.
#[tokio::test]
async fn neighborhood_edge_types_filter() {
    let (app, db) = open("nbhd-etypes");
    {
        let mut w = db.write();
        w.insert_node("Person", "a", vec![]).unwrap();
        w.insert_node("Person", "b", vec![]).unwrap();
        w.insert_node("Person", "c", vec![]).unwrap();
        w.insert_edge("KNOWS", "a", "b").unwrap();
        w.insert_edge("LIKES", "a", "c").unwrap();
    }

    let (status, body, _) = send(app.clone(), get("/node/a/neighborhood?depth=1&dir=out")).await;
    assert_eq!(status, StatusCode::OK);
    let unfiltered = parse_json(&body);
    assert_eq!(
        unfiltered["rows"],
        json!([["b", "Person", 1], ["c", "Person", 1]])
    );

    let (_, body, _) = send(
        app.clone(),
        get("/node/a/neighborhood?depth=1&dir=out&edge_types=KNOWS"),
    )
    .await;
    let knows = parse_json(&body);
    assert_eq!(knows["rows"], json!([["b", "Person", 1]]));

    let (_, body, _) = send(
        app,
        get("/node/a/neighborhood?depth=1&dir=out&edge_types=KNOWS,LIKES"),
    )
    .await;
    let both = parse_json(&body);
    assert_eq!(
        both["rows"],
        json!([["b", "Person", 1], ["c", "Person", 1]])
    );
}

/// Binding: GET /node/{key} is NodeInfo JSON with untagged Value props.
#[tokio::test]
async fn node_info_json_shape() {
    let (app, db) = open("node-info");
    {
        let mut w = db.write();
        w.insert_node(
            "Person",
            "p1",
            vec![
                ("years".into(), Value::Int(8)),
                ("name".into(), Value::Str("ada".into())),
                ("ok".into(), Value::Bool(true)),
                ("rating".into(), Value::Float(0.5)),
                (
                    "tags".into(),
                    Value::List(vec![Value::Str("x".into()), Value::Str("y".into())]),
                ),
            ],
        )
        .unwrap();
    }

    let (status, body, ctype) = send(app, get("/node/p1")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(v["key"], json!("p1"));
    assert_eq!(v["label"], json!("Person"));
    assert_eq!(v["props"]["name"], json!("ada"));
    assert_eq!(v["props"]["ok"], json!(true));
    assert_eq!(v["props"]["years"], json!(8));
    assert_eq!(v["props"]["rating"], json!(0.5));
    assert_eq!(v["props"]["tags"], json!(["x", "y"]));
    // BTreeMap iteration is name-sorted; this assertion also depends on
    // serde_json's preserve_order feature (object keys keep insertion order).
    let keys: Vec<&str> = v["props"]
        .as_object()
        .expect("props object")
        .keys()
        .map(String::as_str)
        .collect();
    assert_eq!(keys, vec!["name", "ok", "rating", "tags", "years"]);
}

/// Binding: unknown GET /node/{key} is 404 {"error":"node key not found: ..."}.
#[tokio::test]
async fn node_info_unknown_key_is_404() {
    let (app, _) = open("node-info-miss");
    let (status, body, _) = send(app, get("/node/ghost")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    let v = parse_json(&body);
    assert_eq!(v, json!({"error": "node key not found: ghost"}));
}

/// Binding: GET /node/{key}/edges is {"edges":[EdgeInfo...]} with derived flags, sorted.
#[tokio::test]
async fn node_edges_json_shape_user_and_derived() {
    let (app, db) = open("node-edges");
    {
        let mut w = db.write();
        w.insert_node("Org", "acme", vec![]).unwrap();
        w.create_rule(core_api::RuleDef {
            name: "works_at".into(),
            src_label: "Person".into(),
            dst_label: "Org".into(),
            predicate: core_api::Predicate::KeyMatch {
                field: "org_id".into(),
            },
            edge_type: "WORKS_AT".into(),
            weight_prop: None,
            max_edges: None,
            approximate: false,
            via_label: None,
            via_edge: None,
            via_dir: None,
        })
        .unwrap();
        w.insert_node(
            "Person",
            "p1",
            vec![("org_id".into(), Value::Str("acme".into()))],
        )
        .unwrap();
        w.insert_node("Person", "p2", vec![]).unwrap();
        w.insert_edge("KNOWS", "p1", "p2").unwrap();
    }

    let (status, body, ctype) = send(app, get("/node/p1/edges")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(
        v,
        json!({
            "edges": [
                {
                    "edge_type": "KNOWS",
                    "src_key": "p1",
                    "dst_key": "p2",
                    "derived": false
                },
                {
                    "edge_type": "WORKS_AT",
                    "src_key": "p1",
                    "dst_key": "acme",
                    "derived": true
                }
            ]
        })
    );
}

/// Binding: unknown GET /node/{key}/edges is 404 {"error":"node key not found: ..."}.
#[tokio::test]
async fn node_edges_unknown_key_is_404() {
    let (app, _) = open("node-edges-miss");
    let (status, body, _) = send(app, get("/node/ghost/edges")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    let v = parse_json(&body);
    assert_eq!(v, json!({"error": "node key not found: ghost"}));
}

/// Binding: unknown neighborhood key is 400.
#[tokio::test]
async fn neighborhood_unknown_key_is_400() {
    let (app, _) = open("nbhd-miss");
    let (status, body, _) = send(app, get("/node/ghost/neighborhood")).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().expect("error string");
    assert!(
        err.contains("ghost"),
        "expected unknown key in detail, got {err}"
    );
}

/// Binding: ServeDir is the fallback; `/stats` stays JSON.
#[tokio::test]
async fn ui_fallback_serves_static_and_stats_stays_json() {
    let ui = tmp("ui-dist");
    std::fs::create_dir_all(&ui).unwrap();
    std::fs::write(
        ui.join("index.html"),
        "<!doctype html><title>graph-db</title>",
    )
    .unwrap();
    std::fs::write(ui.join("hello.txt"), "hello-static").unwrap();

    let db = SharedDb::open(&tmp("ui-api")).unwrap();
    let app = router_with_ui(db, &ui, None);

    let (st, body, _) = send(app.clone(), get("/hello.txt")).await;
    assert_eq!(st, StatusCode::OK);
    assert_eq!(body, b"hello-static");

    let (st, body, _) = send(app.clone(), get("/")).await;
    assert_eq!(st, StatusCode::OK);
    let html = String::from_utf8_lossy(&body);
    assert!(
        html.contains("graph-db"),
        "GET / should serve index.html, got {html}"
    );

    let (st, body, ctype) = send(app, get("/stats")).await;
    assert_eq!(st, StatusCode::OK);
    let ctype = ctype.expect("stats content-type");
    assert!(ctype.contains("json"), "/stats must stay JSON, got {ctype}");
    let j = parse_json(&body);
    assert!(
        j.get("nodes_live").is_some(),
        "/stats JSON must include nodes_live, got {j}"
    );
}

/// Binding: serve binds port 0 and reports the local addr via oneshot readiness.
#[tokio::test]
async fn serve_readiness_returns_local_addr() {
    let db = SharedDb::open(&tmp("serve")).unwrap();
    let (tx, rx) = tokio::sync::oneshot::channel();
    let handle = tokio::spawn(async move {
        serve(db, "127.0.0.1:0".parse().unwrap(), tx, None)
            .await
            .unwrap();
    });
    let addr = rx.await.expect("readiness");
    assert_ne!(addr.port(), 0, "ephemeral port must be resolved");
    handle.abort();
}

/// Binding: POST /ingest optional `edges` shares the node ingest batch.
#[tokio::test]
async fn ingest_edges_inserts_user_edge() {
    let (app, db) = open("ingest-edges");
    db.write().insert_node("Person", "a", vec![]).unwrap();
    db.write().insert_node("Person", "b", vec![]).unwrap();

    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({
                "label": "Person",
                "rows": [],
                "edges": [{"edge_type": "KNOWS", "src": "a", "dst": "b"}]
            }),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["edges_inserted"], json!(1));
    let edges = db.read().node_edges("a").unwrap();
    assert!(
        edges.iter().any(|e| {
            e.edge_type == "KNOWS" && e.src_key == "a" && e.dst_key == "b" && !e.derived
        }),
        "expected user KNOWS a→b, got {edges:?}"
    );
}

/// Binding: unknown src/dst on ingest edges is 400 with the engine key message.
#[tokio::test]
async fn ingest_edges_unknown_endpoint_is_400() {
    let (app, _) = open("ingest-edge-miss");
    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({
                "label": "Person",
                "rows": [],
                "edges": [{"edge_type": "KNOWS", "src": "ghost", "dst": "ghost"}]
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().unwrap();
    assert!(
        err.contains("node key not found"),
        "expected KeyNotFound register, got {err}"
    );
}

/// Binding: a bad edge rejects the whole ingest; nodes from the same body
/// are not persisted.
#[tokio::test]
async fn ingest_bad_edge_is_atomic() {
    let (app, db) = open("ingest-atomic");
    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({
                "label": "Person",
                "rows": [{"id": "newbie"}],
                "edges": [{"edge_type": "KNOWS", "src": "newbie", "dst": "ghost"}]
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().unwrap();
    assert!(
        err.contains("node key not found"),
        "preview error, got {err}"
    );
    assert!(
        !db.read().has_node("newbie"),
        "newbie must not persist after a rejected mixed batch"
    );
}

/// Binding: a duplicate user edge is a no-op and counts as 0 inserts.
#[tokio::test]
async fn ingest_duplicate_edge_counts_zero() {
    let (app, db) = open("ingest-dup-edge");
    {
        let mut w = db.write();
        w.insert_node("Person", "a", vec![]).unwrap();
        w.insert_node("Person", "b", vec![]).unwrap();
        w.insert_edge("KNOWS", "a", "b").unwrap();
    }
    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/ingest",
            json!({
                "label": "Person",
                "rows": [],
                "edges": [{"edge_type": "KNOWS", "src": "a", "dst": "b"}]
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["edges_inserted"], json!(0));
}

/// Binding: POST /rules accepts RuleDef JSON; validation errors are 400 verbatim.
#[tokio::test]
async fn create_rule_http_and_validation() {
    let (app, db) = open("rules-post");
    db.write()
        .insert_node("Org", "o1", vec![("founded_year".into(), Value::Int(2010))])
        .unwrap();
    db.write()
        .insert_node("Org", "o2", vec![("founded_year".into(), Value::Int(2011))])
        .unwrap();

    let (status, body, _) = send(
        app.clone(),
        json_req(
            "POST",
            "/rules",
            json!({
                "name": "founded_within",
                "src_label": "Org",
                "dst_label": "Org",
                "predicate": {"NumericWithin": {"field": "founded_year", "tolerance": 2.0}},
                "edge_type": "FOUNDED_WITHIN",
                "weight_prop": "score",
                "max_edges": null
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        parse_json(&body),
        json!({"ok": true, "name": "founded_within"})
    );
    assert!(db.read().rules().iter().any(|r| r.name == "founded_within"));
    assert_eq!(
        db.read()
            .rules()
            .iter()
            .find(|r| r.name == "founded_within")
            .unwrap()
            .max_edges,
        Some(32),
        "JSON null max_edges fills default scored top-k"
    );

    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/rules",
            json!({
                "name": "",
                "src_label": "Org",
                "dst_label": "Org",
                "predicate": {"NumericWithin": {"field": "founded_year", "tolerance": 2.0}},
                "edge_type": "FOUNDED_WITHIN",
                "weight_prop": "score",
                "max_edges": null
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    let v = parse_json(&body);
    let err = v["error"].as_str().unwrap();
    assert!(
        err.contains("invalid rule:"),
        "engine message verbatim, got {err}"
    );
}

/// Binding: omitted JSON `max_edges` fills `default_max_edges` (scored=32, KeyMatch=1).
#[tokio::test]
async fn create_rule_http_omitted_max_edges_fills_default() {
    let (app, db) = open("rules-omit-max");
    db.write().insert_node("Org", "o1", vec![]).unwrap();
    db.write()
        .insert_node(
            "Person",
            "p1",
            vec![("org_id".into(), Value::Str("o1".into()))],
        )
        .unwrap();

    let (status, _, _) = send(
        app.clone(),
        json_req(
            "POST",
            "/rules",
            json!({
                "name": "works_at",
                "src_label": "Person",
                "dst_label": "Org",
                "predicate": {"KeyMatch": {"field": "org_id"}},
                "edge_type": "WORKS_AT",
                "weight_prop": null
            }),
        ),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(
        db.read()
            .rules()
            .iter()
            .find(|r| r.name == "works_at")
            .unwrap()
            .max_edges,
        Some(1)
    );
}

/// Binding: Serialize exists on the wire types (additive derives).
#[test]
fn wire_types_serialize() {
    let stats = Stats {
        nodes_live: 0,
        nodes_tombstoned: 0,
        edges: 0,
        rules: vec![],
    };
    serde_json::to_value(&stats).unwrap();
    serde_json::to_value(&RuleStats {
        name: "n".into(),
        edges: 0,
        tripped: false,
        fires: 0,
        approximate: false,
    })
    .unwrap();
    serde_json::to_value(&IngestReport {
        inserted: 0,
        row_errors: vec![],
        rules_created: vec![],
        skipped_fk_fields: vec![FkSkip {
            field: "org_id".into(),
            reason: "no matching target keys".into(),
        }],
        edges_inserted: 0,
    })
    .unwrap();
    let expl = serde_json::to_value(&Explanation {
        rule: "r".into(),
        edge_type: "E".into(),
        src_key: "a".into(),
        dst_key: "b".into(),
        weight: Some(0.5),
        predicate: PredicateSummary::from(&Predicate::KeyMatch { field: "fk".into() }),
    })
    .unwrap();
    assert_eq!(expl["predicate"]["kind"], json!("key_match"));
    assert_eq!(expl["predicate"]["fields"], json!(["fk"]));
    let pred = expl["predicate"].as_object().expect("predicate object");
    for key in ["min", "tolerance", "km", "parts"] {
        assert!(pred.contains_key(key), "wire summary must include {key}");
        assert_eq!(pred[key], Json::Null);
    }
    assert_eq!(
        json_to_value(json!("p1")),
        Some(Value::Str("p1".into())),
        "params reuse json_to_value"
    );
}

/// Cypher CREATE over HTTP uses the write lock, WAL is fsynced before the
/// response is sent, and the created node survives a DB re-open.
#[tokio::test]
async fn cypher_write_over_http_is_durable() {
    let dir = tmp("cypher-write-http");
    let db = SharedDb::open(&dir).unwrap();
    let app = router(db.clone());

    // CREATE via POST /query?format=json
    let (status, body, ctype) = send(
        app.clone(),
        json_req(
            "POST",
            "/query?format=json",
            json!({"cypher": "CREATE (n:Person {id: 'alice'})"}),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK, "write must succeed");
    assert_eq!(ctype.as_deref(), Some("application/json"));
    let v = parse_json(&body);
    assert_eq!(
        v["columns"],
        json!(["created", "properties_set", "deleted"])
    );
    let rows = v["rows"].as_array().expect("rows array");
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0][0], json!(1), "created=1");
    assert_eq!(rows[0][1], json!(0), "properties_set=0");
    assert_eq!(rows[0][2], json!(0), "deleted=0");

    // Read back via the same SharedDb handle to confirm node is live.
    assert!(
        db.read().has_node("alice"),
        "node must be queryable immediately"
    );

    // Drop the db + app, re-open from disk: WAL must have been fsynced.
    drop(app);
    drop(db);
    let db2 = SharedDb::open(&dir).unwrap();
    assert!(
        db2.read().has_node("alice"),
        "node must survive DB re-open (WAL fsynced before HTTP response)"
    );
}

#[cfg(feature = "embed-ui")]
#[tokio::test]
async fn embedded_ui_serves_index_and_stats_wins() {
    let db = SharedDb::open(&tmp("embed-ui")).unwrap();
    let app = router_with_embedded_ui(db);
    let (st, body, ctype) = send(app.clone(), get("/")).await;
    assert_eq!(st, StatusCode::OK);
    let html = String::from_utf8_lossy(&body);
    assert!(
        html.contains("mushroomdb") || html.contains("<!doctype") || html.contains("<!DOCTYPE"),
        "embedded GET / should be index.html, got {html}"
    );
    let ctype = ctype.unwrap_or_default();
    assert!(
        ctype.contains("html"),
        "index content-type html, got {ctype}"
    );

    let (st, body, ctype) = send(app, get("/stats")).await;
    assert_eq!(st, StatusCode::OK);
    let ctype = ctype.expect("stats content-type");
    assert!(ctype.contains("json"), "/stats must stay JSON, got {ctype}");
    let j = parse_json(&body);
    assert!(j.get("nodes_live").is_some(), "/stats JSON, got {j}");
}

// ── HTTP params tests ─────────────────────────────────────────────────────────

/// Params round-trip over HTTP: $age filters nodes, returns correct rows.
#[tokio::test]
async fn http_params_read_round_trip() {
    let (app, db) = open("http-params-read");
    {
        let mut w = db.write();
        w.insert_node("HP", "alice", vec![("age".into(), Value::Int(30))])
            .unwrap();
        w.insert_node("HP", "bob", vec![("age".into(), Value::Int(25))])
            .unwrap();
    }

    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/query?format=json",
            json!({
                "cypher": "MATCH (n:HP) WHERE n.age = $age RETURN n",
                "params": {"age": 30}
            }),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let rows = v["rows"].as_array().expect("rows array");
    assert_eq!(rows.len(), 1, "must match exactly the node with age=30");
    // The node key "alice" should appear in the result row.
    let row_str = rows[0].to_string();
    assert!(
        row_str.contains("alice"),
        "returned node must be alice: {row_str}"
    );
}

/// Injection safety at the HTTP layer: a param value containing Cypher syntax
/// must be treated as a literal string, not executed.
#[tokio::test]
async fn http_params_injection_safe() {
    let (app, db) = open("http-params-injection");
    {
        let mut w = db.write();
        w.insert_node("HPI", "real_node", vec![]).unwrap();
    }

    // The param value contains Cypher meta-characters.  If the value were
    // interpolated into the query string, the query would parse differently
    // and could return unexpected rows.  As a literal, no node has id equal
    // to the injection payload, so 0 rows are returned.
    let (status, body, _) = send(
        app,
        json_req(
            "POST",
            "/query?format=json",
            json!({
                "cypher": "MATCH (n:HPI {id: $id}) RETURN n",
                "params": {"id": "' RETURN 1//"}
            }),
        ),
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let rows = v["rows"].as_array().expect("rows array");
    assert_eq!(
        rows.len(),
        0,
        "injection payload must not return rows: {rows:?}"
    );
}

/// Write with SET n.p = $newval over HTTP is durable across DB re-open.
#[tokio::test]
async fn http_params_write_set_is_durable() {
    let dir = tmp("http-params-write");
    let db = SharedDb::open(&dir).unwrap();
    let app = router(db.clone());

    // Insert the node to update.
    {
        let mut w = db.write();
        w.insert_node("HPW", "target", vec![("score".into(), Value::Int(0))])
            .unwrap();
    }

    // MATCH…SET with $newval over HTTP.
    let (status, body, _) = send(
        app.clone(),
        json_req(
            "POST",
            "/query?format=json",
            json!({
                "cypher": "MATCH (n:HPW) WHERE n.score = 0 SET n.score = $newval",
                "params": {"newval": 99}
            }),
        ),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::OK,
        "write must succeed: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(v["rows"][0][1], json!(1), "properties_set must be 1");

    // Verify durability: drop handles and re-open.
    drop(app);
    drop(db);
    let db2 = SharedDb::open(&dir).unwrap();
    // Read back the updated score via a direct query.
    let rs = db2
        .read()
        .query(
            "MATCH (n:HPW) RETURN n.score",
            &std::collections::BTreeMap::new(),
        )
        .unwrap();
    assert_eq!(rs.len(), 1);
    assert_eq!(
        rs.get(0, "n.score"),
        Some(&Value::Int(99)),
        "score must be 99 after re-open"
    );
}

// ── RBAC: role-bound server token tests ────────────────────────────────────────

/// Build a DB with named roles and return (Router, SharedDb) with the role
/// token map wired up.
///
/// `roles` is a slice of (role_name, allowed_labels, allowed_keys).
/// `full_token` is the full-access bearer value (None = no full token).
/// `role_token_map` is a slice of (bearer_value, role_name).
fn open_rbac(
    name: &str,
    roles: &[(&str, &[&str], &[&str])],
    full_token: Option<&str>,
    role_token_map: &[(&str, &str)],
) -> (Router, SharedDb) {
    let db = SharedDb::open(&tmp(name)).unwrap();
    let schema = Schema {
        roles: roles
            .iter()
            .map(|(rname, labels, keys)| RoleDef {
                name: rname.to_string(),
                labels: labels.iter().map(|s| s.to_string()).collect(),
                keys: keys.iter().map(|s| s.to_string()).collect(),
            })
            .collect(),
        ..Default::default()
    };
    db.write().apply_schema(&schema).unwrap();
    let rtoks: std::collections::HashMap<String, String> = role_token_map
        .iter()
        .map(|(tok, role)| (tok.to_string(), role.to_string()))
        .collect();
    let app = router_with_role_tokens(db.clone(), full_token.map(str::to_string), rtoks);
    (app, db)
}

/// Authenticated JSON POST.
fn authed_json_req(method: &str, uri: &str, token: &str, body: Json) -> Request<Body> {
    Request::builder()
        .method(method)
        .uri(uri)
        .header(axum::http::header::AUTHORIZATION, format!("Bearer {token}"))
        .header(axum::http::header::CONTENT_TYPE, "application/json")
        .body(Body::from(body.to_string()))
        .unwrap()
}

/// Authenticated GET.
fn authed_get(uri: &str, token: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .header(axum::http::header::AUTHORIZATION, format!("Bearer {token}"))
        .body(Body::empty())
        .unwrap()
}

/// Authenticated GET that includes WebSocket upgrade headers so the handler
/// can reach the identity check before failing on missing WS framing.
fn authed_ws_upgrade(uri: &str, token: &str) -> Request<Body> {
    Request::builder()
        .method("GET")
        .uri(uri)
        .header(axum::http::header::AUTHORIZATION, format!("Bearer {token}"))
        .header("Connection", "Upgrade")
        .header("Upgrade", "websocket")
        .header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
        .header("Sec-WebSocket-Version", "13")
        .body(Body::empty())
        .unwrap()
}

// ── 1. Role token sees only its subgraph via /query ───────────────────────────

#[tokio::test]
async fn role_token_query_sees_only_role_subgraph() {
    // analyst role: sees "Pub" label; "Secret" label is hidden.
    let (app, db) = open_rbac(
        "rbac-q-subgraph",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("analyst-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Pub", "pub2", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    // Role token: only sees Pub nodes.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "analyst-tok",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let rows = v["rows"].as_array().unwrap();
    assert_eq!(rows.len(), 2, "role must see only 2 Pub nodes, got {v}");

    // Full token: sees all three.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "admin",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(
        v["rows"].as_array().unwrap().len(),
        3,
        "full token must see all 3 nodes"
    );
}

// ── 2. Role token sees subgraph via /node/{key} ───────────────────────────────

#[tokio::test]
async fn role_token_node_visible_key_is_200() {
    let (app, db) = open_rbac(
        "rbac-node-ok",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();

    let (status, _, _) = send(app, authed_get("/node/pub1", "role-tok")).await;
    assert_eq!(status, StatusCode::OK);
}

#[tokio::test]
async fn role_token_node_hidden_key_is_404() {
    let (app, db) = open_rbac(
        "rbac-node-hidden",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    let (status, body, _) = send(app, authed_get("/node/sec1", "role-tok")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    let v = parse_json(&body);
    assert!(
        v["error"].as_str().is_some_and(|s| s.contains("sec1")),
        "404 body must name the key"
    );
}

// ── 3. Hidden key same response shape as truly absent key ────────────────────

#[tokio::test]
async fn role_token_hidden_key_indistinguishable_from_absent() {
    let (app, db) = open_rbac(
        "rbac-hidden-absent",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    let (hidden_status, hidden_body, _) =
        send(app.clone(), authed_get("/node/sec1", "role-tok")).await;
    let (absent_status, absent_body, _) =
        send(app, authed_get("/node/totally-absent", "role-tok")).await;

    assert_eq!(hidden_status, StatusCode::NOT_FOUND);
    assert_eq!(absent_status, StatusCode::NOT_FOUND);
    // Both bodies have the same shape: {"error":"node key not found: ..."}
    let hidden_v = parse_json(&hidden_body);
    let absent_v = parse_json(&absent_body);
    assert!(
        hidden_v["error"].as_str().is_some(),
        "hidden: must have error field"
    );
    assert!(
        absent_v["error"].as_str().is_some(),
        "absent: must have error field"
    );
}

// ── 4. Full token is unaffected by role config ────────────────────────────────

#[tokio::test]
async fn full_token_unaffected_by_role_config() {
    let (app, db) = open_rbac(
        "rbac-full-unaffected",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    // Full token sees all nodes via /query.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "admin",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["rows"].as_array().unwrap().len(), 2);

    // Full token can write.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "admin",
        json!({"cypher": "CREATE (n:Pub {id: 'pub2'})"}),
    );
    let (status, _, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::OK, "full token write must succeed");

    // Full token can read /stats.
    let (status, _, _) = send(app, authed_get("/stats", "admin")).await;
    assert_eq!(status, StatusCode::OK);
}

// ── 5. Write via role token → 403 ────────────────────────────────────────────

#[tokio::test]
async fn role_token_write_query_is_403() {
    let (app, _db) = open_rbac(
        "rbac-write-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({"cypher": "CREATE (n:Pub {id: 'evil'})"}),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "write via role token must be 403: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert!(v["error"].as_str().is_some_and(|s| !s.is_empty()));
}

// ── 6. /ingest via role token → 403 ──────────────────────────────────────────

#[tokio::test]
async fn role_token_ingest_is_403() {
    let (app, _db) = open_rbac(
        "rbac-ingest-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req(
        "POST",
        "/ingest",
        "role-tok",
        json!({"label": "Pub", "rows": [{"id": "x"}]}),
    );
    let (status, _, _) = send(app, req).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── 7. /rules via role token → 403 ───────────────────────────────────────────

#[tokio::test]
async fn role_token_rules_is_403() {
    let (app, _db) = open_rbac(
        "rbac-rules-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req(
        "POST",
        "/rules",
        "role-tok",
        json!({
            "name": "r",
            "src_label": "Pub",
            "dst_label": "Pub",
            "predicate": {"KeyMatch": {"field": "fk"}},
            "edge_type": "REL"
        }),
    );
    let (status, _, _) = send(app, req).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── 8. /subscribe via role token → 403 ───────────────────────────────────────

#[tokio::test]
async fn role_token_subscribe_is_403() {
    let (app, _db) = open_rbac(
        "rbac-sub-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    // Send a proper WS upgrade request so the handler body is reached.
    let req = authed_ws_upgrade("/subscribe", "role-tok");
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "/subscribe with role token must be 403: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert!(v["error"].as_str().is_some_and(|s| !s.is_empty()));
}

// ── 9. /watch via role token → 403 ───────────────────────────────────────────

#[tokio::test]
async fn role_token_watch_is_403() {
    let (app, _db) = open_rbac(
        "rbac-watch-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_ws_upgrade("/watch", "role-tok");
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "/watch with role token must be 403: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert!(v["error"].as_str().is_some_and(|s| !s.is_empty()));
}

// ── 10. /stats via role token → 403 ──────────────────────────────────────────

#[tokio::test]
async fn role_token_stats_is_403() {
    let (app, _db) = open_rbac(
        "rbac-stats-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let (status, _, _) = send(app, authed_get("/stats", "role-tok")).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── 11. /algo/* via role token → 403 ─────────────────────────────────────────

#[tokio::test]
async fn role_token_algo_is_403() {
    let (app, _db) = open_rbac(
        "rbac-algo-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req("POST", "/algo/pagerank", "role-tok", json!({}));
    let (status, _, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::FORBIDDEN, "/algo/pagerank must be 403");

    let req = authed_json_req("POST", "/algo/wcc", "role-tok", json!({}));
    let (status, _, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::FORBIDDEN, "/algo/wcc must be 403");

    let req = authed_json_req("POST", "/algo/degree", "role-tok", json!({}));
    let (status, _, _) = send(app, req).await;
    assert_eq!(status, StatusCode::FORBIDDEN, "/algo/degree must be 403");
}

// ── 12. /explain via role token → 403 ────────────────────────────────────────

#[tokio::test]
async fn role_token_explain_is_403() {
    let (app, _db) = open_rbac(
        "rbac-explain-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let (status, _, _) = send(app, authed_get("/explain?a=x&b=y", "role-tok")).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── 13. /suggest via role token → 403 ────────────────────────────────────────

#[tokio::test]
async fn role_token_suggest_is_403() {
    let (app, _db) = open_rbac(
        "rbac-suggest-403",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let (status, _, _) = send(app, authed_get("/suggest", "role-tok")).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

// ── 14. Unknown bearer token (not in role_tokens and not full) → 401 ─────────

#[tokio::test]
async fn unknown_token_is_401() {
    let (app, _db) = open_rbac(
        "rbac-unknown-tok",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "not-a-real-token",
        json!({"cypher": "MATCH (n) RETURN n"}),
    );
    let (status, _, _) = send(app, req).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

// ── 15. Token bound to unknown role → 401 ────────────────────────────────────

#[tokio::test]
async fn token_bound_to_unknown_role_is_401() {
    // "ghost-role" is not defined in the DB schema.
    let db = SharedDb::open(&tmp("rbac-unknown-role")).unwrap();
    // Apply schema with NO roles at all (or a different role).
    let schema = Schema {
        roles: vec![],
        ..Default::default()
    };
    db.write().apply_schema(&schema).unwrap();

    let rtoks = [("role-tok".to_string(), "ghost-role".to_string())]
        .into_iter()
        .collect();
    let app = router_with_role_tokens(db.clone(), Some("admin".to_string()), rtoks);

    db.write().insert_node("Pub", "pub1", vec![]).unwrap();

    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::UNAUTHORIZED,
        "token bound to unknown role must be 401, body: {}",
        String::from_utf8_lossy(&body)
    );
}

// ── 16. Client mask ∩ role mask: never widens ─────────────────────────────────

#[tokio::test]
async fn role_token_client_mask_intersects_role_mask() {
    // analyst sees "Pub" label; alice, bob, carol are Pub; dave is Secret.
    let (app, db) = open_rbac(
        "rbac-mask-intersect",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "alice", vec![]).unwrap();
    db.write().insert_node("Pub", "bob", vec![]).unwrap();
    db.write().insert_node("Pub", "carol", vec![]).unwrap();
    db.write().insert_node("Secret", "dave", vec![]).unwrap();

    // Client supplies mask [alice, bob, dave]. Role mask = [alice, bob, carol].
    // Effective = intersection = [alice, bob] only. dave must not appear.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({
            "cypher": "MATCH (n:Pub) RETURN n.id",
            "mask": ["alice", "bob", "dave"]
        }),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let rows = v["rows"].as_array().unwrap();
    assert_eq!(rows.len(), 2, "only alice+bob must be visible, got {v}");

    // Client cannot widen by omitting mask: still role-masked.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let rows = v["rows"].as_array().unwrap();
    assert_eq!(
        rows.len(),
        3,
        "role sees 3 Pub nodes without client mask, got {v}"
    );
}

// ── 17. Poisoned roles.json → 500 for role tokens ────────────────────────────

#[tokio::test]
async fn poisoned_sidecar_is_500_for_role_token() {
    let dir = tmp("rbac-poisoned");
    std::fs::create_dir_all(&dir).unwrap();
    // Write a syntactically invalid roles.json before opening the DB.
    std::fs::write(dir.join("roles.json"), b"not valid json at all!").unwrap();

    // SharedDb::open succeeds but roles are poisoned (mask_for_role returns Err).
    let db = SharedDb::open(&dir).unwrap();

    let rtoks = [("role-tok".to_string(), "analyst".to_string())]
        .into_iter()
        .collect();
    // Full token is still functional.
    let app = router_with_role_tokens(db.clone(), Some("admin".to_string()), rtoks);

    // Role token → 500 (poisoned state).
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::INTERNAL_SERVER_ERROR,
        "poisoned sidecar must be 500 for role token: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert!(
        v["error"].as_str().is_some_and(|s| !s.is_empty()),
        "500 body must have error field"
    );

    // Full token is unaffected.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "admin",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, _, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "full token must be unaffected by poisoned sidecar"
    );
}

// ── 18. No role config: existing behavior byte-identical ─────────────────────

#[tokio::test]
async fn no_role_config_is_byte_identical() {
    // A router with no role tokens and no full token behaves exactly as before.
    let (app, db) = open("no-rbac-compat");
    db.write().insert_node("P", "x", vec![]).unwrap();
    let req = json_req(
        "POST",
        "/query?format=json",
        json!({"cypher": "MATCH (n) RETURN n.id"}),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["rows"].as_array().unwrap().len(), 1);
}

// ── 19. /node/{key}/edges hidden key → 404 ───────────────────────────────────

#[tokio::test]
async fn role_token_node_edges_hidden_key_is_404() {
    let (app, db) = open_rbac(
        "rbac-edges-hidden",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    let (status, _, _) = send(app, authed_get("/node/sec1/edges", "role-tok")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── 20. /node/{key}/neighborhood hidden key → 404 ────────────────────────────

#[tokio::test]
async fn role_token_neighborhood_hidden_key_is_404() {
    let (app, db) = open_rbac(
        "rbac-nbhd-hidden",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    let (status, _, _) = send(app, authed_get("/node/sec1/neighborhood", "role-tok")).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

// ── Fix round-1: C1 — /edges filters hidden neighbor endpoints ────────────────

#[tokio::test]
async fn role_token_edges_filters_hidden_neighbor() {
    // pub1 --KNOWS--> sec1 (hidden); pub1 --KNOWS--> pub2 (visible).
    // Role token on /node/pub1/edges must NOT see the edge to sec1.
    let (app, db) = open_rbac(
        "rbac-edges-filter",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    {
        let mut w = db.write();
        w.insert_node("Pub", "pub1", vec![]).unwrap();
        w.insert_node("Pub", "pub2", vec![]).unwrap();
        w.insert_node("Secret", "sec1", vec![]).unwrap();
        w.insert_edge("KNOWS", "pub1", "sec1").unwrap();
        w.insert_edge("KNOWS", "pub1", "pub2").unwrap();
    }

    let (status, body, _) = send(app.clone(), authed_get("/node/pub1/edges", "role-tok")).await;
    assert_eq!(status, StatusCode::OK, "visible entry key must be 200");
    let v = parse_json(&body);
    let edges = v["edges"].as_array().expect("edges array");
    // Only the pub1→pub2 edge should appear; the pub1→sec1 edge must be absent.
    assert_eq!(
        edges.len(),
        1,
        "role token must not see edge to hidden node"
    );
    let dst = edges[0]["dst_key"].as_str().unwrap_or("");
    assert_eq!(dst, "pub2", "only visible-neighbor edge returned");

    // Full token sees both edges.
    let (status, body, _) = send(app, authed_get("/node/pub1/edges", "admin")).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(
        v["edges"].as_array().unwrap().len(),
        2,
        "full token must see all edges"
    );
}

// ── Fix round-1: C2 — /neighborhood never leaks hidden nodes or routes through them

#[tokio::test]
async fn role_token_neighborhood_hides_hidden_nodes_and_does_not_route_through_them() {
    // Graph: pub1 --KNOWS--> sec1 (hidden) --KNOWS--> pub2 (visible, but only
    // reachable through a hidden intermediate).
    //
    // At depth 2 the unmasked BFS would yield both sec1 and pub2.
    // A role token must see neither (sec1 is hidden; pub2 is only reachable via sec1).
    let (app, db) = open_rbac(
        "rbac-nbhd-route",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    {
        let mut w = db.write();
        w.insert_node("Pub", "pub1", vec![]).unwrap();
        w.insert_node("Secret", "sec1", vec![]).unwrap();
        w.insert_node("Pub", "pub2", vec![]).unwrap();
        w.insert_edge("KNOWS", "pub1", "sec1").unwrap();
        w.insert_edge("KNOWS", "sec1", "pub2").unwrap();
    }

    let (status, body, _) = send(
        app.clone(),
        authed_get("/node/pub1/neighborhood?depth=2", "role-tok"),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "visible entry key must be 200");
    let v = parse_json(&body);
    let rows = v["rows"].as_array().expect("rows array");
    // Neither sec1 nor pub2 should appear.
    let keys: Vec<&str> = rows
        .iter()
        .filter_map(|r| r.as_array()?.first()?.as_str())
        .collect();
    assert!(
        !keys.contains(&"sec1"),
        "hidden node sec1 must not appear in neighborhood"
    );
    assert!(
        !keys.contains(&"pub2"),
        "pub2 reachable only via hidden intermediate must not appear"
    );

    // Full token at depth 2 sees both sec1 and pub2.
    let (status, body, _) = send(app, authed_get("/node/pub1/neighborhood?depth=2", "admin")).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let full_rows = v["rows"].as_array().unwrap();
    let full_keys: Vec<&str> = full_rows
        .iter()
        .filter_map(|r| r.as_array()?.first()?.as_str())
        .collect();
    assert!(
        full_keys.contains(&"sec1"),
        "full token must see sec1 in neighborhood"
    );
    assert!(
        full_keys.contains(&"pub2"),
        "full token must see pub2 in neighborhood"
    );
}

// ── Fix round-1: I1 — serve_with_embedded_ui wires role tokens (unit check) ──

/// Validates that `router_with_role_tokens` (used by the embed-ui serve path)
/// enforces role tokens when invoked with a role map.  The embed-ui feature gate
/// guards `serve_with_embedded_ui` itself; this test covers the router logic that
/// `serve_with_embedded_ui` delegates to.
#[tokio::test]
async fn embed_ui_router_path_honors_role_tokens() {
    // open_rbac uses router_with_role_tokens — the same path serve_with_embedded_ui
    // now delegates to — so this exercises the fixed code path.
    let (app, db) = open_rbac(
        "rbac-embed-ui-wire",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    // Role token: visible node is 200; hidden node is 404.
    let (st, _, _) = send(app.clone(), authed_get("/node/pub1", "role-tok")).await;
    assert_eq!(st, StatusCode::OK, "role token must see pub1");
    let (st, _, _) = send(app.clone(), authed_get("/node/sec1", "role-tok")).await;
    assert_eq!(st, StatusCode::NOT_FOUND, "role token must not see sec1");

    // Unknown token is 401 even on this path.
    let (st, _, _) = send(app, authed_get("/node/pub1", "bad-tok")).await;
    assert_eq!(st, StatusCode::UNAUTHORIZED, "unknown token must be 401");
}

// ── Fix round-1: M1 — indistinguishability extends to /edges and /neighborhood ─

#[tokio::test]
async fn role_token_hidden_key_indistinguishable_from_absent_on_edges_and_neighborhood() {
    let (app, db) = open_rbac(
        "rbac-indist-ext",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    // /edges: hidden and absent both return 404 with an error field.
    let (hidden_st, hidden_body, _) =
        send(app.clone(), authed_get("/node/sec1/edges", "role-tok")).await;
    let (absent_st, absent_body, _) = send(
        app.clone(),
        authed_get("/node/totally-absent/edges", "role-tok"),
    )
    .await;
    assert_eq!(hidden_st, StatusCode::NOT_FOUND);
    assert_eq!(absent_st, StatusCode::NOT_FOUND);
    let hv = parse_json(&hidden_body);
    let av = parse_json(&absent_body);
    // Both must have an "error" field with the same prefix pattern.
    let h_err = hv["error"].as_str().unwrap_or("");
    let a_err = av["error"].as_str().unwrap_or("");
    assert!(
        h_err.starts_with("node key not found"),
        "hidden /edges error must match absent prefix: {h_err}"
    );
    assert!(
        a_err.starts_with("node key not found"),
        "absent /edges error must match pattern: {a_err}"
    );

    // /neighborhood: same.
    let (hidden_st, hidden_body, _) = send(
        app.clone(),
        authed_get("/node/sec1/neighborhood", "role-tok"),
    )
    .await;
    let (absent_st, absent_body, _) = send(
        app,
        authed_get("/node/totally-absent/neighborhood", "role-tok"),
    )
    .await;
    assert_eq!(hidden_st, StatusCode::NOT_FOUND);
    assert_eq!(absent_st, StatusCode::NOT_FOUND);
    let hv = parse_json(&hidden_body);
    let av = parse_json(&absent_body);
    let h_err = hv["error"].as_str().unwrap_or("");
    let a_err = av["error"].as_str().unwrap_or("");
    assert!(
        h_err.starts_with("node key not found"),
        "hidden /neighborhood error must match absent prefix: {h_err}"
    );
    assert!(
        a_err.starts_with("node key not found"),
        "absent /neighborhood error must match pattern: {a_err}"
    );
}

// ── Fix round-1: M2 — poisoned sidecar on /node, /edges, /neighborhood → 500 ──

#[tokio::test]
async fn poisoned_sidecar_is_500_on_node_edges_and_neighborhood() {
    let dir = tmp("rbac-poisoned-ext");
    {
        let db = SharedDb::open(&dir).unwrap();
        db.write().insert_node("Pub", "pub1", vec![]).unwrap();
        db.write().insert_node("Pub", "pub2", vec![]).unwrap();
        db.write().insert_edge("KNOWS", "pub1", "pub2").unwrap();
    }
    // Poison the sidecar after nodes are inserted.
    std::fs::write(dir.join("roles.json"), b"not valid json").unwrap();
    let db = SharedDb::open(&dir).unwrap();
    let rtoks: std::collections::HashMap<String, String> =
        [("role-tok".to_string(), "analyst".to_string())]
            .into_iter()
            .collect();
    let app = router_with_role_tokens(db, Some("admin".to_string()), rtoks);

    for path in ["/node/pub1", "/node/pub1/edges", "/node/pub1/neighborhood"] {
        let (status, body, _) = send(app.clone(), authed_get(path, "role-tok")).await;
        assert_eq!(
            status,
            StatusCode::INTERNAL_SERVER_ERROR,
            "poisoned sidecar must be 500 for role token on {path}: {}",
            String::from_utf8_lossy(&body)
        );
        let v = parse_json(&body);
        assert!(
            v["error"].as_str().is_some_and(|s| !s.is_empty()),
            "500 body must have error field on {path}"
        );
    }

    // Full token is unaffected.
    let (status, _, _) = send(app, authed_get("/node/pub1", "admin")).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "full token must be unaffected by poisoned sidecar"
    );
}

// ── Existing non-RBAC test below (unchanged) ─────────────────────────────────

#[tokio::test]
async fn query_mask_filters_nodes() {
    let (app, db) = open("mask-http");
    db.write().insert_node("P", "alice", vec![]).unwrap();
    db.write().insert_node("P", "bob", vec![]).unwrap();
    db.write().insert_node("P", "carol", vec![]).unwrap();

    // With mask: only alice+bob visible.
    let req = json_req(
        "POST",
        "/query?format=json",
        json!({"cypher": "MATCH (n:P) RETURN n.id", "mask": ["alice", "bob"]}),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["rows"].as_array().unwrap().len(), 2);

    // Write through mask → 400.
    let req = json_req(
        "POST",
        "/query?format=json",
        json!({"cypher": "CREATE (n:P {id: 'evil'})", "mask": ["alice"]}),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "masked write must be 400: {}",
        String::from_utf8_lossy(&body)
    );

    // Without mask: all three visible.
    let req = json_req(
        "POST",
        "/query?format=json",
        json!({"cypher": "MATCH (n:P) RETURN n.id"}),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    assert_eq!(v["rows"].as_array().unwrap().len(), 3);
}

/// POST /query with a client mask and a write Cypher must return exactly
/// 400 Bad Request with body `{"error":"masked queries are read-only"}`.
/// Pins the MaskedReadOnly → HTTP mapping so the arm cannot be silently removed.
#[tokio::test]
async fn masked_write_returns_400_with_exact_body() {
    let (app, db) = open("masked-write-pin");
    db.write().insert_node("P", "alice", vec![]).unwrap();

    let req = json_req(
        "POST",
        "/query?format=json",
        json!({"cypher": "CREATE (n:P {id: 'evil'})", "mask": ["alice"]}),
    );
    let (status, body, _) = send(app, req).await;

    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "masked write must be 400; body: {}",
        String::from_utf8_lossy(&body)
    );
    let v: serde_json::Value = serde_json::from_slice(&body).expect("body must be valid JSON");
    assert_eq!(
        v,
        json!({"error": "masked queries are read-only"}),
        "response body must be exactly {{\"error\":\"masked queries are read-only\"}}"
    );
}

// ── History endpoints ─────────────────────────────────────────────────────────

/// Build a DB with two Person nodes and a manual LINK edge for history tests.
fn open_history_db(name: &str) -> (Router, SharedDb) {
    let db = SharedDb::open(&tmp(name)).unwrap();
    db.write()
        .insert_node("Person", "alice", vec![("age".into(), Value::Int(30))])
        .unwrap();
    db.write().insert_node("Person", "bob", vec![]).unwrap();
    db.write().insert_edge("LINK", "alice", "bob").unwrap();
    (router(db.clone()), db)
}

// ── Full-token happy paths ────────────────────────────────────────────────────

#[tokio::test]
async fn node_history_full_token_happy_path() {
    let (app, _db) = open_history_db("hist-nh-full");
    let (status, body, _) = send(app, get("/node/alice/history")).await;
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
    let v = parse_json(&body);

    assert_eq!(v["key"], "alice");
    let total = v["total_commits"].as_u64().expect("total_commits present");
    assert!(total > 0, "total_commits must be > 0");

    let history = v["history"].as_array().expect("history array");
    assert!(
        !history.is_empty(),
        "alice must have at least one history event"
    );

    // First event is NodeInserted.
    assert_eq!(history[0]["change"]["type"], "NodeInserted");
    assert_eq!(history[0]["change"]["label"], "Person");
}

#[tokio::test]
async fn edge_history_full_token_happy_path() {
    let (app, _db) = open_history_db("hist-eh-full");
    let (status, body, _) = send(app, get("/history/edge?a=alice&b=bob")).await;
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
    let v = parse_json(&body);

    assert_eq!(v["a"], "alice");
    assert_eq!(v["b"], "bob");
    let total = v["total_commits"].as_u64().expect("total_commits present");
    assert!(total > 0, "total_commits must be > 0");

    let events = v["events"].as_array().expect("events array");
    assert!(
        !events.is_empty(),
        "alice-bob must have at least one edge event"
    );

    // The LINK edge must appear as Added.
    let has_link = events
        .iter()
        .any(|ev| ev["edge_type"] == "LINK" && ev["event"] == "Added");
    assert!(has_link, "expected LINK Added event: {events:?}");
}

#[tokio::test]
async fn was_linked_full_token_happy_path() {
    let (app, db) = open_history_db("hist-wl-full");
    let total = db.read().wal_total_commits().unwrap();
    let (status, body, _) = send(
        app,
        get(&format!(
            "/history/was_linked?a=alice&b=bob&edge_type=LINK&at_commit={}",
            total - 1
        )),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
    let v = parse_json(&body);
    assert_eq!(v["linked"], true);
    assert_eq!(v["a"], "alice");
    assert_eq!(v["edge_type"], "LINK");
}

#[tokio::test]
async fn was_linked_out_of_horizon_is_400_not_500() {
    let (app, _db) = open_history_db("hist-wl-oob");
    let (status, body, _) = send(
        app,
        get("/history/was_linked?a=alice&b=bob&edge_type=LINK&at_commit=99999"),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "out-of-horizon must be 400: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert!(
        v["error"]
            .as_str()
            .is_some_and(|s| s.contains("range") || s.contains("out of")),
        "error must mention range: {v}"
    );
}

// ── Role-token cases ──────────────────────────────────────────────────────────

#[tokio::test]
async fn role_token_node_history_visible_key_is_200() {
    let (app, db) = open_rbac(
        "hist-nh-role-ok",
        &[("analyst", &["Person"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Person", "alice", vec![]).unwrap();

    let (status, body, _) = send(app, authed_get("/node/alice/history", "role-tok")).await;
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
    let v = parse_json(&body);
    assert_eq!(v["key"], "alice");
    assert!(
        v["total_commits"].as_u64().is_some(),
        "horizon field must be present"
    );
}

#[tokio::test]
async fn role_token_node_history_hidden_key_is_404() {
    let (app, db) = open_rbac(
        "hist-nh-role-hidden",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    let (status, body, _) = send(app, authed_get("/node/sec1/history", "role-tok")).await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "hidden key must be 404: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(
        v,
        json!({"error": "node key not found: sec1"}),
        "body must match key_not_found shape"
    );
}

#[tokio::test]
async fn role_token_edge_history_both_visible_is_200() {
    let (app, db) = open_rbac(
        "hist-eh-role-ok",
        &[("analyst", &["Person"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Person", "alice", vec![]).unwrap();
    db.write().insert_node("Person", "bob", vec![]).unwrap();
    db.write().insert_edge("KNOWS", "alice", "bob").unwrap();

    let (status, body, _) = send(app, authed_get("/history/edge?a=alice&b=bob", "role-tok")).await;
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
    let v = parse_json(&body);
    assert!(
        v["total_commits"].as_u64().is_some(),
        "horizon field must be present"
    );
}

#[tokio::test]
async fn role_token_edge_history_one_hidden_is_404() {
    let (app, db) = open_rbac(
        "hist-eh-role-hidden",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();
    db.write().insert_edge("LINK", "pub1", "sec1").unwrap();

    // sec1 is hidden for the role token; should get 404 (same-as-absent).
    let (status, body, _) = send(app, authed_get("/history/edge?a=pub1&b=sec1", "role-tok")).await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "hidden endpoint must give 404: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(
        v,
        json!({"error": "node key not found: sec1"}),
        "body must match key_not_found shape"
    );
}

#[tokio::test]
async fn role_token_history_write_denied() {
    // Confirm that a role token is rejected (403 FORBIDDEN) on write endpoints.
    // POST /ingest is a real write endpoint guarded by RBAC — this tests the
    // auth middleware, not Axum routing behaviour.
    let (app, _db) = open_rbac(
        "hist-role-write-denied",
        &[("analyst", &["Person"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req(
        "POST",
        "/ingest",
        "role-tok",
        json!({"label": "Person", "rows": [{"id": "x"}]}),
    );
    let (status, _, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "role token must be 403 on POST /ingest"
    );
}

// ── Fix round-2: C1 — node_history Role branch must filter hidden edge neighbors

/// C1 leak-repro: a VISIBLE node's history must NOT reveal hidden neighbor keys
/// in EdgeAdded/EdgeRemoved entries when accessed by a role token.
///
/// Setup: visible Person/alice + hidden Secret/shadow + LINK edge alice→shadow.
/// Role token (can see Person, not Secret): GET /node/alice/history must return
/// history with no mention of "shadow" in any entry.
/// Full token: the same request MUST include the EdgeAdded entry naming "shadow".
#[tokio::test]
async fn role_token_node_history_filters_hidden_edge_neighbor() {
    let (app, db) = open_rbac(
        "hist-nh-c1-leak",
        &[("analyst", &["Person"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    {
        let mut w = db.write();
        w.insert_node("Person", "alice", vec![]).unwrap();
        w.insert_node("Secret", "shadow", vec![]).unwrap();
        w.insert_edge("LINK", "alice", "shadow").unwrap();
    }

    // Role token: alice is visible, shadow is not — the EdgeAdded entry for the
    // LINK edge names "shadow" and must be stripped.
    let (status, body, _) = send(app.clone(), authed_get("/node/alice/history", "role-tok")).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "visible node must be 200 for role token: {}",
        String::from_utf8_lossy(&body)
    );
    let body_str = String::from_utf8_lossy(&body);
    assert!(
        !body_str.contains("shadow"),
        "role token response must NOT contain hidden key 'shadow': {body_str}"
    );

    // Full token: same node, same edge — the EdgeAdded entry naming "shadow"
    // must be present (unfiltered).
    let (status, body, _) = send(app, authed_get("/node/alice/history", "admin")).await;
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
    let body_str = String::from_utf8_lossy(&body);
    assert!(
        body_str.contains("shadow"),
        "full token response MUST contain edge neighbor key 'shadow': {body_str}"
    );
}

/// I2: GET /node/{key}/history for an absent key must return 404 (same as GET
/// /node/{key}) for BOTH Full and Role identities.
#[tokio::test]
async fn node_history_absent_key_is_404_both_identities() {
    let (app, _db) = open_rbac(
        "hist-nh-absent-404",
        &[("analyst", &["Person"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    // Full token: absent key → 404.
    let (status, body, _) = send(app.clone(), authed_get("/node/ghost/history", "admin")).await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "full token: absent key must be 404: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(v, json!({"error": "node key not found: ghost"}));

    // Role token: absent key → 404 (indistinguishable from hidden).
    let (status, body, _) = send(app, authed_get("/node/ghost/history", "role-tok")).await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "role token: absent key must be 404: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(v, json!({"error": "node key not found: ghost"}));
}

// ── Restricted-stub mask mode (Task 1: KB-hardening) ─────────────────────────

/// POST /query with a client mask and `stub_hidden: true` must be accepted
/// and return the same Cypher results as without the flag — hidden nodes are
/// excluded from query results in both modes (Cypher behaviour is mode-agnostic).
#[tokio::test]
async fn client_mask_stub_hidden_query_round_trip() {
    let (app, db) = open("stub-query-rt");
    {
        let mut g = db.write();
        g.insert_node("P", "alice", vec![]).unwrap();
        g.insert_node("P", "bob", vec![]).unwrap();
        g.insert_node("P", "carol", vec![]).unwrap();
        g.insert_edge("KNOWS", "alice", "bob").unwrap();
        g.insert_edge("KNOWS", "alice", "carol").unwrap();
    }

    // With mask=["alice","carol"] and stub_hidden=true, Cypher still sees only
    // the masked subgraph.  alice→carol is the only visible KNOWS edge.
    let req = json_req(
        "POST",
        "/query?format=json",
        json!({
            "cypher": "MATCH (a:P)-[r:KNOWS]->(b:P) RETURN b.id",
            "mask": ["alice", "carol"],
            "stub_hidden": true
        }),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "stub_hidden request must be 200: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    let rows = v["rows"].as_array().unwrap();
    assert_eq!(rows.len(), 1, "only alice→carol must be visible: {v}");

    // Same result without stub_hidden (Omit is default).
    let req2 = json_req(
        "POST",
        "/query?format=json",
        json!({
            "cypher": "MATCH (a:P)-[r:KNOWS]->(b:P) RETURN b.id",
            "mask": ["alice", "carol"],
        }),
    );
    let (status2, body2, _) = send(app, req2).await;
    assert_eq!(status2, StatusCode::OK);
    let v2 = parse_json(&body2);
    assert_eq!(
        v2["rows"].as_array().unwrap().len(),
        1,
        "Omit mode must return same row count"
    );
}

/// GET /node/{key}?mask=alice,carol&stub_hidden=true on a hidden key must
/// return `{"key": "<key>", "restricted": true}` — not 404.
/// Full body must contain ONLY `key` and `restricted` (no label, no props).
#[tokio::test]
async fn client_mask_stub_node_info_hidden_key_returns_restricted_stub() {
    let (app, db) = open("stub-node-info-http");
    {
        let mut g = db.write();
        g.insert_node("P", "alice", vec![("score".into(), Value::Int(99))])
            .unwrap();
        g.insert_node("P", "bob", vec![]).unwrap();
    }

    // GET /node/bob?mask=alice&stub_hidden=true — bob is hidden from the mask.
    let req = get("/node/bob?mask=alice&stub_hidden=true");
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "hidden key in stub mode must be 200: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    // Assert FULL body shape: only key and restricted, nothing else.
    let obj = v.as_object().expect("response must be a JSON object");
    assert_eq!(
        obj.len(),
        2,
        "stub JSON must contain exactly 2 fields (key, restricted): {v}"
    );
    assert_eq!(v["key"], json!("bob"), "stub key must be the requested key");
    assert_eq!(v["restricted"], json!(true), "restricted must be true");
    assert!(v.get("label").is_none(), "stub must not leak label");
    assert!(v.get("props").is_none(), "stub must not leak props");

    // GET /node/alice?mask=alice — visible key returns normal info.
    let req2 = get("/node/alice?mask=alice&stub_hidden=true");
    let (status2, body2, _) = send(app.clone(), req2).await;
    assert_eq!(status2, StatusCode::OK);
    let v2 = parse_json(&body2);
    assert_eq!(v2["key"], json!("alice"));
    assert!(v2.get("label").is_some(), "visible node must have label");

    // GET /node/ghost?mask=alice&stub_hidden=true — absent key must be 404.
    let req3 = get("/node/ghost?mask=alice&stub_hidden=true");
    let (status3, _, _) = send(app, req3).await;
    assert_eq!(
        status3,
        StatusCode::NOT_FOUND,
        "absent key must still be 404 even in stub mode"
    );
}

/// GET /node/{key}/edges?mask=alice,carol&stub_hidden=true must include edges
/// to hidden neighbors rendered as `{"key": "<key>", "restricted": true}`.
#[tokio::test]
async fn client_mask_stub_node_edges_includes_restricted_endpoint() {
    let (app, db) = open("stub-node-edges-http");
    {
        let mut g = db.write();
        g.insert_node("P", "alice", vec![]).unwrap();
        g.insert_node("P", "bob", vec![]).unwrap(); // will be hidden
        g.insert_node("P", "carol", vec![]).unwrap();
        g.insert_edge("KNOWS", "alice", "bob").unwrap();
        g.insert_edge("KNOWS", "alice", "carol").unwrap();
    }

    // mask=alice,carol → bob is hidden; stub_hidden=true → bob appears as stub endpoint.
    let req = get("/node/alice/edges?mask=alice,carol&stub_hidden=true");
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "node edges stub request must be 200: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    let edges = v["edges"]
        .as_array()
        .expect("response must have edges array");
    assert_eq!(edges.len(), 2, "both edges must appear in stub mode: {v}");

    // Find the edge where bob appears as dst_key restricted stub.
    let bob_edge = edges.iter().find(|e| {
        e["dst_key"].is_object()
            && e["dst_key"]["key"] == json!("bob")
            && e["dst_key"]["restricted"] == json!(true)
    });
    assert!(
        bob_edge.is_some(),
        "bob must appear as restricted stub dst_key: {v}"
    );

    // Carol edge must have dst_key as plain string.
    let carol_edge = edges.iter().find(|e| e["dst_key"] == json!("carol"));
    assert!(
        carol_edge.is_some(),
        "carol must appear as plain string: {v}"
    );
}

/// A role-token request with `stub_hidden: true` in the body must NOT produce
/// stubs — the role path is hard-coded to Omit mode and the flag is ignored.
///
/// The test inserts a visible (Pub) and a hidden (Secret) node, issues the
/// query from a role token that only sees Pub nodes, and verifies that Secret
/// never appears in any form (no key, no restricted field).
#[tokio::test]
async fn role_token_stub_hidden_flag_is_ignored() {
    let (app, db) = open_rbac(
        "stub-role-ignored",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    // Role token with stub_hidden: true.  sec1 must NOT appear.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({
            "cypher": "MATCH (n) RETURN n.id",
            "stub_hidden": true,
        }),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "role token stub_hidden request must be 200"
    );
    let v = parse_json(&body);
    let body_str = v.to_string();
    assert!(
        !body_str.contains("sec1"),
        "sec1 must not appear in any form in role-token response: {v}"
    );
    assert!(
        !body_str.contains("restricted"),
        "restricted field must not appear in role-token response: {v}"
    );

    // Verify pub1 is present.
    let rows = v["rows"].as_array().unwrap();
    assert_eq!(
        rows.len(),
        1,
        "role token must see exactly 1 node (pub1): {v}"
    );
}

/// `stub_hidden: true` on the role-token path also must not produce stubs
/// when a client-supplied mask is present (role mask + client mask intersection
/// stays Omit).
#[tokio::test]
async fn role_token_with_client_mask_and_stub_hidden_gets_no_stubs() {
    let (app, db) = open_rbac(
        "stub-role-client-mask",
        &[("analyst", &["Pub"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    db.write().insert_node("Pub", "pub1", vec![]).unwrap();
    db.write().insert_node("Pub", "pub2", vec![]).unwrap();
    db.write().insert_node("Secret", "sec1", vec![]).unwrap();

    // Role token with a client mask that includes pub1 only + stub_hidden: true.
    // sec1 is outside both the role mask and the client mask — no stub must appear.
    let req = authed_json_req(
        "POST",
        "/query?format=json",
        "role-tok",
        json!({
            "cypher": "MATCH (n) RETURN n.id",
            "mask": ["pub1", "sec1"],
            "stub_hidden": true,
        }),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK);
    let v = parse_json(&body);
    let body_str = v.to_string();
    assert!(
        !body_str.contains("sec1"),
        "sec1 must not appear even with stub_hidden on role path: {v}"
    );
    assert!(
        !body_str.contains("restricted"),
        "restricted field must not appear on role path: {v}"
    );
}

/// Full-token GET /neighborhood/{key}?mask=...&stub_hidden=true must return
/// hidden direct neighbours as stub rows (key present, label null).
/// The same request without stub_hidden must omit the hidden neighbours entirely.
///
/// Graph: alice -KNOWS-> bob (hidden from mask) -KNOWS-> carol (visible)
/// Mask: {alice, carol}
///
/// stub_hidden=true  → alice's neighborhood at depth=1 includes bob as stub row
/// stub_hidden absent → alice's neighborhood at depth=1 is empty (bob hidden)
///
/// In both cases carol must NOT appear (BFS doesn't expand through hidden bob).
#[tokio::test]
async fn client_mask_stub_neighborhood_shows_hidden_direct_neighbor() {
    let (app, db) = open("stub-nb-http");
    {
        let mut g = db.write();
        g.insert_node("P", "alice", vec![]).unwrap();
        g.insert_node("P", "bob", vec![]).unwrap(); // hidden from mask
        g.insert_node("P", "carol", vec![]).unwrap();
        g.insert_edge("KNOWS", "alice", "bob").unwrap();
        g.insert_edge("KNOWS", "bob", "carol").unwrap();
    }

    // Stub mode: bob appears as a stub row (label absent/null); carol does not.
    let req = get("/node/alice/neighborhood?mask=alice,carol&stub_hidden=true&depth=2&dir=out");
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "stub neighborhood must be 200: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    let rows = v["rows"].as_array().expect("must have rows");

    let bob_stub_row = rows.iter().find(|r| {
        let row = r.as_array().unwrap();
        row.first() == Some(&json!("bob")) && row.get(1) == Some(&json!(null))
    });
    assert!(
        bob_stub_row.is_some(),
        "stub mode: bob must appear as stub row (key=bob, label=null): {v}"
    );

    let carol_row = rows.iter().find(|r| {
        r.as_array()
            .and_then(|row| row.first())
            .map(|k| k == &json!("carol"))
            .unwrap_or(false)
    });
    assert!(
        carol_row.is_none(),
        "carol must NOT appear — BFS must not expand through hidden bob: {v}"
    );

    // Omit mode (no stub_hidden): bob is invisible, neighborhood is empty.
    let req2 = get("/node/alice/neighborhood?mask=alice,carol&depth=2&dir=out");
    let (status2, body2, _) = send(app, req2).await;
    assert_eq!(status2, StatusCode::OK);
    let v2 = parse_json(&body2);
    let rows2 = v2["rows"].as_array().expect("must have rows");
    assert_eq!(
        rows2.len(),
        0,
        "omit mode: neighborhood must be empty when hidden node blocks all paths: {v2}"
    );
}

// ── HTTP: POST /nodes/{key}/rename ────────────────────────────────────────────

#[tokio::test]
async fn http_rename_node_success() {
    let (app, db) = open("http-rename-ok");
    seed_person(&db, "alice");

    let req = json_req("POST", "/nodes/alice/rename", json!({"new_key": "alice2"}));
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "rename must return 200: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(v["ok"], json!(true));

    // Old key must be gone; new key must exist.
    let (s2, _b2, _) = send(app.clone(), get("/node/alice")).await;
    assert_eq!(s2, StatusCode::NOT_FOUND, "alice must be gone after rename");

    let (s3, b3, _) = send(app, get("/node/alice2")).await;
    assert_eq!(
        s3,
        StatusCode::OK,
        "alice2 must exist after rename: {}",
        String::from_utf8_lossy(&b3)
    );
}

#[tokio::test]
async fn http_rename_node_404_when_not_found() {
    let (app, _db) = open("http-rename-404");

    let req = json_req("POST", "/nodes/ghost/rename", json!({"new_key": "ghost2"}));
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::NOT_FOUND,
        "rename of non-existent key must be 404: {}",
        String::from_utf8_lossy(&body)
    );
}

#[tokio::test]
async fn http_rename_node_409_when_target_exists() {
    let (app, db) = open("http-rename-409");
    seed_person(&db, "alice");
    seed_person(&db, "alice2");

    let req = json_req("POST", "/nodes/alice/rename", json!({"new_key": "alice2"}));
    let (status, body, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::CONFLICT,
        "rename to existing key must be 409: {}",
        String::from_utf8_lossy(&body)
    );
}

// ── HTTP: POST /edges/upsert ──────────────────────────────────────────────────

#[tokio::test]
async fn http_upsert_edge_creates_missing_endpoints_and_edge() {
    let (app, _db) = open("http-upsert-ok");

    let req = json_req(
        "POST",
        "/edges/upsert",
        json!({
            "edge_type": "KNOWS",
            "src_key": "p1",
            "dst_key": "p2",
            "placeholder_label": "Person"
        }),
    );
    let (status, body, _) = send(app.clone(), req).await;
    assert_eq!(
        status,
        StatusCode::OK,
        "upsert must succeed: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(
        v["nodes_created"],
        json!(2),
        "both endpoints must be created"
    );
    assert_eq!(v["edge_inserted"], json!(true));

    // Both nodes must now exist.
    let (s1, _, _) = send(app.clone(), get("/node/p1")).await;
    assert_eq!(s1, StatusCode::OK, "p1 must exist");
    let (s2, _, _) = send(app, get("/node/p2")).await;
    assert_eq!(s2, StatusCode::OK, "p2 must exist");
}

#[tokio::test]
async fn http_upsert_edge_idempotent_when_edge_exists() {
    let (app, db) = open("http-upsert-idem");
    {
        let mut w = db.write();
        w.insert_node("Person", "a", vec![]).unwrap();
        w.insert_node("Person", "b", vec![]).unwrap();
        w.insert_edge("KNOWS", "a", "b").unwrap();
    }

    let req = json_req(
        "POST",
        "/edges/upsert",
        json!({
            "edge_type": "KNOWS",
            "src_key": "a",
            "dst_key": "b",
            "placeholder_label": "Person"
        }),
    );
    let (status, body, _) = send(app, req).await;
    assert_eq!(status, StatusCode::OK, "idempotent upsert must be 200");
    let v = parse_json(&body);
    assert_eq!(v["nodes_created"], json!(0), "no new nodes when both exist");
    assert_eq!(
        v["edge_inserted"],
        json!(false),
        "edge already existed — edge_inserted must be false"
    );
}

// ── POST /backup ──────────────────────────────────────────────────────────────

/// C1b: POST /backup with a full-access token and a concurrent writer thread
/// must produce a clean, openable backup whose node set matches the source.
#[tokio::test]
async fn http_backup_live_serve_dest_opens_clean() {
    use std::sync::{Arc, Barrier};

    let src_dir = tmp("http-backup-src");
    let dst_dir = tmp("http-backup-dst");

    let db = SharedDb::open(&src_dir).unwrap();
    // Seed initial data.
    {
        let mut w = db.write();
        w.insert_node("Person", "alice", vec![]).unwrap();
        w.insert_node("Person", "bob", vec![]).unwrap();
    }

    let app = router_with_auth(db.clone(), Some("admin".into()));

    // Spawn a concurrent writer thread that races with the backup.
    let barrier = Arc::new(Barrier::new(2));
    let db_writer = db.clone();
    let barrier_clone = barrier.clone();
    let writer = std::thread::spawn(move || {
        barrier_clone.wait(); // release once main thread is about to send backup
        for i in 0..20u32 {
            let key = format!("concurrent-{i}");
            let _ = db_writer.write().insert_node("Person", &key, vec![]);
        }
    });

    barrier.wait(); // let writer start racing

    let req = authed_json_req(
        "POST",
        "/backup",
        "admin",
        json!({"dest": dst_dir.to_str().unwrap()}),
    );
    let (status, body, _) = send(app, req).await;
    writer.join().unwrap();

    assert_eq!(
        status,
        StatusCode::OK,
        "POST /backup must be 200: {}",
        String::from_utf8_lossy(&body)
    );
    let v = parse_json(&body);
    assert_eq!(v["verified"], json!(true), "backup must be verified");
    assert!(
        v["bytes"].as_u64().unwrap_or(0) > 0,
        "backup bytes must be > 0"
    );

    // The destination must open cleanly and contain at least the seeded nodes.
    let backup_db = SharedDb::open(&dst_dir).expect("backup dest must open");
    assert!(
        backup_db.read().has_node("alice"),
        "alice must be in backup"
    );
    assert!(backup_db.read().has_node("bob"), "bob must be in backup");

    let _ = std::fs::remove_dir_all(&src_dir);
    let _ = std::fs::remove_dir_all(&dst_dir);
}

/// C1b: POST /backup with a role-bound token must return 403.
#[tokio::test]
async fn http_backup_role_token_is_forbidden() {
    let (app, _db) = open_rbac(
        "http-backup-role-403",
        &[("analyst", &["Person"], &[])],
        Some("admin"),
        &[("role-tok", "analyst")],
    );
    let req = authed_json_req(
        "POST",
        "/backup",
        "role-tok",
        json!({"dest": "/tmp/should-not-exist"}),
    );
    let (status, _, _) = send(app, req).await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "role token must be 403 on POST /backup"
    );
}