khive-pack-memory 0.2.11

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
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")
}

#[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["note_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]["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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!([
        { "note_id": "00000000-0000-0000-0000-000000000001", "fused_score": 0.8 },
        { "note_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]["note_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["note_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["note_id"].as_str().unwrap().to_string();
    let mem2_id = mem2["note_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["note_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("note_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 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["note_id"].as_str(),
            k["note_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["note_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["note_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["note_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["note_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["note_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!([
        {
            "note_id": "00000000-0000-0000-0000-000000000001",
            "fused_score": 0.9,
            "source": "both"
        },
        {
            "note_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["note_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["note_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}"
    );
}

// ── Codex High fixes regressions (#444) ──────────────────────────────────────

/// 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,
        }))
    }
}

/// Fix 1 regression (codex High #1, PR #444): 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["note_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["note_id"].as_str().unwrap())
        .collect();
    assert!(
        ids.contains(&note_id),
        "recall must find the note created via custom embedder; got: {ids:?}"
    );
}

/// Fix 2 regression (codex High #2, PR #444): 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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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["note_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}"
    );
}