khive-pack-memory 0.5.0

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

fn make_runtime() -> KhiveRuntime {
    KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime")
}

fn make_registry(rt: KhiveRuntime) -> khive_runtime::VerbRegistry {
    let mut builder = VerbRegistryBuilder::new();
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt));
    builder.build().expect("registry builds")
}

/// Issue #396 regression: `memory.remember` dispatched through the real KG+memory
/// verb registry must succeed when the runtime is built with
/// `RuntimeConfig::no_embeddings()` — zero embedders registered, no lattice model
/// load attempted. Mirrors `khive-runtime`'s unit-level regression
/// (`no_embeddings_config_registers_zero_embedders` /
/// `no_embeddings_runtime_create_note_succeeds_without_model_fanout`) but drives
/// the actual `MemoryPack::handle_remember` handler through pack registration and
/// verb dispatch, not `create_note` directly.
#[tokio::test]
async fn test_remember_dispatch_succeeds_with_no_embeddings_runtime() {
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        packs: vec!["kg".to_string()],
        ..RuntimeConfig::no_embeddings()
    })
    .expect("no_embeddings runtime");

    assert!(
        rt.registered_embedding_model_names().is_empty(),
        "no_embeddings() runtime must register zero embedders"
    );

    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "issue-396 regression: memory.remember via real dispatch with zero embedders",
                "memory_type": "semantic",
                "salience": 0.7
            }),
        )
        .await
        .expect("memory.remember must succeed with zero registered embedders");

    let note_id = result["id"].as_str().expect("has note_id");
    assert!(!note_id.is_empty());
}

#[tokio::test]
async fn test_remember_recall_smoke() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "The attention mechanism in transformers uses Q K V matrices",
                "memory_type": "semantic",
                "salience": 0.8,
                "decay": 0.01
            }),
        )
        .await
        .expect("memory.remember succeeds");

    let note_id = result["id"].as_str().expect("has note_id");
    assert!(!note_id.is_empty());

    let recall_result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "attention mechanism transformers" }),
        )
        .await
        .expect("memory.recall succeeds");

    let hits = recall_result.as_array().expect("array of hits");
    assert!(!hits.is_empty(), "recall returned at least one result");
    let first_id = hits[0]["id"].as_str().unwrap();
    assert_eq!(first_id, note_id, "recalled the memory we just created");
}

#[tokio::test]
async fn test_recall_decay_ranking() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Both notes have IDENTICAL content so BM25 assigns equal relevance scores.
    // The only difference is creation time and decay_factor, so temporal decay
    // must determine the ranking. This makes the test independent of BM25 tie-breaking.
    let shared_content = "memory about neural networks and deep learning";

    let fresh = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": shared_content,
                "salience": 0.7,
                "decay": 0.01
            }),
        )
        .await
        .expect("fresh remember");
    let fresh_id = fresh["id"].as_str().unwrap().to_string();

    // Create old memory (simulate 90 days ago) with high decay
    let old = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": shared_content,
                "salience": 0.7,
                "decay": 0.1
            }),
        )
        .await
        .expect("old remember");
    let old_id = old["id"].as_str().unwrap().to_string();

    // Manually backdate the old note to simulate age
    let old_uuid: uuid::Uuid = old_id.parse().unwrap();
    let note_store = rt
        .notes(&rt.authorize(Namespace::local()).unwrap())
        .unwrap();
    let mut old_note = note_store.get_note(old_uuid).await.unwrap().unwrap();
    old_note.created_at -= 90 * 86_400_000_000i64; // 90 days in microseconds
    note_store.upsert_note(old_note).await.unwrap();

    // Disable MMR penalty so identical-content notes are ranked purely by
    // temporal decay. MMR would suppress the second hit (rank 2) by -0.1,
    // which can invert the temporal ordering when scores are close.
    let recall_result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "neural networks deep learning",
                "config": {
                    "scoring": {
                        "mmr_penalty": 0.0
                    }
                }
            }),
        )
        .await
        .expect("recall succeeds");

    let hits = recall_result.as_array().expect("array");
    let ranks: Vec<(&str, f64)> = hits
        .iter()
        .map(|h| {
            (
                h["id"].as_str().unwrap(),
                h["rank_score"].as_f64().unwrap_or(0.0),
            )
        })
        .collect();
    let fresh_entry = ranks
        .iter()
        .find(|(id, _)| *id == fresh_id)
        .expect("fresh in results");
    let old_entry = ranks
        .iter()
        .find(|(id, _)| *id == old_id)
        .expect("old in results");
    assert!(
        fresh_entry.1 > old_entry.1,
        "fresh memory (rank_score={}) should rank higher than 90-day-old high-decay memory (rank_score={})",
        fresh_entry.1,
        old_entry.1
    );
}

#[tokio::test]
async fn test_recall_salience_ranking() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Use non-identical content so MMR penalty does not affect the test.
    // The rank_score difference between salience=0.9 and salience=0.1 is
    // ~10% under the archive scoring model (1.18 vs 1.02 salience_boost), which
    // would be eliminated by the MMR penalty (-0.1) on identical content.
    let high = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "high-salience concept about knowledge representation theory",
                "salience": 0.9,
                "decay": 0.0
            }),
        )
        .await
        .expect("high salience remember");
    let high_id = high["id"].as_str().unwrap().to_string();

    let low = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "low-salience concept about knowledge representation systems",
                "salience": 0.1,
                "decay": 0.0
            }),
        )
        .await
        .expect("low salience remember");
    let low_id = low["id"].as_str().unwrap().to_string();

    let recall_result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "knowledge representation" }),
        )
        .await
        .expect("recall succeeds");

    let hits = recall_result.as_array().expect("array");
    let ranks: Vec<(&str, f64)> = hits
        .iter()
        .map(|h| {
            (
                h["id"].as_str().unwrap(),
                h["rank_score"].as_f64().unwrap_or(0.0),
            )
        })
        .collect();
    let high_entry = ranks
        .iter()
        .find(|(id, _)| *id == high_id)
        .expect("high in results");
    let low_entry = ranks
        .iter()
        .find(|(id, _)| *id == low_id)
        .expect("low in results");
    assert!(
        high_entry.1 >= low_entry.1,
        "high salience memory (rank_score={}) should rank >= low salience (rank_score={})",
        high_entry.1,
        low_entry.1
    );
}

#[tokio::test]
async fn test_recall_memory_type_filter() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "episodic event about meeting with Alice",
                "memory_type": "episodic",
                "salience": 0.7
            }),
        )
        .await
        .expect("episodic remember");

    let semantic = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "semantic fact about meeting protocols",
                "memory_type": "semantic",
                "salience": 0.7
            }),
        )
        .await
        .expect("semantic remember");
    let semantic_id = semantic["id"].as_str().unwrap().to_string();

    let filtered = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "meeting", "memory_type": "semantic" }),
        )
        .await
        .expect("recall with filter");

    let hits = filtered.as_array().expect("array");
    assert!(!hits.is_empty(), "got results with memory_type filter");
    for hit in hits {
        let mt = hit["memory_type"].as_str().unwrap_or("");
        assert_eq!(mt, "semantic", "only semantic results returned");
    }
    let ids: Vec<&str> = hits.iter().map(|h| h["id"].as_str().unwrap()).collect();
    assert!(
        ids.contains(&semantic_id.as_str()),
        "semantic note is in results"
    );
}

#[test]
fn test_memory_pack_requires_kg() {
    assert_eq!(MemoryPack::REQUIRES, &["kg"]);
    assert_eq!(MemoryPack::NAME, "memory");
    assert_eq!(MemoryPack::NOTE_KINDS, &["memory"]);
}

/// Regression test for issue #93: source_id must NOT be stored in note properties.
/// The annotates edge is the sole authorized source reference (ADR-036 §4).
#[tokio::test]
async fn test_remember_source_id_not_in_properties() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create a real entity to use as the source (source_id must exist in namespace).
    let source = registry
        .dispatch(
            "create",
            json!({
                "kind": "person",
                "name": "Alice",
                "description": "test source person"
            }),
        )
        .await
        .expect("create source entity");
    let source_uuid = source["id"].as_str().unwrap().to_string();

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "memory with a source",
                "source": source_uuid
            }),
        )
        .await
        .expect("remember with source_id");

    let note_id: Uuid = result["id"].as_str().unwrap().parse().expect("valid uuid");

    let note_store = rt
        .notes(&rt.authorize(Namespace::local()).unwrap())
        .expect("note store");
    let note = note_store
        .get_note(note_id)
        .await
        .expect("get note")
        .expect("note exists");

    if let Some(props) = &note.properties {
        assert!(
            props.get("source_id").is_none(),
            "source_id must not be stored in note properties; got: {props:?}"
        );
    }
}

/// ADR-021 §4 (F108): decay_factor >= 0 is the only constraint — no upper cap.
/// Values above 1.0 are valid (fast-fading memories with very short effective half-lives).
/// Negative values are rejected with InvalidInput.
#[tokio::test]
async fn test_remember_decay_factor_no_upper_cap() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // decay_factor = 5.0 is valid — no upper cap per ADR-021 §4
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "memory with high decay rate",
                "decay": 5.0
            }),
        )
        .await
        .expect("remember with decay_factor > 1.0 should succeed");

    let note_id: Uuid = result["id"].as_str().unwrap().parse().expect("valid uuid");

    let note_store = rt
        .notes(&rt.authorize(Namespace::local()).unwrap())
        .expect("note store");
    let note = note_store
        .get_note(note_id)
        .await
        .expect("get note")
        .expect("note exists");

    let df = note.decay_factor.unwrap_or(0.0);
    // Stored value must match exactly (not clamped to 1.0)
    assert!(
        (df - 5.0).abs() < 1e-10,
        "decay_factor should be stored as-is (5.0), got {df}"
    );
}

/// ADR-021 §4 (F108): negative decay_factor is rejected.
#[tokio::test]
async fn test_remember_decay_factor_negative_rejected() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "memory with negative decay",
                "decay": -0.1
            }),
        )
        .await;

    assert!(result.is_err(), "negative decay_factor must be rejected");
}

/// ADR-021 §4 (F107): remember always writes memory_type to properties.
/// When memory_type is absent, it defaults to "episodic".
#[tokio::test]
async fn test_remember_default_memory_type_written_to_properties() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    let result = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "memory without explicit type" }),
        )
        .await
        .expect("remember without memory_type");

    let note_id: Uuid = result["id"].as_str().unwrap().parse().expect("valid uuid");

    // The response must carry memory_type
    assert_eq!(
        result["memory_type"].as_str(),
        Some("episodic"),
        "response must include default memory_type"
    );

    let note_store = rt
        .notes(&rt.authorize(Namespace::local()).unwrap())
        .expect("note store");
    let note = note_store
        .get_note(note_id)
        .await
        .expect("get note")
        .expect("note exists");

    let stored_type = note
        .properties
        .as_ref()
        .and_then(|p| p.get("memory_type"))
        .and_then(|v| v.as_str());
    assert_eq!(
        stored_type,
        Some("episodic"),
        "memory_type must be written to properties even when not supplied"
    );
}

/// ADR-021 §4 (F109): invalid UUID string in source_id is rejected with an error.
#[tokio::test]
async fn test_remember_invalid_source_id_uuid_rejected() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "memory with bad source_id",
                "source": "not-a-valid-uuid"
            }),
        )
        .await;

    assert!(
        result.is_err(),
        "invalid source_id UUID must cause an error, got: {result:?}"
    );
}

/// ADR-021 §4 (F108): salience outside [0, 1] is rejected.
#[tokio::test]
async fn test_remember_salience_out_of_range_rejected() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let neg = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "test", "salience": -0.1 }),
        )
        .await;
    assert!(neg.is_err(), "negative salience must be rejected");

    let rt2 = make_runtime();
    let registry2 = make_registry(rt2);
    let above = registry2
        .dispatch(
            "memory.remember",
            json!({ "content": "test", "salience": 1.1 }),
        )
        .await;
    assert!(above.is_err(), "salience > 1 must be rejected");
}

/// ADR-033 §2 (F222): recall.rerank is callable and returns expected shape.
#[tokio::test]
async fn test_recall_rerank_passthrough_with_no_active_rerankers() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let candidates = json!([
        { "id": "00000000-0000-0000-0000-000000000001", "fused_score": 0.8 },
        { "id": "00000000-0000-0000-0000-000000000002", "fused_score": 0.6 },
    ]);

    let result = registry
        .dispatch("memory.recall_rerank", json!({ "candidates": candidates }))
        .await
        .expect("recall.rerank with no active rerankers");

    let reranked = result["reranked"].as_array().expect("reranked array");
    assert_eq!(reranked.len(), 2, "must return one entry per candidate");
    for entry in reranked {
        let scores = entry["rerank_scores"]
            .as_object()
            .expect("rerank_scores object");
        assert!(
            scores.is_empty(),
            "no active rerankers → empty rerank_scores, got {scores:?}"
        );
    }
    let active = result["active_rerankers"]
        .as_array()
        .expect("active_rerankers array");
    assert!(active.is_empty(), "no active rerankers expected");
}

#[test]
fn test_memory_dotted_verbs_registered() {
    let names: Vec<&str> = MemoryPack::HANDLERS.iter().map(|v| v.name).collect();
    assert!(names.contains(&"memory.recall_candidates"));
    assert!(names.contains(&"memory.recall_fuse"));
    assert!(names.contains(&"memory.recall_score"));
    assert!(names.contains(&"memory.recall_embed"));
    // F222: recall.rerank must be registered (ADR-033 §2)
    assert!(
        names.contains(&"memory.recall_rerank"),
        "recall.rerank not found in: {names:?}"
    );
}

#[tokio::test]
async fn test_recall_candidates_returns_arrays() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "attention recall candidates" }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch(
            "memory.recall_candidates",
            json!({ "query": "attention candidates" }),
        )
        .await
        .expect("memory.recall_candidates");

    let text = result["text_candidates"].as_array().expect("text array");
    assert!(!text.is_empty());
    assert!(text[0]["id"].as_str().is_some());
    assert!(text[0]["score"].as_f64().is_some());
    assert!(text[0]["rank"].as_u64().is_some());
    assert!(result["candidate_limit"].as_u64().is_some());
    assert!(
        result.get("text_hits").is_none(),
        "old count field must be absent"
    );
}

#[tokio::test]
async fn test_recall_fuse_returns_fused_candidates_not_full_recall() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "attention fusion diagnostic" }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch("memory.recall_fuse", json!({ "query": "attention fusion" }))
        .await
        .expect("memory.recall_fuse");

    let fused = result["fused_candidates"].as_array().expect("fused array");
    assert!(!fused.is_empty());
    assert!(fused[0]["fused_score"].as_f64().is_some());
    assert!(fused[0]["source"].as_str().is_some());
    assert!(
        fused[0].get("content").is_none(),
        "full recall field must be absent"
    );
    assert!(
        fused[0].get("salience").is_none(),
        "full recall field must be absent"
    );
}

#[tokio::test]
async fn test_recall_breakdown_is_opt_in() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "attention score breakdown", "salience": 0.8 }),
        )
        .await
        .expect("memory.remember");

    let plain = registry
        .dispatch("memory.recall", json!({ "query": "attention breakdown" }))
        .await
        .expect("memory.recall");
    let hits = plain.as_array().unwrap();
    assert!(!hits.is_empty());
    assert!(
        hits[0].get("breakdown").is_none(),
        "breakdown must be absent by default"
    );

    let explained = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "attention breakdown", "config": { "include_breakdown": true } }),
        )
        .await
        .expect("recall with breakdown");
    let hits = explained.as_array().unwrap();
    assert!(!hits.is_empty());
    let bd = &hits[0]["breakdown"];
    assert!(bd["relevance"].as_f64().is_some());
    assert!(bd["salience_raw"].as_f64().is_some());
    assert!(bd["salience_decayed"].as_f64().is_some());
    assert!(bd["temporal"].as_f64().is_some());
    assert!(bd["weighted"]["relevance_contribution"].as_f64().is_some());
}

/// recall.candidates always includes both array keys even when the embedding model is absent
/// and the vector path returns nothing.
#[tokio::test]
async fn test_recall_candidates_vector_field_always_present() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "text only candidate check" }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch(
            "memory.recall_candidates",
            json!({ "query": "text only candidate" }),
        )
        .await
        .expect("memory.recall_candidates");

    // Both arrays must be present even if one is empty.
    assert!(
        result["vector_candidates"].as_array().is_some(),
        "vector_candidates key must always be present"
    );
    assert!(
        result["text_candidates"].as_array().is_some(),
        "text_candidates key must always be present"
    );
}

/// recall.fuse source field must be a plain string ("text"), not a serde-tagged enum.
#[tokio::test]
async fn test_recall_fuse_source_field_is_plain_string() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "fuse source string check" }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch(
            "memory.recall_fuse",
            json!({ "query": "fuse source string" }),
        )
        .await
        .expect("memory.recall_fuse");

    let fused = result["fused_candidates"].as_array().expect("fused array");
    assert!(!fused.is_empty());
    let source = fused[0]["source"].as_str().expect("source is string");
    // Must be a plain label, not a JSON object or enum tag.
    assert!(
        source == "text" || source == "vector" || source == "both",
        "source must be a plain label, got {source:?}"
    );
}

/// Verifies that recall.fuse routes through khive_retrieval::fuse_search_results
/// by injecting a non-default fusion config (Rrf k=1) and asserting the fused
/// score matches the RRF k=1 formula: 1/(k + rank) = 1/(1 + 1) = 0.5.
///
/// Under default k=60 the score would be 1/61 ≈ 0.0164. The large gap (0.5 vs
/// 0.0164) is the discriminator: if the adapter did not pass k=1 through to
/// khive_retrieval::HybridConfig, the score would not be 0.5.
#[tokio::test]
async fn test_recall_fuse_rrf_k1_uses_retrieval_adapter() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "retrieval adapter rrf k1 probe memory" }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch(
            "memory.recall_fuse",
            json!({
                "query": "retrieval adapter rrf k1 probe",
                "config": {
                    "fuse_strategy": { "rrf": { "k": 1 } }
                }
            }),
        )
        .await
        .expect("recall.fuse with Rrf k=1");

    let fused = result["fused_candidates"].as_array().expect("fused array");
    assert!(
        !fused.is_empty(),
        "recall.fuse must return at least one candidate"
    );

    let score = fused[0]["fused_score"]
        .as_f64()
        .expect("fused_score is f64");
    // Rank 1 in a single text source with k=1: RRF = 1/(1+1) = 0.5.
    // If k=60 were used instead, score ≈ 0.0164 — the gap proves the adapter works.
    let expected = 0.5_f64;
    assert!(
        (score - expected).abs() < 1e-6,
        "RRF k=1, rank 1 → fused_score must be 0.5; got {score:.6} \
         (≈0.0164 means the adapter passed k=60 instead of k=1)"
    );
}

/// Regression: after wiring khive-retrieval into fuse_candidates, the recall.fuse
/// response shape must be unchanged — top-level strategy + candidate_limit, and
/// per-candidate note_id + fused_score + source must all be present. Full recall
/// fields (content, salience) must remain absent.
#[tokio::test]
async fn test_recall_fuse_shape_preserved_after_retrieval_wiring() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "shape regression check after retrieval wiring" }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch(
            "memory.recall_fuse",
            json!({ "query": "shape regression retrieval wiring" }),
        )
        .await
        .expect("memory.recall_fuse");

    // Top-level shape
    assert!(
        result.get("strategy").is_some(),
        "strategy field must be present in recall.fuse response"
    );
    assert!(
        result["candidate_limit"].as_u64().is_some(),
        "candidate_limit must be a non-negative integer"
    );

    let fused = result["fused_candidates"]
        .as_array()
        .expect("fused_candidates array");
    assert!(!fused.is_empty(), "fused_candidates must be non-empty");

    let c = &fused[0];
    assert!(c["id"].as_str().is_some(), "note_id must be a string UUID");
    assert!(
        c["fused_score"].as_f64().is_some(),
        "fused_score must be a float"
    );
    let source = c["source"].as_str().expect("source must be a plain string");
    assert!(
        matches!(source, "text" | "vector" | "both"),
        "source must be a plain label, got {source:?}"
    );
    // Full recall fields must not leak into fuse output
    assert!(
        c.get("content").is_none(),
        "content must be absent from recall.fuse output"
    );
    assert!(
        c.get("salience").is_none(),
        "salience must be absent from recall.fuse output"
    );
}

/// When include_breakdown is true, breakdown.total() must equal the hit's composite score.
#[tokio::test]
async fn test_recall_breakdown_total_matches_composite_score() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "arithmetic score check memory", "salience": 0.7 }),
        )
        .await
        .expect("memory.remember");

    let result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "arithmetic score check", "config": { "include_breakdown": true } }),
        )
        .await
        .expect("recall with breakdown");

    let hits = result.as_array().unwrap();
    assert!(!hits.is_empty());
    let hit = &hits[0];
    // `rank_score` is the composite score from the archive pipeline.
    // `score` is the absolute relevance (pre-fusion raw cosine, or composite if no vector).
    // The breakdown weighted sum corresponds to the legacy compute_score path which
    // computes contributions under the RecallConfig additive model. The rank_score
    // from the archive multiplicative model does NOT equal the breakdown sum —
    // they are two different scoring strategies coexisting in the pipeline.
    // Here we just verify rank_score is bounded in [0, 1] and breakdown fields are present.
    let rank_score = hit["rank_score"].as_f64().expect("hit has rank_score");
    assert!(
        (0.0..=1.0).contains(&rank_score),
        "rank_score {rank_score} must be in [0, 1]"
    );
    let bd = &hit["breakdown"];
    let rc = bd["weighted"]["relevance_contribution"].as_f64().unwrap();
    let ic = bd["weighted"]["salience_contribution"].as_f64().unwrap();
    let tc = bd["weighted"]["temporal_contribution"].as_f64().unwrap();
    let total = rc + ic + tc;
    assert!(
        (0.0..=1.0).contains(&total),
        "breakdown weighted sum {total} must be in [0, 1]"
    );
}

/// Regression test for issue #94: non-memory notes must not appear in recall results.
///
/// Creates more non-memory notes than the default `limit * 4` candidate threshold (the amount
/// at which non-memory notes can dominate the candidate pool without pre-filtering), then
/// verifies that recall returns only memory-kind notes.
#[tokio::test]
async fn test_recall_excludes_non_memory_notes() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create 50 observation notes whose content matches the recall query — enough to
    // dominate a `limit=5` candidate pool at `limit * 4 = 20` without pre-filtering.
    let tok = rt.authorize(Namespace::local()).unwrap();
    for i in 0..50 {
        rt.create_note(
            &tok,
            "observation",
            None,
            &format!("observation {i} about attention mechanisms in neural networks"),
            Some(0.5),
            None,
            vec![],
        )
        .await
        .expect("create observation");
    }

    // Create a small number of memory notes with matching content.
    let mem1 = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "memory note about attention mechanisms in neural networks",
                "salience": 0.8
            }),
        )
        .await
        .expect("remember 1");
    let mem2 = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "another memory note about attention mechanisms",
                "salience": 0.7
            }),
        )
        .await
        .expect("remember 2");
    let mem1_id = mem1["id"].as_str().unwrap().to_string();
    let mem2_id = mem2["id"].as_str().unwrap().to_string();

    let result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "attention mechanisms neural networks", "limit": 5 }),
        )
        .await
        .expect("recall succeeds");

    let hits = result.as_array().expect("array of hits");
    assert!(
        !hits.is_empty(),
        "recall should return memory notes even when non-memory notes dominate the index"
    );
    let ids: Vec<&str> = hits.iter().map(|h| h["id"].as_str().unwrap()).collect();
    assert!(
        ids.contains(&mem1_id.as_str()) || ids.contains(&mem2_id.as_str()),
        "at least one memory note must appear in recall results"
    );
    for hit in hits {
        // recall must never surface observation or other non-memory kinds
        assert!(
            hit.get("id").is_some(),
            "hit has note_id field (memory pack shape)"
        );
        assert!(
            hit.get("salience").is_some(),
            "hit has salience field (memory pack shape)"
        );
    }
}

/// Regression test for issue #430: recall must return the requested count of
/// memory results even when a tiny `candidate_limit` and many higher-ranking
/// non-memory notes would otherwise exhaust the candidate cap before the
/// memory-kind scope is ever applied.
#[tokio::test]
async fn recall_candidate_cap_counts_eligible_memories_not_generic_notes() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // 30 non-memory notes, all matching the query, all ranked ahead of the
    // memory notes below (higher salience is irrelevant to FTS/vector rank,
    // but sheer count is enough to exhaust a `candidate_limit` of 5).
    let tok = rt.authorize(Namespace::local()).unwrap();
    for i in 0..30 {
        rt.create_note(
            &tok,
            "observation",
            None,
            &format!("observation {i} about quokka migration patterns in tundra"),
            Some(0.9),
            None,
            vec![],
        )
        .await
        .expect("create observation");
    }

    let want = 5usize;
    let mut memory_ids = Vec::with_capacity(want);
    for i in 0..want {
        let mem = registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("memory note {i} about quokka migration patterns in tundra"),
                    "salience": 0.6
                }),
            )
            .await
            .expect("remember");
        memory_ids.push(mem["id"].as_str().unwrap().to_string());
    }

    // `candidate_limit: 5` is smaller than the 30 non-memory notes competing
    // for the same candidate window — without memory-kind scoping applied
    // before the cap, the 5 memory notes can be starved out entirely.
    let result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "quokka migration patterns tundra",
                "limit": want,
                "config": { "candidate_limit": 5 },
            }),
        )
        .await
        .expect("recall succeeds");

    let hits = result.as_array().expect("array of hits");
    assert_eq!(
        hits.len(),
        want,
        "recall must return the requested count of memories even when non-memory \
         notes dominate a small candidate window; got {} of {want}: {hits:?}",
        hits.len()
    );
    let ids: std::collections::HashSet<&str> =
        hits.iter().map(|h| h["id"].as_str().unwrap()).collect();
    for mid in &memory_ids {
        assert!(
            ids.contains(mid.as_str()),
            "expected memory {mid} in recall results, got {ids:?}"
        );
    }
}

/// Regression for #159: PackTunable::apply_config must actually affect recall
/// scoring, not just mutate a Mutex that handlers ignore.
///
/// The wire is:
///   apply_config(weights) → MemoryPack.config (Mutex)
///   → MemoryPack::active_config() reads it
///   → handle_recall / handle_recall_score use it as the base
///   → compute_score uses the tuned weights
///
/// This test uses `recall.score` (deterministic — no FTS/vector noise) with
/// no per-call `config` argument, applies different configs via
/// PackTunable::apply_config, and verifies the resulting `total` score
/// reflects the tuned weights. Without the active_config wire (issue #159
/// bug), the result would always reflect RecallConfig::default() regardless
/// of apply_config.
#[tokio::test]
async fn test_pack_tunable_apply_config_affects_recall_score() {
    use khive_pack_memory::config::RecallConfig;

    let rt = make_runtime();
    let pack = MemoryPack::new(rt.clone());

    // Sanity: with default config (0.70/0.20/0.10), the score for
    //   rrf=1.0, salience=1.0, decay=0.0, age=0 → 0.70+0.20+0.10 = 1.0
    // With salience_only (0.0/1.0/0.0), the score for
    //   rrf=1.0, salience=0.0, decay=0.0, age=0 → 0.0
    // The difference is large enough to prove the weights flow through.

    // Apply salience-only config to the pack.
    let salience_only = RecallConfig {
        relevance_weight: 0.0,
        salience_weight: 1.0,
        temporal_weight: 0.0,
        ..RecallConfig::default()
    };
    pack.apply_config(serde_json::to_value(&salience_only).unwrap())
        .expect("apply_config (salience-only) succeeds");

    let mut builder = VerbRegistryBuilder::new();
    builder.register(KgPack::new(rt.clone()));
    builder.register(pack);
    let registry = builder.build().expect("registry builds");

    // Call recall.score with high relevance but ZERO salience — under
    // salience-only weights, score MUST be 0.0. Under default weights
    // (the bug), it would be 0.70.
    let result = registry
        .dispatch(
            "memory.recall_score",
            json!({
                "rrf": 1.0,
                "salience": 0.0,
                "decay_factor": 0.0,
                "age_days": 0.0,
            }),
        )
        .await
        .expect("recall.score succeeds");
    let total = result["total"].as_f64().expect("total is a number");
    assert!(
        total.abs() < 1e-9,
        "under salience_weight=1.0, salience=0 → score=0; got {total}. \
         If non-zero, MemoryPack::active_config() is not being used by \
         recall.score (#159 regression)."
    );

    // Mirror check: under relevance-only weights with rrf=1.0, salience=0 → score=1.0.
    // This requires a SECOND pack instance because PackRuntime ownership prevents
    // mutating the live registry's config from outside. We construct the test
    // by exercising the same wire on a fresh pack.
    let rt2 = make_runtime();
    let pack2 = MemoryPack::new(rt2.clone());
    // Use Weighted strategy so the input relevance score (1.0) passes through
    // unnormalized — RRF strategy would scale it by (k+1) = 61, producing 61.0.
    let relevance_only = RecallConfig {
        relevance_weight: 1.0,
        salience_weight: 0.0,
        temporal_weight: 0.0,
        fuse_strategy: FusionStrategy::Weighted {
            weights: vec![0.5, 0.5],
        },
        ..RecallConfig::default()
    };
    pack2
        .apply_config(serde_json::to_value(&relevance_only).unwrap())
        .expect("apply_config (relevance-only) succeeds");

    let mut builder2 = VerbRegistryBuilder::new();
    builder2.register(KgPack::new(rt2.clone()));
    builder2.register(pack2);
    let registry2 = builder2.build().expect("registry2 builds");

    let result2 = registry2
        .dispatch(
            "memory.recall_score",
            json!({
                "rrf": 1.0,
                "salience": 0.0,
                "decay_factor": 0.0,
                "age_days": 0.0,
            }),
        )
        .await
        .expect("recall.score (relevance-only) succeeds");
    let total2 = result2["total"].as_f64().expect("total is a number");
    assert!(
        (total2 - 1.0).abs() < 1e-9,
        "under relevance_weight=1.0 with rrf=1.0 (Weighted strategy) → score=1.0; got {total2}"
    );
}

// ── ADR-033 §6 knob tests ──────────────────────────────────────────────────

#[tokio::test]
async fn test_recall_default_identity() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create multiple memories so the identity comparison is meaningful
    // (single-hit fixtures can't distinguish ordering changes).
    for content in [
        "the mitochondria is the powerhouse of the cell",
        "ribosomes synthesize proteins in the cell",
        "the nucleus contains the cell's DNA",
        "lysosomes digest cellular waste in the cell",
    ] {
        registry
            .dispatch(
                "memory.remember",
                json!({ "content": content, "salience": 0.8 }),
            )
            .await
            .expect("remember succeeds");
    }

    // Baseline recall with no knobs
    let base = registry
        .dispatch("memory.recall", json!({ "query": "cell" }))
        .await
        .expect("baseline recall succeeds");
    let base_hits = base.as_array().expect("array");
    assert!(
        base_hits.len() >= 2,
        "baseline must return at least two hits to make ordering meaningful, got {}",
        base_hits.len()
    );

    // Same call with all three knobs explicitly set to null — must be byte-identical
    let knobless = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "cell",
                "top_k": null,
                "fusion_strategy": null,
                "score_floor": null,
            }),
        )
        .await
        .expect("recall with all knobs null succeeds");
    let knobless_hits = knobless.as_array().expect("array");

    assert_eq!(
        base_hits.len(),
        knobless_hits.len(),
        "null knobs must not change result count"
    );

    // Full ordering identity: each hit's note_id AND fused_score must match
    // position-by-position. This catches a regression where a null knob silently
    // shifts the ranking or rescaling.
    for (i, (b, k)) in base_hits.iter().zip(knobless_hits.iter()).enumerate() {
        assert_eq!(
            b["id"].as_str(),
            k["id"].as_str(),
            "null knobs altered note_id at position {i}"
        );
        // Scores must round-trip; allow tiny float jitter
        let bs = b["score"].as_f64().unwrap_or(0.0);
        let ks = k["score"].as_f64().unwrap_or(0.0);
        assert!(
            (bs - ks).abs() < 1e-9,
            "null knobs altered score at position {i}: baseline={bs} knobless={ks}"
        );
    }
}

#[tokio::test]
async fn test_recall_top_k_override() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create several distinct memories to ensure the pool is large enough
    for i in 0..5 {
        registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("rust ownership memory safety concept {i}"),
                    "salience": 0.7
                }),
            )
            .await
            .expect("remember succeeds");
    }

    // Recall with top_k=2 — must not return more than 2 results
    let result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "rust ownership memory safety", "top_k": 2 }),
        )
        .await
        .expect("recall with top_k=2 succeeds");
    let hits = result.as_array().expect("array");
    assert!(
        hits.len() <= 2,
        "top_k=2 must return at most 2 results, got {}",
        hits.len()
    );

    // top_k=1 must return at most 1
    let result1 = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "rust ownership memory safety", "top_k": 1 }),
        )
        .await
        .expect("recall with top_k=1 succeeds");
    let hits1 = result1.as_array().expect("array");
    assert!(
        hits1.len() <= 1,
        "top_k=1 must return at most 1 result, got {}",
        hits1.len()
    );
}

#[tokio::test]
async fn test_recall_fusion_strategy_override() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "gradient descent optimization machine learning",
                "salience": 0.8
            }),
        )
        .await
        .expect("remember succeeds");

    // Each valid strategy must succeed and return an array
    for strategy in &["rrf", "weighted", "union", "vector_only", "keyword_only"] {
        let result = registry
            .dispatch(
                "memory.recall",
                json!({
                    "query": "gradient descent optimization",
                    "fusion_strategy": strategy
                }),
            )
            .await
            .unwrap_or_else(|e| panic!("recall with fusion_strategy={strategy:?} failed: {e}"));
        assert!(
            result.is_array(),
            "fusion_strategy={strategy:?} must return an array, got {result}"
        );
    }

    // Invalid strategy must return an error
    let err = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "gradient descent optimization",
                "fusion_strategy": "bogus"
            }),
        )
        .await;
    assert!(err.is_err(), "invalid fusion_strategy must return an error");
    let msg = err.unwrap_err().to_string();
    assert!(
        msg.contains("rrf")
            && msg.contains("weighted")
            && msg.contains("union")
            && msg.contains("vector_only")
            && msg.contains("keyword_only"),
        "error message must list valid strategies, got: {msg}"
    );
}

#[tokio::test]
async fn test_recall_score_floor() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "backpropagation neural network training algorithm",
                "salience": 0.6
            }),
        )
        .await
        .expect("remember succeeds");

    // Baseline: no floor — get result count
    let base = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "backpropagation neural network" }),
        )
        .await
        .expect("baseline recall succeeds");
    let base_count = base.as_array().expect("array").len();

    // score_floor=0.99 must not return MORE results than baseline
    let floored = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "backpropagation neural network",
                "score_floor": 0.99
            }),
        )
        .await
        .expect("recall with score_floor=0.99 succeeds");
    let floored_hits = floored.as_array().expect("array");
    assert!(
        floored_hits.len() <= base_count,
        "score_floor=0.99 must return ≤ baseline count ({base_count}), got {}",
        floored_hits.len()
    );

    // All returned hits must have score >= 0.99
    for hit in floored_hits {
        let score = hit["score"].as_f64().expect("score is a number");
        assert!(
            score >= 0.99,
            "score_floor=0.99: all returned scores must be ≥ 0.99, got {score}"
        );
    }

    // score_floor=0.0 must behave same as no floor
    let zero_floor = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "backpropagation neural network",
                "score_floor": 0.0
            }),
        )
        .await
        .expect("recall with score_floor=0.0 succeeds");
    let zero_count = zero_floor.as_array().expect("array").len();
    assert_eq!(
        zero_count, base_count,
        "score_floor=0.0 must return same count as no floor"
    );
}

// ── Reranker integration tests (PR #375) ────────────────────────────────────

/// PR #375: empty reranker_weights is a pass-through — results must be identical
/// to a baseline recall with no reranker config.
#[tokio::test]
async fn test_recall_with_empty_reranker_weights_is_passthrough() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    for i in 0..4 {
        registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("memory about deep learning topic {i}"),
                    "salience": 0.5 + (i as f64) * 0.1,
                    "decay": 0.0
                }),
            )
            .await
            .expect("memory.remember");
    }

    let baseline = registry
        .dispatch("memory.recall", json!({ "query": "deep learning" }))
        .await
        .expect("baseline recall");
    let baseline_ids: Vec<String> = baseline
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap().to_string())
        .collect();

    let with_empty_reranker = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "deep learning",
                "config": { "reranker_weights": {} }
            }),
        )
        .await
        .expect("recall with empty reranker_weights");
    let reranker_ids: Vec<String> = with_empty_reranker
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap().to_string())
        .collect();

    assert_eq!(
        baseline_ids, reranker_ids,
        "empty reranker_weights must be a pass-through — result ordering must match baseline"
    );
}

/// PR #375: reranker_weights with salience=1.0 must promote the highest-salience
/// memory to rank #1, even when it would rank lower under the default compute_score.
///
/// Strengthened: captures baseline ordering first (no reranker) and asserts that
/// the reranked order actually differs — proving the REPLACE wiring is not a no-op.
///
/// Fixture design: all notes contain the query keyword so all are retrieved.
/// Low-salience notes have richer keyword density (higher FTS BM25).  Baseline
/// uses pure relevance scoring (salience_weight=0) so the keyword-dense
/// low-salience notes rank first.  The salience=1.0 reranker then flips the
/// order, placing the high-salience note at rank #1.
#[tokio::test]
async fn test_recall_with_reranker_weights_changes_ordering() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Three low-salience notes with high keyword density for "gradient descent" —
    // their BM25 score will be higher than the high-salience note.
    for _ in 0..3 {
        registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": "gradient descent gradient descent gradient descent optimization",
                    "salience": 0.1,
                    "decay": 0.0
                }),
            )
            .await
            .expect("low salience remember");
    }

    // One high-salience note that mentions gradient descent only once — lower BM25
    // relevance so baseline (pure-relevance) ranks it below the low-salience notes.
    let high_salience = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "gradient descent is a key technique in machine learning",
                "salience": 0.95,
                "decay": 0.0
            }),
        )
        .await
        .expect("high salience remember");
    let high_id = high_salience["id"].as_str().unwrap().to_string();

    // Step 1: baseline recall — pure relevance scoring (salience_weight=0) so
    // BM25-heavy low-salience notes rank first.
    let baseline = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "gradient descent",
                "config": {
                    "relevance_weight": 1.0,
                    "salience_weight": 0.0,
                    "temporal_weight": 0.0
                }
            }),
        )
        .await
        .expect("baseline recall");
    let baseline_hits = baseline.as_array().expect("baseline array");
    assert!(
        baseline_hits.len() >= 2,
        "need at least 2 results to test ordering change, got {}",
        baseline_hits.len()
    );
    let baseline_ids: Vec<String> = baseline_hits
        .iter()
        .map(|h| h["id"].as_str().unwrap().to_string())
        .collect();
    let baseline_top = &baseline_ids[0];

    // Baseline must NOT have high_id at rank #1 — if it does, the fixture is
    // degenerate (the reranker would be a no-op for the top position).
    assert_ne!(
        baseline_top, &high_id,
        "fixture error: high-salience note already ranks first in baseline; \
         reranker change cannot be demonstrated. baseline={baseline_ids:?}"
    );

    // Step 2: reranked recall — salience weight only (REPLACE strategy).
    let reranked = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "gradient descent",
                "config": {
                    "reranker_weights": { "salience": 1.0 }
                }
            }),
        )
        .await
        .expect("recall with salience reranker");
    let reranked_hits = reranked.as_array().expect("reranked array");
    assert!(!reranked_hits.is_empty(), "must get results");
    let reranked_ids: Vec<String> = reranked_hits
        .iter()
        .map(|h| h["id"].as_str().unwrap().to_string())
        .collect();
    let top_id = &reranked_ids[0];

    // Step 3: assert the reranker placed high-salience memory at rank #1.
    assert_eq!(
        top_id, &high_id,
        "salience=1.0 reranker must rank the highest-salience memory first; got {top_id} not {high_id}"
    );

    // Step 4: assert the ordering actually changed — the reranker is not a no-op.
    // baseline_top != high_id (asserted above) and top_id == high_id, so orderings differ.
    assert_ne!(
        baseline_ids, reranked_ids,
        "reranker must change the result ordering; baseline={baseline_ids:?} reranked={reranked_ids:?}"
    );
}

/// PR #375: the recall.rerank subhandler applies request weights and returns
/// non-zero rerank_scores when reranker_weights are provided.
#[tokio::test]
async fn test_rerank_subhandler_uses_request_weights() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    // Build two synthetic fused candidates with different fused_scores.
    // The one with higher fused_score should get a higher rerank_score
    // when relevance weight = 1.0.
    let candidates = json!([
        {
            "id": "00000000-0000-0000-0000-000000000001",
            "fused_score": 0.9,
            "source": "both"
        },
        {
            "id": "00000000-0000-0000-0000-000000000002",
            "fused_score": 0.3,
            "source": "text"
        }
    ]);

    let result = registry
        .dispatch(
            "memory.recall_rerank",
            json!({
                "candidates": candidates,
                "config": {
                    "reranker_weights": { "relevance": 1.0 }
                }
            }),
        )
        .await
        .expect("recall.rerank succeeds");

    let reranked = result["reranked"].as_array().expect("reranked array");
    assert_eq!(reranked.len(), 2, "both candidates returned");

    // Find scores by note_id.
    let score_for = |id: &str| -> f64 {
        reranked
            .iter()
            .find(|c| c["id"].as_str() == Some(id))
            .and_then(|c| c["rerank_score"].as_f64())
            .unwrap_or(f64::NAN)
    };
    let score_high = score_for("00000000-0000-0000-0000-000000000001");
    let score_low = score_for("00000000-0000-0000-0000-000000000002");

    assert!(
        score_high.is_finite() && score_low.is_finite(),
        "rerank_score must be a finite number; got high={score_high} low={score_low}"
    );
    assert!(
        score_high > score_low,
        "candidate with fused_score=0.9 must outscore fused_score=0.3 under relevance reranker; \
         got {score_high} vs {score_low}"
    );

    // Verify active_rerankers field is present.
    let active = result["active_rerankers"]
        .as_array()
        .expect("active_rerankers");
    assert!(
        active.iter().any(|v| v.as_str() == Some("relevance")),
        "active_rerankers must include 'relevance'"
    );
}

// ── Wave-1 hygiene fixes (v024) ────────────────────────────────────────────────

/// Fix 1 (Critical): remember(source_id=) accepts 8-char short IDs.
///
/// The chain `create → remember(source_id=$prev.id)` broke because agent-mode
/// responses carry an 8-char short ID (first 8 hex chars of the full UUID) and
/// `remember` was parsing it as a full UUID, which always fails.
#[tokio::test]
async fn test_remember_source_id_accepts_short_id() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create an entity; the internal test registry returns the full UUID in "id".
    let entity = registry
        .dispatch(
            "create",
            json!({
                "kind": "concept",
                "name": "attention mechanism",
                "description": "QKV self-attention"
            }),
        )
        .await
        .expect("create entity");

    let full_id = entity["id"].as_str().expect("entity has id");
    // Simulate agent-mode short ID: first 8 hex chars of the UUID (strip dashes).
    let short_id: String = full_id.chars().filter(|c| c != &'-').take(8).collect();
    assert_eq!(short_id.len(), 8, "derived short_id must be 8 chars");

    // remember with short id — must NOT return an error (previously did)
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "attention uses Q K V matrices",
                "source_id": short_id,
            }),
        )
        .await
        .expect("remember with 8-char short source_id must succeed");

    let note_id_str = result["id"].as_str().expect("has note_id");

    // Verify the annotates edge was created: neighbors(note, direction=out) returns
    // an array of NeighborHit; each hit carries "id" (the neighbor's UUID) and "relation".
    let neighbors = registry
        .dispatch(
            "neighbors",
            json!({
                "id": note_id_str,
                "direction": "out",
            }),
        )
        .await
        .expect("neighbors call succeeds");

    // response is a direct JSON array (not wrapped in an object)
    let hits = neighbors.as_array().expect("neighbors returns array");
    let found = hits.iter().any(|h| h["id"].as_str() == Some(full_id));
    assert!(
        found,
        "annotates edge to entity {full_id} must appear in note neighbors; got: {hits:?}\n\
         (short_id used: {short_id}, note_id: {note_id_str})"
    );
}

/// Fix 2: recall(help=true) must expose all params added in PRs #406/#421.
#[test]
fn test_handler_def_recall_params_complete() {
    use khive_types::Pack;

    let recall_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.recall")
        .expect("recall handler must be registered");

    let param_names: Vec<&str> = recall_def.params.iter().map(|p| p.name).collect();

    assert!(
        param_names.contains(&"top_k"),
        "recall HandlerDef must expose top_k param; got: {param_names:?}"
    );
    assert!(
        param_names.contains(&"score_floor"),
        "recall HandlerDef must expose score_floor param; got: {param_names:?}"
    );
    assert!(
        param_names.contains(&"fusion_strategy"),
        "recall HandlerDef must expose fusion_strategy param; got: {param_names:?}"
    );
    assert!(
        param_names.contains(&"embedding_model"),
        "recall HandlerDef must expose embedding_model param; got: {param_names:?}"
    );
    // Issue #482: verb-level presentation renamed to include_breakdown.
    assert!(
        param_names.contains(&"include_breakdown"),
        "recall HandlerDef must expose include_breakdown param (not presentation); got: {param_names:?}"
    );
    assert!(
        !param_names.contains(&"presentation"),
        "recall HandlerDef must not expose verb-level presentation (ambiguous with MCP envelope); got: {param_names:?}"
    );
}

#[test]
fn test_handler_def_remember_params_complete() {
    use khive_types::Pack;

    let remember_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.remember")
        .expect("remember handler must be registered");

    let param_names: Vec<&str> = remember_def.params.iter().map(|p| p.name).collect();
    assert!(
        param_names.contains(&"embedding_model"),
        "remember HandlerDef must expose embedding_model param; got: {param_names:?}"
    );

    // Issue #70: decay_factor defaults are now type-differentiated; description must
    // document both episodic (0.02) and semantic (0.005) defaults, not the old flat 0.01.
    let decay_def = remember_def
        .params
        .iter()
        .find(|p| p.name == "decay_factor")
        .expect("decay_factor param must exist");
    assert!(
        decay_def.description.contains("0.02"),
        "decay_factor description must document episodic default 0.02, got: {:?}",
        decay_def.description
    );
    assert!(
        decay_def.description.contains("0.005"),
        "decay_factor description must document semantic default 0.005, got: {:?}",
        decay_def.description
    );
    assert!(
        !decay_def
            .description
            .starts_with("Decay rate 0.0–1.0 (default 0.1)"),
        "decay_factor description must NOT say 'default 0.1', got: {:?}",
        decay_def.description
    );
}

/// Fix 4: score_floor is portable across fusion strategies.
///
/// Creates 10 memories with varying salience; recall with score_floor=0.3 must
/// return a non-zero comparable number of hits under both RRF and Weighted fusion
/// — not 0 for one and many for the other.
#[tokio::test]
async fn test_score_floor_portable_across_fusion_strategies() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create 10 memories ALL containing both query terms "attention" and "transformer"
    // so FTS5 returns 10 results and the score span is non-zero. With span > 0 the
    // normalizer maps scores to [0.15, 0.82], so high-salience memories score above
    // 0.3 and low-salience ones score below — the exact split the test verifies.
    // (With only some memories matching both words, FTS5 returns ≤ 1 hit whose span=0;
    // normalize_rank_fusion_scores then clamps to 0.3 * signal_strength, and
    // calculate_score with w_rel=0.7 and the episodic bonus still barely misses 0.3
    // under the correct text-weight=0.3 Weighted mapping.)
    for (i, content) in [
        "transformer architecture uses attention mechanism",
        "attention is all you need for transformer models",
        "feedforward layers in transformer with self-attention",
        "layer normalization helps transformer attention training",
        "residual connections in transformer improve attention flow",
        "positional encoding enables transformer attention over sequences",
        "multi-head attention splits queries in transformer blocks",
        "softmax function normalizes transformer attention scores",
        "token embeddings feed transformer attention layers",
        "output projection combines transformer multi-head attention",
    ]
    .iter()
    .enumerate()
    {
        let salience = 0.4 + 0.06 * (i as f64); // 0.40 to 0.94
        registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": content,
                    "salience": salience,
                    "decay_factor": 0.0,
                }),
            )
            .await
            .expect("memory.remember");
    }

    // Query relevant to several memories
    let rrf_result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "attention transformer",
                "score_floor": 0.3_f64,
                "fusion_strategy": "rrf",
                "limit": 20,
            }),
        )
        .await
        .expect("recall rrf");

    let weighted_result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "attention transformer",
                "score_floor": 0.3_f64,
                "fusion_strategy": "weighted",
                "limit": 20,
            }),
        )
        .await
        .expect("recall weighted");

    let rrf_hits = rrf_result.as_array().expect("rrf array").len();
    let weighted_hits = weighted_result.as_array().expect("weighted array").len();

    assert!(
        rrf_hits > 0,
        "score_floor=0.3 with RRF strategy must return > 0 hits (got 0); \
         RRF scores are not being normalized to [0,1]"
    );
    assert!(
        weighted_hits > 0,
        "score_floor=0.3 with Weighted strategy must return > 0 hits (got 0)"
    );
}

/// Fix 5: include_breakdown=true includes score breakdown without changing agent-mode shape.
#[tokio::test]
async fn test_recall_include_breakdown_flag_includes_breakdown() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "transformer positional encoding", "salience": 0.8 }),
        )
        .await
        .expect("memory.remember");

    // Default (agent-mode): no breakdown
    let default_result = registry
        .dispatch("memory.recall", json!({ "query": "transformer" }))
        .await
        .expect("recall default");

    let default_hits = default_result.as_array().expect("array");
    assert!(!default_hits.is_empty(), "must have hits");
    assert!(
        default_hits[0].get("breakdown").is_none(),
        "default recall must NOT include breakdown"
    );

    // include_breakdown=true: breakdown present
    let verbose_result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "transformer", "include_breakdown": true }),
        )
        .await
        .expect("recall with include_breakdown=true");

    let verbose_hits = verbose_result.as_array().expect("array");
    assert!(
        !verbose_hits.is_empty(),
        "include_breakdown=true must have hits"
    );
    let bd = verbose_hits[0]
        .get("breakdown")
        .expect("include_breakdown=true result must include breakdown");
    assert!(
        bd.get("relevance").is_some(),
        "breakdown must have relevance field; got: {bd}"
    );
    assert!(
        bd.get("temporal").is_some(),
        "breakdown must have temporal field; got: {bd}"
    );
}

/// #514 regression: presentation= must be rejected by deny_unknown_fields.
#[tokio::test]
async fn recall_presentation_alias_is_rejected_by_deny_unknown_fields() {
    let registry = make_registry(make_runtime());
    let err = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "transformer", "presentation": "verbose" }),
        )
        .await
        .expect_err("presentation alias must be rejected");

    let msg = err.to_string();
    assert!(
        msg.contains("unknown field") && msg.contains("presentation"),
        "error must mention unknown field 'presentation'; got: {msg}"
    );
}

// ── PR #444 regressions ──────────────────────────────────────────────────────

/// Trivial constant-vector embedding service for testing without real model weights.
/// The `_model` parameter is ignored; returns a synthetic `dims × seed` vector.
struct ConstVecService {
    dims: usize,
    seed: f32,
}

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

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

    fn name(&self) -> &'static str {
        "const-vec"
    }
}

struct ConstVecProvider {
    provider_name: String,
    dims: usize,
    seed: f32,
}

impl ConstVecProvider {
    fn new(name: &str, dims: usize, seed: f32) -> Self {
        Self {
            provider_name: name.to_owned(),
            dims,
            seed,
        }
    }
}

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

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

    async fn build(&self) -> Result<Arc<dyn EmbeddingService>, khive_runtime::RuntimeError> {
        Ok(Arc::new(ConstVecService {
            dims: self.dims,
            seed: self.seed,
        }))
    }
}

/// PR #444 regression: a runtime with no lattice
/// `embedding_model` in config but a custom registered embedder must fan out
/// `remember` through that embedder and store a vector.
///
/// Previously the fan-out gate checked `config().embedding_model.is_some()`;
/// custom-only runtimes fell through to `vec![]`.
#[tokio::test]
async fn test_custom_embedder_only_runtime_fanout_remember_recall() {
    const MODEL_A: &str = "custom-enc-a";
    const DIMS: usize = 4;

    // Runtime with no lattice model, only a custom embedder.
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        ..RuntimeConfig::default()
    })
    .expect("runtime");
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.9));

    assert!(rt.config().embedding_model.is_none());
    assert!(
        rt.registered_embedding_model_names()
            .contains(&MODEL_A.to_string()),
        "custom embedder must be in registry"
    );

    let registry = make_registry(rt.clone());

    // remember — must not fail even with no lattice model.
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "custom embedder fanout regression test content alpha",
                "salience": 0.8
            }),
        )
        .await
        .expect("remember with custom-only embedder must succeed");

    let note_id = result["id"].as_str().expect("note_id present");
    assert!(!note_id.is_empty());

    // recall — custom embedder must have participated: at least the text path
    // should return the note.
    let recall_result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "custom embedder fanout regression" }),
        )
        .await
        .expect("recall after custom-embedder remember");

    let hits = recall_result.as_array().expect("array");
    let ids: Vec<&str> = hits.iter().map(|h| h["id"].as_str().unwrap()).collect();
    assert!(
        ids.contains(&note_id),
        "recall must find the note created via custom embedder; got: {ids:?}"
    );
}

/// PR #444 regression: Weighted fusion with N > 1
/// vector models must not zero-weight the text source.
///
/// Previously `fuse_candidates` passed [vec_a, vec_b, text] as 3 sources to
/// `fuse_search_results(Weighted)`.  `normalized_weights()` returns exactly 2
/// weights; sources beyond index 1 received weight 0.0, silently dropping text.
///
/// After the fix, N > 1 vector sources are Union-combined into one before
/// passing [combined_vector, text] — preserving the 2-source Weighted contract.
///
/// This test verifies that a memory created with two registered embedders is
/// returned by recall under the Weighted strategy (text contributes).
#[tokio::test]
async fn test_weighted_fusion_multi_model_text_not_zeroed() {
    const MODEL_A: &str = "enc-model-a";
    const MODEL_B: &str = "enc-model-b";
    const DIMS: usize = 4;

    // Runtime with two custom embedders and no lattice model.
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        ..RuntimeConfig::default()
    })
    .expect("runtime");
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.5));
    rt.register_embedder(ConstVecProvider::new(MODEL_B, DIMS, 0.6));

    assert_eq!(rt.registered_embedding_model_names().len(), 2);

    let registry = make_registry(rt.clone());

    // Store a memory with distinctive text content.
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "weighted fusion multi model text contribution regression beta",
                "salience": 0.7
            }),
        )
        .await
        .expect("remember with two custom embedders");

    let note_id = result["id"].as_str().expect("note_id");

    // Recall with explicit Weighted strategy — text must not be zeroed.
    let recall = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "weighted fusion multi model text",
                "fusion_strategy": "weighted",
                "limit": 10
            }),
        )
        .await
        .expect("recall with weighted fusion and 2 vector models");

    let hits = recall.as_array().expect("array");
    let ids: Vec<&str> = hits.iter().map(|h| h["id"].as_str().unwrap()).collect();
    assert!(
        ids.contains(&note_id),
        "weighted fusion with N>1 vector models must not zero-weight text — \
         note {note_id} must appear in results; got: {ids:?}"
    );
}

// ── Wave-2 regression tests (M-C1..M-C4) ──────────────────────────────────────

/// M-C1: memory_type="procedural" must be rejected with a clear error listing
/// the valid values ("episodic" | "semantic").
#[tokio::test]
async fn test_remember_procedural_memory_type_rejected() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "procedural memory of how to deploy",
                "memory_type": "procedural"
            }),
        )
        .await;

    assert!(
        result.is_err(),
        "memory_type='procedural' must be rejected; got ok: {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("episodic") && msg.contains("semantic"),
        "error must list valid memory_type values (episodic, semantic); got: {msg}"
    );
}

/// M-C1: recall with memory_type="procedural" must also be rejected.
#[tokio::test]
async fn test_recall_procedural_memory_type_filter_rejected() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "deploy procedure",
                "memory_type": "procedural"
            }),
        )
        .await;

    assert!(
        result.is_err(),
        "recall with memory_type='procedural' must be rejected; got ok: {result:?}"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("episodic") && msg.contains("semantic"),
        "error must list valid memory_type values; got: {msg}"
    );
}

/// M-C3: composite scores returned by recall are always in [0, 1].
///
/// Verifies that the final_score is bounded regardless of fusion strategy.
/// Specifically, after normalize_relevance + weighted combination, scores must
/// not exceed 1.0.
#[tokio::test]
async fn test_recall_composite_score_bounded_to_unit_interval() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    // Store several memories to exercise the scoring path.
    for i in 0..5 {
        registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("bounded score test memory number {i}"),
                    "salience": 0.5 + 0.1 * (i as f64),
                    "decay_factor": 0.0,
                }),
            )
            .await
            .expect("memory.remember");
    }

    let result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "bounded score test memory", "limit": 10 }),
        )
        .await
        .expect("recall succeeds");

    let hits = result.as_array().expect("array of hits");
    assert!(!hits.is_empty(), "must have hits for bounded score test");

    for hit in hits {
        let score = hit["score"].as_f64().expect("hit has score");
        assert!(
            (0.0..=1.0).contains(&score),
            "composite score must be in [0, 1]; got {score}. \
             If score > 1.0, normalize_relevance or weighted combination is broken."
        );
    }
}

/// M-C3: HandlerDef description for min_score must not claim a fixed 0.0-1.0 range
/// without the qualification that it applies to the composite (not raw fusion) score.
#[test]
fn test_handler_def_min_score_description_clarified() {
    use khive_types::Pack;

    let recall_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.recall")
        .expect("recall handler must be registered");

    let min_score_param = recall_def
        .params
        .iter()
        .find(|p| p.name == "min_score")
        .expect("min_score param must exist");

    // The description must NOT just say "0.0–1.0" without qualification —
    // it must mention "composite" so callers understand the score applies to
    // the final weighted output, not the raw FTS/vector fusion score.
    assert!(
        min_score_param.description.contains("composite")
            || min_score_param.description.contains("[0,1]"),
        "min_score description must clarify the score is composite/[0,1]; got: {:?}",
        min_score_param.description
    );
}

/// M-C1: HandlerDef description for remember.memory_type must list exact valid values.
#[test]
fn test_handler_def_remember_memory_type_description_lists_valid_values() {
    use khive_types::Pack;

    let remember_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.remember")
        .expect("remember handler must be registered");

    let mt_param = remember_def
        .params
        .iter()
        .find(|p| p.name == "memory_type")
        .expect("memory_type param must exist");

    // Must list both valid values explicitly so help text is accurate.
    assert!(
        mt_param.description.contains("episodic") && mt_param.description.contains("semantic"),
        "memory_type description must list valid values 'episodic' and 'semantic'; got: {:?}",
        mt_param.description
    );
    // Must indicate these are the only valid values (not just examples).
    assert!(
        !mt_param.description.contains("e.g."),
        "memory_type description must not use 'e.g.' — values are exhaustive; got: {:?}",
        mt_param.description
    );
}

// Issue #288: recall text_candidates must be non-empty when the query partially
// matches a memory note. Previously the conjunction Plain MATCH returned zero
// candidates if the note only contained some of the query terms.
#[tokio::test]
async fn recall_candidates_text_candidates_non_empty_for_partial_match() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create a memory note whose content matches only the first two words of the query.
    registry
        .dispatch(
            "memory.remember",
            serde_json::json!({
                "content": "attention mechanism in neural networks",
                "salience": 0.9,
                "memory_type": "semantic"
            }),
        )
        .await
        .expect("remember succeeds");

    // The query contains the note's terms plus extras the note doesn't have.
    let result = registry
        .dispatch(
            "memory.recall_candidates",
            serde_json::json!({
                "query": "attention mechanism transformers deep learning architecture"
            }),
        )
        .await
        .expect("recall_candidates succeeds");

    let text_candidates = result["text_candidates"]
        .as_array()
        .expect("text_candidates is array");

    assert!(
        !text_candidates.is_empty(),
        "text_candidates must be non-empty when a memory note partially matches the query; \
         got empty array. Query fanout is likely not working."
    );

    // All returned text candidates must be memory-kind notes.
    for tc in text_candidates {
        let note_id = tc["id"].as_str().expect("note_id present");
        assert!(
            !note_id.is_empty(),
            "text_candidate note_id must be non-empty"
        );
    }
}

// Issue #482: recall include_breakdown=true must include per-component breakdown.
// presentation= was removed in #514 and is now rejected by deny_unknown_fields.
#[tokio::test]
async fn recall_include_breakdown_true_includes_breakdown() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    registry
        .dispatch(
            "memory.remember",
            serde_json::json!({ "content": "breakdown test memory", "salience": 0.8 }),
        )
        .await
        .expect("remember succeeds");

    let result = registry
        .dispatch(
            "memory.recall",
            serde_json::json!({ "query": "breakdown test memory", "include_breakdown": true }),
        )
        .await
        .expect("recall with include_breakdown=true succeeds");

    let hits = result.as_array().expect("array of hits");
    assert!(!hits.is_empty(), "recall returned results");
    assert!(
        hits[0].get("breakdown").is_some(),
        "include_breakdown=true must include 'breakdown' in results"
    );
}

#[tokio::test]
async fn recall_default_omits_breakdown() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    registry
        .dispatch(
            "memory.remember",
            serde_json::json!({ "content": "no breakdown memory", "salience": 0.8 }),
        )
        .await
        .expect("remember succeeds");

    let result = registry
        .dispatch(
            "memory.recall",
            serde_json::json!({ "query": "no breakdown memory" }),
        )
        .await
        .expect("recall without include_breakdown succeeds");

    let hits = result.as_array().expect("array of hits");
    if !hits.is_empty() {
        assert!(
            hits[0].get("breakdown").is_none(),
            "default recall must not include 'breakdown' in results"
        );
    }
}

#[tokio::test]
async fn recall_handler_metadata_advertises_include_breakdown_not_presentation() {
    let recall_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.recall")
        .expect("memory.recall handler must be registered");

    let has_include_breakdown = recall_def
        .params
        .iter()
        .any(|p| p.name == "include_breakdown");
    assert!(
        has_include_breakdown,
        "memory.recall must advertise include_breakdown param in metadata"
    );

    // presentation must no longer be advertised as a public param.
    let has_presentation = recall_def.params.iter().any(|p| p.name == "presentation");
    assert!(
        !has_presentation,
        "memory.recall must not advertise verb-level 'presentation' param to avoid ambiguity with MCP envelope"
    );
}

// Issue #277: search(kind="memory") must resolve when memory pack is loaded.
// The KG resolver is registry-driven: memory kind only appears in all_note_kinds()
// when MemoryPack is registered alongside KgPack. Without it the verb rejects
// "memory" as an unknown kind.
#[tokio::test]
async fn search_kind_memory_resolves_when_memory_pack_loaded() {
    let registry = make_registry(make_runtime());

    assert!(
        registry.all_note_kinds().contains(&"memory"),
        "registry.all_note_kinds() must include \"memory\" when memory pack is loaded; got: {:?}",
        registry.all_note_kinds()
    );

    // search(kind="memory") must succeed — previously failed with "unknown kind".
    let result = registry
        .dispatch(
            "search",
            serde_json::json!({ "kind": "memory", "query": "test" }),
        )
        .await;
    assert!(
        result.is_ok(),
        "search(kind=\"memory\") must succeed when memory pack is loaded; got: {:?}",
        result.err()
    );
}

// ── #515: tag-filtered recall ─────────────────────────────────────────────────

/// #515: tag filter — OR (any), AND (all), and no-filter behaviors.
#[tokio::test]
async fn recall_tags_filter_any_all_and_no_filter() {
    let registry = make_registry(make_runtime());

    // Store three memories with distinct tag combos.
    let impl_khive = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "tag filter regression shared semantic target alpha",
                "salience": 0.9,
                "tags": ["role:implementer", "khive"]
            }),
        )
        .await
        .expect("remember impl khive");
    let impl_khive_id = impl_khive["id"].as_str().unwrap().to_owned();

    let critic_khive = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "tag filter regression shared semantic target beta",
                "salience": 0.9,
                "tags": ["role:critic", "khive"]
            }),
        )
        .await
        .expect("remember critic khive");
    let critic_khive_id = critic_khive["id"].as_str().unwrap().to_owned();

    let impl_rust = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "tag filter regression shared semantic target gamma",
                "salience": 0.9,
                "tags": ["role:implementer", "rust"]
            }),
        )
        .await
        .expect("remember impl rust");
    let impl_rust_id = impl_rust["id"].as_str().unwrap().to_owned();

    // no-filter: all three should appear.
    let no_filter = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "tag filter regression shared semantic target", "limit": 20 }),
        )
        .await
        .expect("recall no filter");
    let no_filter_ids: Vec<&str> = no_filter
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|h| h["id"].as_str())
        .collect();
    assert!(
        no_filter_ids.contains(&impl_khive_id.as_str()),
        "no-filter must return impl+khive memory"
    );
    assert!(
        no_filter_ids.contains(&critic_khive_id.as_str()),
        "no-filter must return critic+khive memory"
    );
    assert!(
        no_filter_ids.contains(&impl_rust_id.as_str()),
        "no-filter must return impl+rust memory"
    );

    // any (OR): tags=["role:critic", "rust"] → critic_khive and impl_rust, not impl_khive.
    let any_result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "tag filter regression shared semantic target",
                "limit": 20,
                "tags": ["role:critic", "rust"],
                "tag_mode": "any"
            }),
        )
        .await
        .expect("recall tag any");
    let any_ids: Vec<&str> = any_result
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|h| h["id"].as_str())
        .collect();
    assert!(
        any_ids.contains(&critic_khive_id.as_str()),
        "any filter must include critic+khive (has role:critic)"
    );
    assert!(
        any_ids.contains(&impl_rust_id.as_str()),
        "any filter must include impl+rust (has rust)"
    );
    assert!(
        !any_ids.contains(&impl_khive_id.as_str()),
        "any filter must exclude impl+khive (has neither role:critic nor rust)"
    );

    // all (AND): tags=["role:implementer", "khive"] → impl_khive only.
    let all_result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "tag filter regression shared semantic target",
                "limit": 20,
                "tags": ["role:implementer", "khive"],
                "tag_mode": "all"
            }),
        )
        .await
        .expect("recall tag all");
    let all_ids: Vec<&str> = all_result
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|h| h["id"].as_str())
        .collect();
    assert!(
        all_ids.contains(&impl_khive_id.as_str()),
        "all filter must include impl+khive (has both role:implementer and khive)"
    );
    assert!(
        !all_ids.contains(&critic_khive_id.as_str()),
        "all filter must exclude critic+khive (missing role:implementer)"
    );
    assert!(
        !all_ids.contains(&impl_rust_id.as_str()),
        "all filter must exclude impl+rust (missing khive)"
    );
}

/// B7: raw_score must be present (possibly null) in every result returned by
/// memory.recall, including when tag filters narrow the result set with tag_mode="all".
/// The field is null for text-only hits (no vector index) and a float for vector hits.
#[tokio::test]
async fn recall_raw_score_field_always_present_with_tag_filter() {
    let registry = make_registry(make_runtime());

    registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "raw score presence check alpha beta gamma delta epsilon",
                "salience": 0.9,
                "tags": ["team:alpha", "project:khive"]
            }),
        )
        .await
        .expect("remember tagged memory");

    registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "raw score presence check alpha beta gamma delta epsilon",
                "salience": 0.9,
                "tags": ["team:alpha", "project:khive"]
            }),
        )
        .await
        .expect("remember second tagged memory");

    for tag_mode in &["any", "all"] {
        let result = registry
            .dispatch(
                "memory.recall",
                json!({
                    "query": "raw score presence check alpha beta gamma",
                    "limit": 20,
                    "tags": ["team:alpha", "project:khive"],
                    "tag_mode": tag_mode
                }),
            )
            .await
            .unwrap_or_else(|e| panic!("recall tag_mode={tag_mode} failed: {e}"));

        let hits = result.as_array().expect("results must be an array");
        assert!(
            !hits.is_empty(),
            "tag_mode={tag_mode}: expected at least one result"
        );
        for (i, hit) in hits.iter().enumerate() {
            let obj = hit.as_object().expect("each hit must be a JSON object");
            assert!(
                obj.contains_key("raw_score"),
                "tag_mode={tag_mode} result[{i}] missing raw_score field; got keys: {:?}",
                obj.keys().collect::<Vec<_>>()
            );
        }
    }
}

/// #515 metadata: memory.recall handler must advertise tags and tag_mode params.
#[test]
fn recall_handler_metadata_advertises_tags_and_tag_mode() {
    let recall_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.recall")
        .expect("memory.recall handler must be registered");

    let param_names: Vec<&str> = recall_def.params.iter().map(|p| p.name).collect();
    assert!(
        param_names.contains(&"tags"),
        "memory.recall must advertise 'tags' param; got: {param_names:?}"
    );
    assert!(
        param_names.contains(&"tag_mode"),
        "memory.recall must advertise 'tag_mode' param; got: {param_names:?}"
    );
}

// ── #566: recall_embed vectors opt-in ────────────────────────────────────────

/// #566: default recall_embed omits embedding vectors, keeps model+dimension metadata.
#[tokio::test]
async fn recall_embed_default_omits_embedding_vectors() {
    const MODEL_A: &str = "embed-a";
    const DIMS: usize = 4;

    let rt = make_runtime();
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.7));
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.recall_embed",
            json!({ "query": "embedding metadata only" }),
        )
        .await
        .expect("recall_embed default");

    // Top-level embedding array must be absent.
    assert!(
        result.get("embedding").is_none(),
        "default recall_embed must not include top-level embedding; got: {result}"
    );
    // Dimension metadata must still be present.
    assert_eq!(
        result["dimensions"].as_u64(),
        Some(DIMS as u64),
        "dimensions must be returned even without embeddings"
    );
    // Per-engine entry must have model and dimensions but no embedding array.
    let engines = result["engines"].as_array().expect("engines array");
    assert_eq!(engines.len(), 1);
    assert_eq!(engines[0]["model"].as_str(), Some(MODEL_A));
    assert_eq!(engines[0]["dimensions"].as_u64(), Some(DIMS as u64));
    assert!(
        engines[0].get("embedding").is_none(),
        "default recall_embed must not include per-engine embedding; got: {}",
        engines[0]
    );
}

/// #566: include_embeddings=true returns full vector payload.
#[tokio::test]
async fn recall_embed_include_embeddings_returns_vectors() {
    const MODEL_A: &str = "embed-a";
    const DIMS: usize = 4;

    let rt = make_runtime();
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.7));
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.recall_embed",
            json!({ "query": "embedding full payload", "include_embeddings": true }),
        )
        .await
        .expect("recall_embed include embeddings");

    // Top-level embedding array must be present.
    let top_vec = result["embedding"]
        .as_array()
        .expect("top-level embedding array");
    assert_eq!(
        top_vec.len(),
        DIMS,
        "top-level embedding length must match dims"
    );
    // Per-engine embedding also present.
    let engines = result["engines"].as_array().expect("engines array");
    assert_eq!(engines.len(), 1);
    let engine_vec = engines[0]["embedding"]
        .as_array()
        .expect("per-engine embedding array");
    assert_eq!(
        engine_vec.len(),
        DIMS,
        "per-engine embedding length must match dims"
    );
}

/// #566 metadata: memory.recall_embed handler must advertise include_embeddings param.
#[test]
fn recall_embed_handler_metadata_advertises_include_embeddings() {
    let embed_def = khive_pack_memory::MemoryPack::HANDLERS
        .iter()
        .find(|h| h.name == "memory.recall_embed")
        .expect("memory.recall_embed handler must be registered");

    let param_names: Vec<&str> = embed_def.params.iter().map(|p| p.name).collect();
    assert!(
        param_names.contains(&"include_embeddings"),
        "memory.recall_embed must advertise 'include_embeddings' param; got: {param_names:?}"
    );
}

// ── Type-differentiated default tests — production path (#84) ───────────────
//
// These tests dispatch through the real handler and assert stored note values
// (via the response) for the omitted/explicit default matrix.  A revert of the
// production defaults in remember.rs would cause these to fail.

/// Omitting salience and decay_factor for an episodic memory must store 0.3 / 0.02.
#[tokio::test]
async fn test_remember_episodic_defaults_stored() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "episodic default test", "memory_type": "episodic" }),
        )
        .await
        .expect("memory.remember must succeed");

    let salience = result["salience"].as_f64().expect("salience field present");
    let decay = result["decay_factor"]
        .as_f64()
        .expect("decay_factor field present");
    assert!(
        (salience - 0.3).abs() < 1e-12,
        "episodic default salience must be 0.3, got {salience}"
    );
    assert!(
        (decay - 0.02).abs() < 1e-12,
        "episodic default decay_factor must be 0.02, got {decay}"
    );
}

/// Omitting memory_type defaults to episodic and applies episodic defaults.
#[tokio::test]
async fn test_remember_omitted_memory_type_uses_episodic_defaults() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "no memory_type supplied" }),
        )
        .await
        .expect("memory.remember must succeed");

    let mt = result["memory_type"].as_str().expect("memory_type present");
    assert_eq!(
        mt, "episodic",
        "omitted memory_type must default to episodic"
    );
    let salience = result["salience"].as_f64().expect("salience present");
    let decay = result["decay_factor"]
        .as_f64()
        .expect("decay_factor present");
    assert!(
        (salience - 0.3).abs() < 1e-12,
        "omitted-type default salience must be 0.3, got {salience}"
    );
    assert!(
        (decay - 0.02).abs() < 1e-12,
        "omitted-type default decay_factor must be 0.02, got {decay}"
    );
}

/// Omitting salience and decay_factor for a semantic memory must store 0.5 / 0.005.
#[tokio::test]
async fn test_remember_semantic_defaults_stored() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "semantic default test", "memory_type": "semantic" }),
        )
        .await
        .expect("memory.remember must succeed");

    let salience = result["salience"].as_f64().expect("salience present");
    let decay = result["decay_factor"]
        .as_f64()
        .expect("decay_factor present");
    assert!(
        (salience - 0.5).abs() < 1e-12,
        "semantic default salience must be 0.5, got {salience}"
    );
    assert!(
        (decay - 0.005).abs() < 1e-12,
        "semantic default decay_factor must be 0.005, got {decay}"
    );
}

/// Explicit salience=0.5 with episodic type must store exactly 0.5 (old flat default wins explicitly).
#[tokio::test]
async fn test_remember_explicit_salience_overrides_episodic_default() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "explicit salience test", "memory_type": "episodic", "salience": 0.5 }),
        )
        .await
        .expect("memory.remember must succeed");

    let salience = result["salience"].as_f64().expect("salience present");
    assert!(
        (salience - 0.5).abs() < 1e-12,
        "explicit salience=0.5 must be stored as-is, not replaced by episodic default 0.3; got {salience}"
    );
}

/// Explicit decay_factor=0.01 with episodic type must store exactly 0.01.
#[tokio::test]
async fn test_remember_explicit_decay_overrides_episodic_default() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch(
            "memory.remember",
            json!({ "content": "explicit decay test", "memory_type": "episodic", "decay_factor": 0.01 }),
        )
        .await
        .expect("memory.remember must succeed");

    let decay = result["decay_factor"]
        .as_f64()
        .expect("decay_factor present");
    assert!(
        (decay - 0.01).abs() < 1e-12,
        "explicit decay_factor=0.01 must be stored as-is, not replaced by episodic default 0.02; got {decay}"
    );
}

/// Legacy note (created via KG create_note with no properties.memory_type, no salience,
/// no decay_factor) must be returned by memory.recall(memory_type="episodic") because
/// the resolved memory_type defaults to "episodic" when no stored value is present.
#[tokio::test]
async fn test_recall_legacy_note_no_memory_type_returned_as_episodic() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create a bare memory note with no properties.memory_type, no salience, no decay —
    // simulates a note written before the type-differentiated defaults PR.
    let tok = rt.authorize(Namespace::local()).unwrap();
    let legacy_note = rt
        .create_note(
            &tok,
            "memory",
            None,
            "legacy note about transformer attention heads no memory type",
            None,   // no salience
            None,   // no properties (therefore no memory_type)
            vec![], // no annotates edges
        )
        .await
        .expect("create legacy note");
    let legacy_id = legacy_note.id.to_string();

    // recall with explicit memory_type="episodic" must include the legacy note because
    // resolved memory_type defaults to "episodic" when properties.memory_type is absent.
    let result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "transformer attention heads no memory type",
                "memory_type": "episodic",
                "limit": 10
            }),
        )
        .await
        .expect("memory.recall must succeed");

    let hits = result.as_array().expect("recall returns array");
    let returned_ids: Vec<&str> = hits
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        returned_ids.contains(&legacy_id.as_str()),
        "legacy note with no stored memory_type must appear in recall(memory_type=\"episodic\"); \
         returned ids: {returned_ids:?}"
    );

    // Recall hits must carry resolved (read-model) values, not raw stored NULLs.
    // Consumers such as ranking explanations and brain.auto_feedback rely on these fields.
    let legacy_hit = hits
        .iter()
        .find(|h| h["id"].as_str().unwrap_or("") == legacy_id)
        .expect("legacy hit present");

    let hit_memory_type = legacy_hit["memory_type"]
        .as_str()
        .expect("memory_type field present in hit");
    assert_eq!(
        hit_memory_type, "episodic",
        "recall hit memory_type must be resolved to \"episodic\" for legacy note; got {hit_memory_type:?}"
    );

    let hit_salience = legacy_hit["salience"]
        .as_f64()
        .expect("salience field present in hit");
    assert!(
        (hit_salience - 0.3).abs() < 1e-12,
        "recall hit salience must be episodic default 0.3 for legacy note; got {hit_salience}"
    );

    let hit_decay = legacy_hit["decay_factor"]
        .as_f64()
        .expect("decay_factor field present in hit");
    assert!(
        (hit_decay - 0.02).abs() < 1e-12,
        "recall hit decay_factor must be episodic default 0.02 for legacy note; got {hit_decay}"
    );
}

// ── Regression tests for issue #94: token-budget truncation signal + rank order ──

/// #94 regression (budget cap): when the token budget caps the returned count below
/// the requested `limit`, fewer results than `limit` are returned.
///
/// The non-verbose path always returns a bare array; the budget-capped status is
/// observable as a count < limit.  Budget signal fields (`budget_capped`,
/// `truncated_for_budget`) are available on the verbose/breakdown path when the
/// runtime loads two or more embedding models (multi-model production setup).
#[tokio::test]
async fn test_recall_budget_capped_surfaces_signal() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Create 5 notes whose content is long enough that the tiny budget below
    // cannot accommodate all of them.  Each note content is ~75 chars.
    let shared_query = "budget signal regression unique phrase alpha";
    for i in 0..5_u8 {
        let content =
            format!("budget signal regression unique phrase alpha memory content item number {i}");
        registry
            .dispatch(
                "memory.remember",
                json!({ "content": content, "salience": 0.8 }),
            )
            .await
            .expect("remember");
    }

    // default_token_budget=20 tokens × chars_per_token=4 = 80 chars budget.
    // Each note is ~75 chars; only 1 fits; the remaining 4 are dropped by the prefix cut.
    let result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": shared_query,
                "limit": 5,
                "config": {
                    "scoring": {
                        "default_token_budget": 20,
                        "chars_per_token": 4,
                        "mmr_penalty": 0.0
                    }
                }
            }),
        )
        .await
        .expect("recall with tiny budget succeeds");

    // Non-verbose path always returns a bare array regardless of budget state.
    let returned = result
        .as_array()
        .expect("#94: recall must return a bare array on the non-verbose path");
    assert!(
        !returned.is_empty(),
        "#94: at least one result must fit within the budget"
    );
    assert!(
        returned.len() < 5,
        "#94: returned count ({}) must be < requested limit (5) when budget is exhausted; \
         prefix-cut is not working if all 5 fit in an 80-char budget",
        returned.len()
    );
}

/// #94 regression (no false positive): when all results fit within the token budget,
/// the response is a plain array with count equal to available results.
#[tokio::test]
async fn test_recall_no_budget_cap_returns_plain_array() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    registry
        .dispatch(
            "memory.remember",
            json!({ "content": "plain array uncapped recall test phrase", "salience": 0.7 }),
        )
        .await
        .expect("remember");

    // Large budget: 4000 tokens × 4 chars = 16 000 chars — one short note trivially fits.
    let result = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "plain array uncapped recall test", "limit": 3 }),
        )
        .await
        .expect("recall with generous budget succeeds");

    assert!(
        result.is_array(),
        "#94 no-cap path: recall must return a plain array; got: {result}"
    );
}

/// #94 regression (rank order): when the token budget forces truncation, the
/// returned items must be the top-ranked contiguous prefix — no higher-ranked
/// item may be skipped to accommodate a shorter lower-ranked item.
///
/// Setup uses THREE notes with DIFFERENT content lengths so the old greedy
/// `retain` bug actually fires:
///   rank #1 — short content (~55 chars) — fits within the 80-char budget
///   rank #2 — long content (~110 chars) — overflows the remaining budget after #1
///   rank #3 — short content (~55 chars) — would fit if reached by old retain
///
/// With the fix (prefix cut): result = [#1] — #2 overflows → cut, #3 never reached.
/// With the old retain bug:    result = [#1, #3] — #2 skipped, #3 kept (rank violation).
///
/// Assert: exactly 1 result returned AND it is rank #1 AND rank #3 is absent.
#[tokio::test]
async fn test_recall_budget_truncation_preserves_rank_order() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Shared keyword prefix so all 3 notes score on the same query.
    // Unique distinguishing suffix per note controls both length and identity.
    let query = "rankorder prefix budget truncation";

    // rank #1: short — fits in 80-char budget (~55 chars with prefix).
    let content_rank1 = format!("{query} item short alpha unique");
    // rank #2: long — overflows the remaining budget after rank #1.
    // budget = 80 chars; rank #1 uses ~55 chars; remaining = ~25 chars.
    // rank #2 must exceed 25 chars — pad to ~110 chars total.
    let content_rank2 = format!("{query} item long beta {}", "x".repeat(50));
    // rank #3: short — would fit if the old retain reached it.
    let content_rank3 = format!("{query} item short gamma unique");

    // Salience drives rank: 0.9 → rank #1, 0.6 → rank #2, 0.3 → rank #3.
    // mmr_penalty=0 prevents diversity suppression from reordering.
    let notes = [
        (&content_rank1, 0.9_f64),
        (&content_rank2, 0.6_f64),
        (&content_rank3, 0.3_f64),
    ];
    let mut stored_ids = Vec::new();
    for (content, sal) in &notes {
        let res = registry
            .dispatch(
                "memory.remember",
                json!({ "content": content, "salience": sal }),
            )
            .await
            .expect("remember");
        stored_ids.push(res["id"].as_str().unwrap().to_owned());
    }
    let id_rank1 = &stored_ids[0];
    let id_rank3 = &stored_ids[2];

    // budget = 20 tokens × 4 chars = 80 chars.
    // rank #1 (~55 chars) admitted. rank #2 (~110 chars) pushes total to ~165 > 80 → cut.
    // rank #3 is never considered (prefix cut stops at rank #2 overflow).
    let result = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": query,
                "limit": 3,
                "config": {
                    "scoring": {
                        "default_token_budget": 20,
                        "chars_per_token": 4,
                        "mmr_penalty": 0.0
                    }
                }
            }),
        )
        .await
        .expect("recall with rank-order budget test");

    // Non-verbose path returns a bare array.
    let returned = result
        .as_array()
        .expect("#94 rank-order: recall must return a bare array");

    // Exactly 1 result (rank #1 fits, prefix cut stops at rank #2 overflow).
    // Old retain would return 2 results: [rank#1, rank#3].
    assert_eq!(
        returned.len(),
        1,
        "#94 rank-order: exactly 1 result expected (rank #1 fits, rank #2 overflows, \
         rank #3 must not be reached); got {} — old retain bug returns [#1,#3]",
        returned.len()
    );

    let returned_id = returned[0]["id"].as_str().expect("note_id present");
    assert_eq!(
        returned_id, id_rank1,
        "#94 rank-order: the single returned note must be rank #1 ({id_rank1}), got {returned_id}"
    );

    // rank #3 must not appear — its presence is the rank-skip signature.
    let has_rank3 = returned.iter().any(|r| r["id"].as_str() == Some(id_rank3));
    assert!(
        !has_rank3,
        "#94 rank-order: rank #3 ({id_rank3}) must NOT be in results — \
         its presence proves the old greedy retain was used instead of the prefix cut"
    );
}

// =============================================================================
// ADR-007 Rev 4 regression tests — additive read visible-set
// =============================================================================

/// (b) Writes stamp the local namespace even when actor.id = "lambda:khive".
///
/// A `memory.remember` dispatched with no explicit `namespace=` param must
/// produce a note with `namespace == "local"`. Actor identity must not route
/// storage writes.
#[tokio::test]
async fn adr007_rev4_writes_stamp_local() {
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        // No real embedder: this test exercises namespace scoping, not embedding.
        // The CI runner has no model files, so loading one would fail (see a/a2).
        embedding_model: None,
        additional_embedding_models: vec![],
        visible_namespaces: vec![Namespace::parse("lambda:khive").unwrap()],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");

    let mut builder = VerbRegistryBuilder::new();
    builder.with_visible_namespaces(rt.config().visible_namespaces.clone());
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let registry = builder.build().expect("registry builds");

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "adr007 rev4 write test — must land in local",
                "memory_type": "semantic",
                "salience": 0.6
            }),
        )
        .await
        .expect("memory.remember must succeed");

    let note_id = result["id"].as_str().expect("note id present");
    let tok_local = rt.authorize(Namespace::local()).expect("authorize local");
    let note = rt
        .get_note_including_deleted(&tok_local, Uuid::parse_str(note_id).unwrap())
        .await
        .expect("get must succeed")
        .expect("note must exist in local");
    assert_eq!(
        note.namespace, "local",
        "write must stamp local, not actor namespace; got: {}",
        note.namespace
    );
}

/// (c) No actor configured → default visible-set is exactly {local}.
///
/// A registry built with no visible_namespaces must NOT surface notes written
/// to a foreign namespace via default-path recall.
#[tokio::test]
async fn adr007_rev4_no_actor_yields_local_only_visible_set() {
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        // No real embedder: scoping test, FTS recall only (see a/a2). CI has no model files.
        embedding_model: None,
        additional_embedding_models: vec![],
        // no visible_namespaces — same as Rev 3 behavior
        visible_namespaces: vec![],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");

    // Write a note directly into the foreign namespace.
    let tok_foreign = rt
        .authorize(Namespace::parse("ns-foreign-c").unwrap())
        .expect("authorize foreign");
    rt.create_note(
        &tok_foreign,
        "memory",
        None,
        "adr007-c-foreign-content-unique-marker",
        None,
        None,
        vec![],
    )
    .await
    .expect("create note in foreign ns");

    // Build the registry with no visible_namespaces (zero actor extras).
    let mut builder = VerbRegistryBuilder::new();
    // deliberately NOT calling with_visible_namespaces
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let registry = builder.build().expect("registry builds");

    // Default recall must NOT surface the foreign note.
    let hits = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "adr007-c-foreign-content-unique-marker" }),
        )
        .await
        .expect("memory.recall must succeed");
    let hits = hits.as_array().expect("recall returns array");
    let foreign_visible = hits.iter().any(|h| {
        h["content"]
            .as_str()
            .unwrap_or("")
            .contains("adr007-c-foreign-content-unique-marker")
    });
    assert!(
        !foreign_visible,
        "no-actor config: foreign-namespace note must NOT appear in default recall (visible-set={{local}} only)"
    );
}

/// (d) Explicit namespace= is strict — Reading 2 regression guard.
///
/// When `namespace="lambda:khive"` is passed explicitly, the result set must
/// be EXACTLY that namespace. A note written to `local` must NOT appear in the
/// results (the explicit param is not widened by visible_namespaces).
#[tokio::test]
async fn adr007_rev4_explicit_namespace_is_strict_reading2() {
    const MODEL_A: &str = "custom-enc-a";
    const DIMS: usize = 4;

    // No real model (CI has no model files); a ConstVecProvider drives the vector leg
    // instead. The constant vector is identical across notes, so the local note WOULD
    // surface if the explicit namespace= weren't strict — making this a sharp Reading-2
    // guard rather than relying on FTS lexical luck for the hyphenated marker query.
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        visible_namespaces: vec![Namespace::parse("lambda:khive").unwrap()],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.9));

    // Write a note to local (default path — no explicit namespace).
    let tok_local = rt.authorize(Namespace::local()).expect("authorize local");
    rt.create_note(
        &tok_local,
        "memory",
        None,
        "adr007-d-local-content-marker",
        None,
        None,
        vec![],
    )
    .await
    .expect("create local note");

    // Write a note to lambda:khive (explicit namespace).
    let tok_lk = rt
        .authorize(Namespace::parse("lambda:khive").unwrap())
        .expect("authorize lambda:khive");
    let lk_note = rt
        .create_note(
            &tok_lk,
            "memory",
            None,
            "adr007-d-lambdakhive-content-marker",
            None,
            None,
            vec![],
        )
        .await
        .expect("create lambda:khive note");

    let mut builder = VerbRegistryBuilder::new();
    builder.with_visible_namespaces(rt.config().visible_namespaces.clone());
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let registry = builder.build().expect("registry builds");

    // Explicit namespace="lambda:khive" → strict {lambda:khive} only.
    // The local note must NOT appear even though visible_namespaces includes it.
    let results = registry
        .dispatch(
            "memory.recall",
            json!({
                "query": "adr007-d",
                "namespace": "lambda:khive"
            }),
        )
        .await
        .expect("recall with explicit namespace must succeed");
    let hits = results.as_array().expect("recall returns array");

    let local_leaked = hits.iter().any(|h| {
        h["content"]
            .as_str()
            .unwrap_or("")
            .contains("adr007-d-local-content-marker")
    });
    assert!(
        !local_leaked,
        "Reading 2 violation: explicit namespace=lambda:khive must NOT return local-namespace notes; \
         visible_namespaces must not widen explicit-namespace escapes"
    );

    let lk_found = hits.iter().any(|h| {
        h["id"].as_str() == Some(&lk_note.id.to_string())
            || h["content"]
                .as_str()
                .unwrap_or("")
                .contains("adr007-d-lambdakhive-content-marker")
    });
    assert!(
        lk_found,
        "explicit namespace=lambda:khive must return the lambda:khive note"
    );
}

/// (e) By-ID get of a lambda:khive-attributed note works namespace-agnostically.
///
/// Rule 2 (shipped PR-A1): get by UUID is globally resolved regardless of token.
/// This test is a regression guard that the Rev 4 changes did not re-introduce
/// any namespace check on the by-ID path.
#[tokio::test]
async fn adr007_rev4_get_byid_is_namespace_agnostic() {
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        // No real embedder: by-ID get needs no embedding (see a/a2). CI has no model files.
        embedding_model: None,
        additional_embedding_models: vec![],
        visible_namespaces: vec![],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");

    // Create a note attributed to lambda:khive.
    let tok_lk = rt
        .authorize(Namespace::parse("lambda:khive").unwrap())
        .expect("authorize lambda:khive");
    let lk_note = rt
        .create_note(
            &tok_lk,
            "memory",
            None,
            "adr007-e-byid-content",
            None,
            None,
            vec![],
        )
        .await
        .expect("create lambda:khive note");

    let mut builder = VerbRegistryBuilder::new();
    // No visible_namespaces — local-only token will be minted by dispatch default.
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let registry = builder.build().expect("registry builds");

    // get by UUID with no namespace= param → must resolve the lambda:khive note.
    let result = registry
        .dispatch("get", json!({ "id": lk_note.id.to_string() }))
        .await
        .expect("get by UUID must succeed regardless of namespace");

    let record = result.get("record").unwrap_or(&result);
    let returned_id = record["id"].as_str().expect("id present in get result");
    assert_eq!(
        returned_id,
        lk_note.id.to_string().as_str(),
        "by-ID get must return the lambda:khive-attributed note (Rule 2 / PR-A1 regression guard)"
    );
}

/// (a) ADR-007 Rev 4: [actor] id=lambda:khive ⇒ default recall surfaces a lambda:khive note via
/// BOTH the FTS leg (5a) and the vector leg (5b, lexically-disjoint query).
///
/// A `KhiveRuntime` with `visible_namespaces = ["lambda:khive"]` and a registered
/// `ConstVecProvider` (so the vector leg is live) writes a note into `lambda:khive`
/// via the Rule-3 explicit-namespace escape, then asserts:
///   5a — default recall with a matching query returns the note (FTS + vector both reachable).
///   5b — default recall with a lexically-disjoint query (no shared trigrams) still returns the
///        note, isolating the vector leg via the `authorize(ns)` fanout.
#[tokio::test]
async fn adr007_rev4_default_recall_surfaces_actor_ns_via_both_legs() {
    const MODEL_A: &str = "custom-enc-a";
    const DIMS: usize = 4;

    // Build a runtime with visible_namespaces = ["lambda:khive"] and a registered
    // ConstVecProvider so the vector leg is live (no lattice model needed).
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        visible_namespaces: vec![Namespace::parse("lambda:khive").unwrap()],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.9));

    // Build the registry with with_visible_namespaces, mirroring tests (b)/(d).
    let mut builder = VerbRegistryBuilder::new();
    builder.with_visible_namespaces(rt.config().visible_namespaces.clone());
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let registry = builder.build().expect("registry builds");

    // Step 3: write the note into lambda:khive via the Rule-3 explicit-namespace escape.
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "alpha beta gamma delta",
                "salience": 0.8,
                "namespace": "lambda:khive"
            }),
        )
        .await
        .expect("memory.remember with explicit namespace must succeed");
    let note_id = result["id"].as_str().expect("note id present").to_owned();
    assert!(!note_id.is_empty());

    // Step 5a: default recall with a query that shares trigrams with the content.
    // Both FTS and vector legs can surface the note here.
    let recall_5a = registry
        .dispatch("memory.recall", json!({ "query": "alpha beta" }))
        .await
        .expect("memory.recall (5a) must succeed");
    let hits_5a = recall_5a.as_array().expect("recall returns array");
    let ids_5a: Vec<&str> = hits_5a
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        ids_5a.contains(&note_id.as_str()),
        "5a: default recall must surface the lambda:khive note (both legs); got: {ids_5a:?}"
    );

    // Step 5b: default recall with a lexically-disjoint query — no shared letters with
    // "alpha beta gamma delta" (content uses a,l,p,h,b,e,t,g,m,d; query uses j,x,w,v,z,r,f,k)
    // so zero shared trigrams. FTS cannot match; only the vector leg can surface the note
    // via the constant-vector ANN index fanned out through authorize("lambda:khive").
    // This isolates the vector-leg fanout as the sole return path.
    let recall_5b = registry
        .dispatch("memory.recall", json!({ "query": "jxwvz qrpfk" }))
        .await
        .expect("memory.recall (5b) must succeed");
    let hits_5b = recall_5b.as_array().expect("recall returns array");
    let ids_5b: Vec<&str> = hits_5b
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        ids_5b.contains(&note_id.as_str()),
        "5b: vector-leg fanout via authorize(lambda:khive) must surface the note \
         even with a lexically-disjoint query (no FTS match possible); got: {ids_5b:?}"
    );
}

/// (a2) ADR-007 Rev 4: FTS-leg isolation — with the vector leg disabled (no embedder),
/// default recall surfaces a lambda:khive note via the FTS fanout alone.
///
/// Builds a `KhiveRuntime` with `embedding_model: None` and registers NO embedder,
/// so the vector leg is dead. Asserts `registered_embedding_model_names()` is empty
/// (self-documenting premise). Dispatches `memory.remember` with
/// `namespace="lambda:khive"` (explicit-param write into that namespace), then
/// `memory.recall` with a lexically matching query and no `namespace=` param.
/// The note id must appear — with the vector leg dead, the ONLY path that can
/// surface it is the FTS fanout (`with_namespace` selecting `fts_notes_lambda:khive`).
#[tokio::test]
async fn adr007_rev4_default_recall_surfaces_actor_ns_via_fts_leg() {
    // Build a runtime with visible_namespaces = ["lambda:khive"] and NO embedder,
    // so the vector leg is dead.
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        visible_namespaces: vec![Namespace::parse("lambda:khive").unwrap()],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");

    // Assert the vector leg is dead — no embedder registered.
    // This makes the test premise self-documenting: if an embedder were registered,
    // the vector leg could carry the result without FTS, and the test would prove nothing.
    assert!(
        rt.registered_embedding_model_names().is_empty(),
        "FTS-leg isolation premise: no embedder must be registered (vector leg must be dead)"
    );

    // Build the registry with with_visible_namespaces mirroring tests (b)/(d).
    let mut builder = VerbRegistryBuilder::new();
    builder.with_visible_namespaces(rt.config().visible_namespaces.clone());
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let registry = builder.build().expect("registry builds");

    // Write the note into lambda:khive via the Rule-3 explicit-namespace escape.
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "alpha beta gamma delta",
                "salience": 0.8,
                "namespace": "lambda:khive"
            }),
        )
        .await
        .expect("memory.remember with explicit namespace must succeed");
    let note_id = result["id"].as_str().expect("note id present").to_owned();
    assert!(!note_id.is_empty());

    // Default recall with a lexically matching query and no namespace= param.
    // With the vector leg dead, the ONLY path that can surface the note is the
    // FTS fanout (with_namespace selecting fts_notes_lambda:khive). This isolates
    // the FTS leg as the sole return path.
    let recall = registry
        .dispatch("memory.recall", json!({ "query": "alpha beta" }))
        .await
        .expect("memory.recall must succeed");
    let hits = recall.as_array().expect("recall returns array");
    let ids: Vec<&str> = hits
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        ids.contains(&note_id.as_str()),
        "FTS-leg: default recall must surface the lambda:khive note via FTS fanout alone \
         (vector leg is dead — no embedder registered); got: {ids:?}"
    );
}

// ── B2 — multi-namespace recall regression (ADR-062 §2 over-fetch + filter) ────

/// B2: ANN over-fetch + namespace post-filter.
///
/// Stores memories in two namespaces (`local` and `other`).  The global ANN index
/// spans both.  Asserts:
///  1. Default recall (visible = [`local`]) excludes `other`-namespace memories.
///  2. A wide token (visible = [`local`, `other`]) includes both namespaces.
///  3. Recall@k is satisfied when ≥k local candidates exist (over-fetch is enough).
///
/// Uses a deterministic custom embedder (no lattice weights required).
#[tokio::test]
async fn test_multi_namespace_recall_overfetch_filter() {
    use khive_runtime::PackRuntime;

    const MODEL: &str = "ns-filter-enc";
    const DIMS: usize = 8;

    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        ..RuntimeConfig::default()
    })
    .expect("runtime");
    rt.register_embedder(ConstVecProvider::new(MODEL, DIMS, 0.42));

    let registry = make_registry(rt.clone());

    // Store 3 memories in `local` namespace.
    let mut local_ids = Vec::new();
    for i in 0..3 {
        let r = registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("local memory entry number {i} about graph databases"),
                    "salience": 0.7,
                    "namespace": "local"
                }),
            )
            .await
            .unwrap_or_else(|e| panic!("local remember {i} failed: {e}"));
        local_ids.push(r["id"].as_str().expect("note_id").to_string());
    }

    // Store 2 memories in `other` namespace.
    let mut other_ids = Vec::new();
    for i in 0..2 {
        let r = registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("other namespace memory {i} about graph databases"),
                    "salience": 0.7,
                    "namespace": "other"
                }),
            )
            .await
            .unwrap_or_else(|e| panic!("other remember {i} failed: {e}"));
        other_ids.push(r["id"].as_str().expect("note_id").to_string());
    }

    // ── Assertion 1: default recall (local-only) excludes `other` memories ────
    let default_recall = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "graph databases", "limit": 10 }),
        )
        .await
        .expect("default recall");
    let default_hits: Vec<&str> = default_recall
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap())
        .collect();

    for oid in &other_ids {
        assert!(
            !default_hits.contains(&oid.as_str()),
            "default recall must exclude other-namespace memory {oid}; got: {default_hits:?}"
        );
    }
    for lid in &local_ids {
        assert!(
            default_hits.contains(&lid.as_str()),
            "default recall must include local memory {lid}; got: {default_hits:?}"
        );
    }

    // ── Assertion 2: wide token includes both namespaces ──────────────────────
    let pack = MemoryPack::new(rt.clone());
    // Warm the ANN so vectors are indexed.
    pack.warm().await;

    let wide_token = rt
        .authorize_with_visibility(
            Namespace::parse("local").expect("local ns"),
            vec![Namespace::parse("other").expect("other ns")],
        )
        .expect("wide token");

    let wide_recall = pack
        .dispatch(
            "memory.recall",
            json!({ "query": "graph databases", "limit": 10 }),
            &registry,
            &wide_token,
        )
        .await
        .expect("wide-token recall");

    let wide_hits: Vec<&str> = wide_recall
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap())
        .collect();

    for lid in &local_ids {
        assert!(
            wide_hits.contains(&lid.as_str()),
            "wide-token recall must include local memory {lid}; got: {wide_hits:?}"
        );
    }
    for oid in &other_ids {
        assert!(
            wide_hits.contains(&oid.as_str()),
            "wide-token recall must include other-namespace memory {oid}; got: {wide_hits:?}"
        );
    }

    // ── Assertion 3: recall@3 satisfied with 3 local candidates even when ────
    // the global ANN top results may include foreign-namespace hits.
    let k3_recall = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "graph databases", "limit": 3 }),
        )
        .await
        .expect("recall@3");
    let k3_hits: Vec<&str> = k3_recall
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap())
        .collect();

    // All 3 local memories should be present — over-fetch ensures enough
    // local candidates survive the post-filter even if the global NN top-k
    // includes foreign-namespace hits.
    assert_eq!(
        k3_hits.len(),
        3,
        "recall@3 must return exactly 3 results when 3 local candidates exist; got: {k3_hits:?}"
    );
    for lid in &local_ids {
        assert!(
            k3_hits.contains(&lid.as_str()),
            "recall@3 must include local memory {lid}; got: {k3_hits:?}"
        );
    }
}

// ── C1 regression (rewritten) ─────────────────────────────────────────────────
//
// ANN bounded retry — local memories must be found even when the first over-fetch
// round is dominated by foreign-namespace vectors that cluster NEAR the query.
//
// Setup (deterministic, hand-constructed geometry):
//   - N_FOREIGN=50 "foreign" vectors embedded near the query direction [1,0,0,0].
//   - N_LOCAL=3  "local"   vectors embedded far from the query direction [0,1,0,0].
//   - Query text maps to [1,0,0,0] (same cluster as foreign).
//   - candidate_limit = Some(8) → ann_fetch_limit = max(8×4, 8+32) = 40.
//   - Round 1: ANN returns 40 nearest → all foreign (locals are far). 0 local survivors.
//   - The retry gate must fire (index spans "foreign" which is NOT in visible {"local"}).
//   - Round 2: doubles fetch to 80 > 53 total → exhausts corpus, finds all 3 locals.
//
// Correctness:
//   - Default (ANN_OVERFETCH_MAX_ROUNDS env unset → 3 rounds): all locals FOUND.
//   - ANN_OVERFETCH_MAX_ROUNDS=1 (single round only): locals MISSING.
//     Run as: ANN_OVERFETCH_MAX_ROUNDS=1 cargo test -p khive-pack-memory \
//                test_ann_overfetch_retry_stalls_without_widening
//
// Token: uses a DEFAULT local-only token — the production default-recall scenario.

/// Content-keyed embedding service.
///
/// Foreign cluster (query direction):
///   texts containing "xforeign", or the query "xforeign dominant cluster" → [1,0,0,0]
///   cosine with query = 1.0 — closest to query, fill top-40 ANN results.
///
/// Local cluster (far from query but NOT orthogonal):
///   texts containing "xlocal" → [0.15, 0.9887, 0.0, 0.0] (pre-normalised unit vector)
///   cosine with query [1,0,0,0] = 0.15 — above the default min_raw_relevance=0.10 floor,
///   but cosine < 1.0 so ANN ranks locals behind all 50 foreign vectors.
///
/// Geometry guarantee:
///   ann_fetch_limit=40 < 50 foreign vectors → round 1 returns only foreign hits;
///   locals are unreachable until the retry widens the window to >53.
struct ClusteredVecService;

#[async_trait]
impl EmbeddingService for ClusteredVecService {
    async fn embed(
        &self,
        texts: &[String],
        _model: EmbeddingModel,
    ) -> std::result::Result<Vec<Vec<f32>>, EmbedError> {
        Ok(texts
            .iter()
            .map(|t| {
                if t.contains("xlocal") {
                    // Far cluster: cosine=0.15 with query direction → above score floor,
                    // but farther than all 50 foreign vectors (cosine=1.0).
                    // Pre-normalised: 0.15² + 0.9887² ≈ 0.0225 + 0.9775 = 1.0000.
                    vec![0.15_f32, 0.9887, 0.0, 0.0]
                } else {
                    // "xforeign" content and the query both map to the foreign cluster.
                    vec![1.0_f32, 0.0, 0.0, 0.0]
                }
            })
            .collect())
    }

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

    fn name(&self) -> &'static str {
        "clustered-vec"
    }
}

struct ClusteredVecProvider {
    provider_name: String,
}

impl ClusteredVecProvider {
    fn new(name: &str) -> Self {
        Self {
            provider_name: name.to_owned(),
        }
    }
}

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

    fn dimensions(&self) -> usize {
        4
    }

    async fn build(&self) -> Result<Arc<dyn EmbeddingService>, khive_runtime::RuntimeError> {
        Ok(Arc::new(ClusteredVecService))
    }
}

/// Shared setup for the C1 regression tests. Returns `(rt, registry, pack, local_ids)`.
///
/// Corpus layout:
///   - 50 foreign memories with vector [1,0,0,0]        (cosine=1.0, nearest to query)
///   - 3  local  memories with vector [0.15,0.9887,0,0] (cosine=0.15, farther from query)
///   - Query "xforeign dominant cluster" → vector [1,0,0,0]
///   - candidate_limit = Some(8) → ann_fetch_limit = 40 < total 53
///
/// With only 40 candidates fetched in round 1, all 40 are foreign (nearest to query).
/// Locals are ranked 51-53 (behind all 50 foreign) and NOT retrieved until the fetch
/// window is widened to ≥53 (round 2 doubles to 80, exhausting the corpus).
///
/// Local cosine=0.15 is above the default min_raw_relevance=0.10 score floor so locals
/// survive the final scoring step once the retry loop surfaces them.
async fn c1_setup() -> (
    KhiveRuntime,
    khive_runtime::VerbRegistry,
    MemoryPack,
    Vec<String>,
) {
    const MODEL: &str = "c1-clustered-enc";
    const N_FOREIGN: usize = 50;
    const N_LOCAL: usize = 3;

    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        ..RuntimeConfig::default()
    })
    .expect("runtime");
    rt.register_embedder(ClusteredVecProvider::new(MODEL));

    let registry = make_registry(rt.clone());

    // Insert N_FOREIGN memories in "foreign" namespace. Content contains "xforeign"
    // so the embedder returns [1,0,0,0] — same direction as the query vector.
    for i in 0..N_FOREIGN {
        registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("xforeign memory slot {i} cluster-a"),
                    "salience": 0.6,
                    "namespace": "foreign"
                }),
            )
            .await
            .unwrap_or_else(|e| panic!("foreign remember {i} failed: {e}"));
    }

    // Insert N_LOCAL memories in "local" namespace. Content contains "xlocal"
    // so the embedder returns [0.15,0.9887,0,0] — far from query (cosine=0.15),
    // ranked behind all 50 foreign vectors but above the min_raw_relevance floor.
    let mut local_ids = Vec::new();
    for i in 0..N_LOCAL {
        let r = registry
            .dispatch(
                "memory.remember",
                json!({
                    "content": format!("xlocal memory {i} must be recalled"),
                    "salience": 0.8,
                    "namespace": "local"
                }),
            )
            .await
            .unwrap_or_else(|e| panic!("local remember {i} failed: {e}"));
        local_ids.push(r["id"].as_str().expect("note_id").to_string());
    }

    let pack = MemoryPack::new(rt.clone());
    {
        use khive_runtime::PackRuntime;
        pack.warm().await;
    }

    (rt, registry, pack, local_ids)
}

// C1 deterministic: asserts BOTH branches of the ANN over-fetch retry loop in a
// single test with no env mutation. Both branches run every CI invocation.
//
// Corpus geometry (see c1_setup):
//   - 50 foreign vectors [1,0,0,0] closest to query direction
//   - 3 local  vectors [0.15,0.9887,0,0] farther from query (cosine=0.15)
//   - candidate_limit=8 → ann_fetch_limit=40 < 53 total
//
// Branch (a): ann_overfetch_max_rounds=3 (≥2 rounds needed to widen to 80>53)
//   → retry fires, corpus exhausted, all 3 locals surface.
//
// Branch (b): ann_overfetch_max_rounds=1 (single round only)
//   → round 1 returns 40 foreign hits; no retry; locals silently absent.
//
// Both branches are exercised in-process via RecallConfig.ann_overfetch_max_rounds.
// No env var mutation; no cross-test interference; no silent skips.
#[tokio::test]
async fn test_ann_overfetch_retry_both_branches_deterministic() {
    use khive_runtime::PackRuntime;

    let (rt, registry, pack, local_ids) = c1_setup().await;

    // Local-only token: the production default. visible = {"local"}.
    // The global ANN index spans {"local", "foreign"} — retry gate must fire.
    let local_token = rt
        .authorize(Namespace::parse("local").expect("local ns"))
        .expect("authorize local");

    // Branch (a): with adequate rounds (3), the retry widens to 80>53 and
    // exhausts the corpus, surfacing all 3 local memories.
    let result_with_retry = pack
        .dispatch(
            "memory.recall",
            json!({
                "query": "xforeign dominant cluster",
                "limit": 3,
                "config": {
                    "candidate_limit": 8,
                    "ann_overfetch_max_rounds": 3
                }
            }),
            &registry,
            &local_token,
        )
        .await
        .expect("recall with retry");

    let hits_with_retry: Vec<&str> = result_with_retry
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap())
        .collect();

    for lid in &local_ids {
        assert!(
            hits_with_retry.contains(&lid.as_str()),
            "C1 branch-a: local memory {lid} MUST appear when retry rounds=3; \
             got: {hits_with_retry:?}"
        );
    }

    // Branch (b): with a single round, round 1 fetches 40 of 53 vectors — all
    // foreign (nearest to query direction). No retry fires so local memories
    // (ranked 51-53 behind all 50 foreign) are absent from the result.
    let result_no_retry = pack
        .dispatch(
            "memory.recall",
            json!({
                "query": "xforeign dominant cluster",
                "limit": 3,
                "config": {
                    "candidate_limit": 8,
                    "ann_overfetch_max_rounds": 1
                }
            }),
            &registry,
            &local_token,
        )
        .await
        .expect("recall without retry");

    let hits_no_retry: Vec<&str> = result_no_retry
        .as_array()
        .expect("array")
        .iter()
        .map(|h| h["id"].as_str().unwrap())
        .collect();

    for lid in &local_ids {
        assert!(
            !hits_no_retry.contains(&lid.as_str()),
            "C1 branch-b: local memory {lid} must NOT appear when retry rounds=1 \
             (corpus geometry broken if it does); got: {hits_no_retry:?}"
        );
    }
}

// ── ADR-007 Rev 6: episodic actor-namespace routing ─────────────────────────────────

/// Build a registry whose dispatch tokens carry the given actor_id.
///
/// This is the test seam for ADR-007 Rev 6: `VerbRegistryBuilder::with_actor_id`
/// configures the actor that `dispatch()` uses when minting the NamespaceToken
/// passed to each handler. `mint_authorized` is `pub(crate)` to khive-runtime, so
/// tests in other crates must go through this builder path.
fn make_registry_with_actor(rt: KhiveRuntime, actor_id: &str) -> khive_runtime::VerbRegistry {
    let mut builder = VerbRegistryBuilder::new();
    builder.with_actor_id(Some(actor_id.to_string()));
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt));
    builder.build().expect("registry with actor builds")
}

/// ADR-007 Rev 6: episodic memory → stamped with actor namespace.
///
/// A registry configured with actor_id="alice" writes an episodic memory.
/// The note's stored namespace must be "alice".
#[tokio::test]
async fn test_episodic_remember_stamps_actor_namespace() {
    let rt = make_runtime();
    let registry = make_registry_with_actor(rt.clone(), "alice");

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "alice episodic event for namespace routing test",
                "memory_type": "episodic",
            }),
        )
        .await
        .expect("memory.remember must succeed");

    let note_id = result["id"].as_str().expect("response has id").to_owned();

    // Fetch the note by ID (by-ID get is namespace-agnostic per PR-A1).
    let got = registry
        .dispatch("get", json!({ "id": note_id }))
        .await
        .expect("get by UUID must succeed");

    let stored_ns = got["namespace"].as_str().expect("note has namespace field");
    assert_eq!(
        stored_ns, "alice",
        "ADR-007 Rev 6: episodic memory with actor_id=alice must be stamped in namespace 'alice'; \
         got: {stored_ns:?}"
    );
}

/// ADR-007 Rev 6: semantic memory → remains in "local" (shared pool).
///
/// Even with actor_id="alice", a semantic memory must land in "local".
#[tokio::test]
async fn test_semantic_remember_stamps_local_namespace() {
    let rt = make_runtime();
    let registry = make_registry_with_actor(rt.clone(), "alice");

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "alice semantic fact for namespace routing test",
                "memory_type": "semantic",
            }),
        )
        .await
        .expect("memory.remember must succeed");

    let note_id = result["id"].as_str().expect("response has id").to_owned();

    let got = registry
        .dispatch("get", json!({ "id": note_id }))
        .await
        .expect("get by UUID must succeed");

    let stored_ns = got["namespace"].as_str().expect("note has namespace field");
    assert_eq!(
        stored_ns, "local",
        "ADR-007 Rev 6: semantic memory must always land in 'local' regardless of actor; \
         got: {stored_ns:?}"
    );
}

/// ADR-007 Rev 6: explicit namespace= override takes precedence over routing rules.
///
/// Passing `namespace="override-ns"` with an episodic memory for actor "alice"
/// must stamp the note in "override-ns", not "alice".
///
/// Note: override correctness is provided at the dispatch layer — the Rule-3 escape
/// in pack.rs (~line 886) mints the override namespace into the token BEFORE the
/// handler runs. This test confirms the end-to-end override behavior as seen by
/// callers, not the handler's own override branch in isolation.
#[tokio::test]
async fn test_remember_namespace_override_takes_precedence() {
    let rt = make_runtime();
    let registry = make_registry_with_actor(rt.clone(), "alice");

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "explicit override namespace test",
                "memory_type": "episodic",
                "namespace": "override-ns",
            }),
        )
        .await
        .expect("memory.remember with explicit namespace must succeed");

    let note_id = result["id"].as_str().expect("response has id").to_owned();

    let got = registry
        .dispatch("get", json!({ "id": note_id }))
        .await
        .expect("get by UUID must succeed");

    let stored_ns = got["namespace"].as_str().expect("note has namespace field");
    assert_eq!(
        stored_ns, "override-ns",
        "ADR-007 Rev 6: explicit namespace= must override actor routing; \
         got: {stored_ns:?}"
    );
}

/// ADR-007 Rev 6: anonymous actor (actor_id="local") episodic → namespace "local".
///
/// When no actor is configured (`ActorRef::anonymous()` has id="local"), episodic
/// memories must land in "local" — backward-compatible with pre-Rev-6 behavior.
#[tokio::test]
async fn test_episodic_anonymous_actor_uses_local() {
    // make_registry uses the default builder (no actor_id) → ActorRef::anonymous() → id="local".
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "anonymous episodic memory backward-compat test",
                "memory_type": "episodic",
            }),
        )
        .await
        .expect("memory.remember must succeed");

    let note_id = result["id"].as_str().expect("response has id").to_owned();

    let got = registry
        .dispatch("get", json!({ "id": note_id }))
        .await
        .expect("get by UUID must succeed");

    let stored_ns = got["namespace"].as_str().expect("note has namespace field");
    assert_eq!(
        stored_ns, "local",
        "ADR-007 Rev 6: anonymous actor (id='local') episodic memory must land in 'local' \
         (backward-compat no-op); got: {stored_ns:?}"
    );
}

/// ADR-007 Rev 6 (R1): cross-actor isolation — episodic write lands in actor ns AND is
/// invisible to a principal whose visible set excludes that actor namespace.
///
/// This is the discriminating test for the Rev-6 carve-out:
///   (a) Alice's episodic memory writes to the "alice" namespace and is recallable by alice.
///   (b) A `{local}`-only principal (anonymous make_registry) CANNOT recall alice's memory.
///
/// The vector leg is seeded with a ConstVecProvider but — because all stored
/// memories share the same constant embedding vector — it cannot discriminate
/// between alice's memory and any other.  The genuine cross-actor gate is the FTS
/// namespace fanout; the vector leg is structurally present but not the discriminating
/// signal (noted honestly here per the brief).  The FTS isolation IS the RED→GREEN
/// discriminator validated by the red-run procedure.
///
/// Note: recall as alice requires alice's registry to have `with_visible_namespaces([alice_ns])`
/// because pack.rs dispatch (default path) fans reads over {local} ∪ visible_namespaces only.
#[tokio::test]
async fn adr007_rev6_episodic_cross_actor_isolation() {
    const MODEL_A: &str = "rev6-isolation-enc";
    const DIMS: usize = 4;

    // Build a runtime. Both alice and the anonymous observer share the same in-memory DB,
    // which is the only way to verify cross-actor isolation within a single test.
    let rt = KhiveRuntime::new(RuntimeConfig {
        db_path: None,
        embedding_model: None,
        additional_embedding_models: vec![],
        visible_namespaces: vec![Namespace::parse("alice").unwrap()],
        ..RuntimeConfig::default()
    })
    .expect("in-memory runtime");
    // Register a ConstVecProvider so the vector leg is structurally live.
    // NOTE: ConstVecProvider returns the same constant vector for every input, so the
    // vector leg cannot discriminate between principals — the cross-actor isolation
    // enforced here is via the FTS namespace fanout.  The vector leg is present but
    // not a meaningful signal for this test.
    rt.register_embedder(ConstVecProvider::new(MODEL_A, DIMS, 0.9));

    // Alice's registry: actor_id="alice" + alice in visible_namespaces so recall fans out there.
    let mut builder = VerbRegistryBuilder::new();
    builder.with_actor_id(Some("alice".to_string()));
    builder.with_visible_namespaces(vec![Namespace::parse("alice").unwrap()]);
    builder.register(KgPack::new(rt.clone()));
    builder.register(MemoryPack::new(rt.clone()));
    let alice_registry = builder.build().expect("alice registry builds");

    // Anonymous (bob-equivalent) registry: no actor_id, no alice in visible set →
    // only {local} is in scope for reads.
    let anon_registry = make_registry(rt.clone());

    // Step (a): alice writes an episodic memory (no explicit namespace= arg).
    let result = alice_registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "alice private episodic cross-actor isolation marker",
                "memory_type": "episodic",
            }),
        )
        .await
        .expect("memory.remember as alice must succeed");
    let note_id = result["id"].as_str().expect("note id present").to_owned();
    assert!(!note_id.is_empty());

    // Confirm the write landed in the "alice" namespace (not "local").
    let got = alice_registry
        .dispatch("get", json!({ "id": note_id }))
        .await
        .expect("get by UUID must succeed");
    let stored_ns = got["namespace"].as_str().expect("note has namespace field");
    assert_eq!(
        stored_ns, "alice",
        "ADR-007 Rev 6: episodic memory must land in actor namespace 'alice'; got: {stored_ns:?}"
    );

    // Step (a-recall): alice can recall her own episodic memory.
    let alice_recall = alice_registry
        .dispatch(
            "memory.recall",
            json!({ "query": "alice private episodic cross-actor isolation marker" }),
        )
        .await
        .expect("memory.recall as alice must succeed");
    let alice_hits = alice_recall.as_array().expect("recall returns array");
    let alice_ids: Vec<&str> = alice_hits
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        alice_ids.contains(&note_id.as_str()),
        "ADR-007 Rev 6: alice must recall her own episodic memory; got: {alice_ids:?}"
    );

    // Step (b): the anonymous (local-only) principal MUST NOT recall alice's episodic memory.
    // This is the cross-actor isolation guarantee — the "alice" namespace is outside the
    // anonymous visible set {local}, so the memory must be absent from recall results.
    let anon_recall = anon_registry
        .dispatch(
            "memory.recall",
            json!({ "query": "alice private episodic cross-actor isolation marker" }),
        )
        .await
        .expect("memory.recall as anonymous must succeed");
    let anon_hits = anon_recall.as_array().expect("recall returns array");
    let anon_ids: Vec<&str> = anon_hits
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        !anon_ids.contains(&note_id.as_str()),
        "ADR-007 Rev 6: anonymous principal (visible={{local}}) must NOT see alice's episodic \
         memory (in namespace 'alice'); isolation FAILED — got: {anon_ids:?}"
    );
}

// ── expires_at recall filter ──────────────────────────────────────────────────

/// Expired memories (expires_at <= now) must be excluded from recall results.
#[tokio::test]
async fn test_expires_at_excluded_from_recall() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Store a memory.
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "this memory should expire and vanish from recall",
                "memory_type": "semantic",
                "salience": 0.9,
            }),
        )
        .await
        .expect("memory.remember must succeed");

    let note_id_str = result["id"].as_str().expect("note id present").to_owned();
    let note_id: Uuid = note_id_str.parse().expect("valid UUID");

    // Confirm it is recalled while fresh.
    let fresh_recall = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "memory should expire and vanish from recall" }),
        )
        .await
        .expect("recall must succeed");
    let fresh_hits = fresh_recall.as_array().expect("array");
    let fresh_ids: Vec<&str> = fresh_hits
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        fresh_ids.contains(&note_id_str.as_str()),
        "memory must appear in recall before expiry; got: {fresh_ids:?}"
    );

    // Backdate expires_at to a point in the past.
    let past_micros = chrono::Utc::now().timestamp_micros() - 1_000_000; // 1 second ago
    let tok = rt.authorize(Namespace::local()).expect("authorize local");
    let note_store = rt.notes(&tok).expect("notes store");
    let mut note = note_store
        .get_note(note_id)
        .await
        .expect("get must succeed")
        .expect("note must exist");
    note.expires_at = Some(past_micros);
    note_store
        .upsert_note(note)
        .await
        .expect("upsert must succeed");

    // Now recall must NOT include the expired memory.
    let expired_recall = registry
        .dispatch(
            "memory.recall",
            json!({ "query": "memory should expire and vanish from recall" }),
        )
        .await
        .expect("recall after expiry must succeed");
    let expired_hits = expired_recall.as_array().expect("array");
    let expired_ids: Vec<&str> = expired_hits
        .iter()
        .map(|h| h["id"].as_str().unwrap_or(""))
        .collect();
    assert!(
        !expired_ids.contains(&note_id_str.as_str()),
        "expired memory (expires_at <= now) must be excluded from recall; got: {expired_ids:?}"
    );
}

// ── memory.prune ─────────────────────────────────────────────────────────────

/// memory.prune with min_salience soft-deletes low-salience memories.
#[tokio::test]
async fn test_prune_by_salience() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // High-salience memory — must survive prune.
    let high = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "high salience memory that should survive prune",
                "memory_type": "semantic",
                "salience": 0.9,
            }),
        )
        .await
        .expect("remember high");
    let high_id = high["id"].as_str().expect("id").to_owned();

    // Low-salience memory — must be pruned.
    let low = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "low salience memory that should be pruned",
                "memory_type": "semantic",
                "salience": 0.1,
            }),
        )
        .await
        .expect("remember low");
    let low_id = low["id"].as_str().expect("id").to_owned();

    // Prune min_salience=0.5: low must go, high must remain.
    let prune_result = registry
        .dispatch("memory.prune", json!({ "min_salience": 0.5, "before": 0 }))
        .await
        .expect("memory.prune must succeed");

    assert_eq!(
        prune_result["dry_run"].as_bool(),
        Some(false),
        "dry_run must be false"
    );
    assert!(
        prune_result["pruned"].as_u64().unwrap_or(0) >= 1,
        "at least 1 memory pruned; got: {prune_result:?}"
    );

    // Verify via NoteStore that low-salience note is soft-deleted.
    let tok = rt.authorize(Namespace::local()).expect("authorize local");
    let low_uuid: Uuid = low_id.parse().expect("valid uuid");
    let low_note = rt
        .get_note_including_deleted(&tok, low_uuid)
        .await
        .expect("get must succeed")
        .expect("row must exist");
    assert!(
        low_note.deleted_at.is_some(),
        "low-salience memory must be soft-deleted after prune; deleted_at={:?}",
        low_note.deleted_at
    );

    // High-salience note must NOT be deleted.
    let high_uuid: Uuid = high_id.parse().expect("valid uuid");
    let high_note = rt
        .get_note_including_deleted(&tok, high_uuid)
        .await
        .expect("get must succeed")
        .expect("row must exist");
    assert!(
        high_note.deleted_at.is_none(),
        "high-salience memory must NOT be deleted by prune; deleted_at={:?}",
        high_note.deleted_at
    );
}

/// memory.prune with no explicit `before` value (defaults to now) prunes expired memories.
#[tokio::test]
async fn test_prune_expired_by_default_cutoff() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    // Store a memory.
    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "will be expired and then pruned",
                "memory_type": "semantic",
                "salience": 0.8,
            }),
        )
        .await
        .expect("remember");
    let note_id_str = result["id"].as_str().expect("id").to_owned();
    let note_id: Uuid = note_id_str.parse().expect("valid uuid");

    // Set expires_at to the past.
    let past_micros = chrono::Utc::now().timestamp_micros() - 1_000_000;
    let tok = rt.authorize(Namespace::local()).expect("authorize local");
    let note_store = rt.notes(&tok).expect("notes");
    let mut note = note_store
        .get_note(note_id)
        .await
        .expect("get")
        .expect("exists");
    note.expires_at = Some(past_micros);
    note_store.upsert_note(note).await.expect("upsert");

    // Prune with no salience filter, default cutoff = now.
    let prune_result = registry
        .dispatch("memory.prune", json!({}))
        .await
        .expect("memory.prune must succeed");

    assert!(
        prune_result["pruned"].as_u64().unwrap_or(0) >= 1,
        "expired memory must be pruned; got: {prune_result:?}"
    );

    let pruned_note = rt
        .get_note_including_deleted(&tok, note_id)
        .await
        .expect("get")
        .expect("exists");
    assert!(
        pruned_note.deleted_at.is_some(),
        "expired memory must be soft-deleted after prune"
    );
}

/// memory.prune dry_run=true counts without deleting.
#[tokio::test]
async fn test_prune_dry_run() {
    let rt = make_runtime();
    let registry = make_registry(rt.clone());

    let result = registry
        .dispatch(
            "memory.remember",
            json!({
                "content": "dry run target memory",
                "memory_type": "semantic",
                "salience": 0.05,
            }),
        )
        .await
        .expect("remember");
    let note_id_str = result["id"].as_str().expect("id").to_owned();
    let note_id: Uuid = note_id_str.parse().expect("valid uuid");

    // Dry run — should report would_prune >= 1 but not delete.
    let dry_result = registry
        .dispatch(
            "memory.prune",
            json!({ "min_salience": 0.5, "before": 0, "dry_run": true }),
        )
        .await
        .expect("memory.prune dry_run must succeed");

    assert_eq!(
        dry_result["dry_run"].as_bool(),
        Some(true),
        "dry_run field must be true"
    );
    assert!(
        dry_result["would_prune"].as_u64().unwrap_or(0) >= 1,
        "dry_run must report >= 1 would_prune; got: {dry_result:?}"
    );
    assert_eq!(
        dry_result["pruned"].as_u64(),
        Some(0),
        "dry_run must not delete (pruned must be 0)"
    );

    // Verify note is NOT deleted.
    let tok = rt.authorize(Namespace::local()).expect("authorize local");
    let note = rt
        .get_note_including_deleted(&tok, note_id)
        .await
        .expect("get")
        .expect("exists");
    assert!(
        note.deleted_at.is_none(),
        "dry_run must not soft-delete notes; deleted_at={:?}",
        note.deleted_at
    );
}

// ── memory.vacuum ─────────────────────────────────────────────────────────────

/// memory.vacuum must succeed and return ok=true.
#[tokio::test]
async fn test_vacuum_succeeds() {
    let rt = make_runtime();
    let registry = make_registry(rt);

    let result = registry
        .dispatch("memory.vacuum", json!({}))
        .await
        .expect("memory.vacuum must succeed");

    assert_eq!(
        result["ok"].as_bool(),
        Some(true),
        "vacuum must return ok=true; got: {result:?}"
    );
}