wm-tools 9.2.4

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

#![forbid(unsafe_code)]

use async_trait::async_trait;

use serde_json::{Value, json};
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::Arc;
use wm_core::{Context, EffectRow, Galaxy, Gana, Resource, Tool, ToolStats};
use wm_memory::{
    AssociationStore, MemoryStore, RecallEngine, SearchEngine, episodic::detect_conflicts,
};

use super::common::{
    bool_prop, galaxy_name, galaxy_search_arg, int_prop, num_prop, parse_galaxy, parse_galaxy_or,
    schema, str_prop,
};

/// Recall-mode label for the fused search route.
///
/// The fusion path runs whenever a real embedder is wired, but with the
/// vector weight configured to zero it ranks by BM25 alone. The disclosure
/// must follow the configured weights, not the code path taken (T0 finding
/// F-T0-2: `bm25-baseline` disclosed `hybrid` while its ranking was BM25).
fn fused_mode_label(vector_weight: f32) -> &'static str {
    if vector_weight > 0.0 {
        "hybrid"
    } else {
        "bm25"
    }
}

/// Attach the navigation disclosure to a scrubbed excerpt result. The source
/// stays exact and `memory.read` remains the complete-read path.
fn with_navigation_disclosure(mut result: serde_json::Value, original: &str) -> serde_json::Value {
    let limit = wm_memory::search::MAX_INDEX_CONTENT_LEN;
    let scrubbed = result
        .get("content")
        .and_then(serde_json::Value::as_str)
        .is_none_or(|navigation| navigation != original);
    if let Some(obj) = result.as_object_mut() {
        obj.insert(
            "content_representation".into(),
            json!("scrubbed_navigation"),
        );
        obj.insert("content_character_limit".into(), json!(limit));
        obj.insert(
            "content_truncated".into(),
            json!(original.chars().nth(limit).is_some()),
        );
        obj.insert("content_scrubbed".into(), json!(scrubbed));
        obj.insert("exact_read_available".into(), json!(true));
        // mcp-input-boundary (2026-09-21): content that reads as
        // instructions is disclosed on surfacing, not blocked at the write.
        // The model (and any UI) can treat it as untrusted data; exact read
        // stays available for humans and audit.
        if let Some(pattern) = wm_memory::detect_injection(original) {
            obj.insert("instruction_shaped".into(), json!(true));
            obj.insert("instruction_pattern".into(), json!(pattern));
        }
    }
    result
}

/// Absolute-BM25 abstention floor (`WM_RECALL_ABSTENTION_FLOOR`); 0 = off.
fn abstention_floor() -> f32 {
    std::env::var("WM_RECALL_ABSTENTION_FLOOR")
        .ok()
        .and_then(|value| value.trim().parse::<f32>().ok())
        .filter(|value| *value > 0.0)
        .unwrap_or(0.0)
}

/// Minimum matched-term coverage (`WM_RECALL_ABSTENTION_COVERAGE`, 0..=1); 0 = off.
fn abstention_coverage() -> f32 {
    std::env::var("WM_RECALL_ABSTENTION_COVERAGE")
        .ok()
        .and_then(|value| value.trim().parse::<f32>().ok())
        .filter(|value| (0.0..=1.0).contains(value) && *value > 0.0)
        .unwrap_or(0.0)
}

/// Weak-evidence abstention over already-assembled result JSON.
///
/// Per-query normalization makes the top hit's `score` 1.0 no matter how weak
/// the match (2026-09-22 hosted-lane finding). Each result now also carries
/// `raw_score` (absolute BM25) or `matched_terms` (episodic coverage); these
/// opt-in knobs turn that absolute signal into an explicit abstention object.
/// Results are never dropped here — the caller can still inspect them.
fn weak_evidence_abstention(
    results: &[serde_json::Value],
    query: &str,
) -> Option<serde_json::Value> {
    weak_evidence_abstention_with(results, query, abstention_floor(), abstention_coverage())
}

/// Parameterized core of [`weak_evidence_abstention`] (deterministic tests).
fn weak_evidence_abstention_with(
    results: &[serde_json::Value],
    query: &str,
    floor: f32,
    coverage_floor: f32,
) -> Option<serde_json::Value> {
    if floor <= 0.0 && coverage_floor <= 0.0 {
        return None;
    }
    let top = results.first()?;
    let source = top
        .get("source")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    match source {
        "hybrid" | "bm25" | "fts" => {
            let raw = top
                .get("raw_score")
                .and_then(serde_json::Value::as_f64)
                .unwrap_or(0.0);
            // `raw == 0.0` marks vector-only evidence (cosine scale, not BM25):
            // the BM25 floor does not apply — disclosed, not guessed.
            if floor > 0.0 && raw > 0.0 && (raw as f32) < floor {
                return Some(json!({
                    "status": "insufficient_evidence",
                    "reason": "top_below_floor",
                    "scope": "retrieval",
                    "signal": "bm25",
                    "top_score": raw,
                    "floor": floor,
                }));
            }
        }
        "episodic" => {
            let matched = top
                .get("matched_terms")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0);
            let query_terms = wm_memory::strip_stopwords(query).split_whitespace().count() as u64;
            if coverage_floor > 0.0 && query_terms > 0 {
                let coverage = matched as f64 / query_terms as f64;
                if coverage < f64::from(coverage_floor) {
                    return Some(json!({
                        "status": "insufficient_evidence",
                        "reason": "coverage_below_floor",
                        "scope": "retrieval",
                        "signal": "coverage",
                        "coverage": coverage,
                        "matched_terms": matched,
                        "query_terms": query_terms,
                        "floor": coverage_floor,
                    }));
                }
            }
        }
        _ => {}
    }
    None
}

/// Compact per-result evidence bundle (v0): exact identity, retrieval reason,
/// source time, integrity, visibility, and coverage. Cold-only records report
/// their time as unavailable rather than guessing.
fn build_evidence_bundle(store: &MemoryStore, results: &[serde_json::Value]) -> serde_json::Value {
    let entries: Vec<serde_json::Value> = results
        .iter()
        .map(|r| {
            let id = r
                .get("id")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let galaxy = r
                .get("galaxy")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_string();
            let resolved = uuid::Uuid::parse_str(&id)
                .ok()
                .and_then(|key| resolve_memory_across_galaxies(store, key));
            let (source_time, visibility, history) = match &resolved {
                Some((_, mem)) => {
                    let revisions = store
                        .revisions(mem.metadata.galaxy, mem.metadata.id)
                        .unwrap_or_default();
                    let chain_valid =
                        wm_memory::revision::verify_chain(&revisions, &mem.metadata.content_hash)
                            .valid;
                    (
                        json!({
                            "created_at": mem.metadata.created_at,
                            "basis": "recorded_at",
                            "event_time": serde_json::Value::Null,
                            "event_time_basis": "not_tracked",
                        }),
                        json!({
                            "private": mem.metadata.is_private,
                            "model_exclude": mem.metadata.model_exclude,
                        }),
                        json!({
                            "revision_count": revisions.len(),
                            "superseded": !revisions.is_empty(),
                            "chain_valid": chain_valid,
                            "current": true,
                        }),
                    )
                }
                None => (
                    json!({
                        "created_at": serde_json::Value::Null,
                        "basis": "unavailable_cold_record",
                        "event_time": serde_json::Value::Null,
                        "event_time_basis": "not_tracked",
                    }),
                    json!({
                        "private": false,
                        "model_exclude": !r
                            .get("model_visible")
                            .and_then(serde_json::Value::as_bool)
                            .unwrap_or(false),
                    }),
                    json!({
                        "revision_count": 0,
                        "superseded": false,
                        "chain_valid": serde_json::Value::Null,
                        "current": true,
                        "basis": "unavailable_cold_record",
                    }),
                ),
            };
            let mut retrieval = json!({
                "route": r.get("source").cloned().unwrap_or(serde_json::Value::Null),
                "score": r.get("score").cloned().unwrap_or(serde_json::Value::Null),
            });
            if let Some(terms) = r.get("matched_terms") {
                retrieval["matched_terms"] = terms.clone();
            }
            if let Some(via) = r.get("via") {
                retrieval["via"] = via.clone();
            }
            json!({
                "id": id,
                "galaxy": galaxy,
                "retrieval": retrieval,
                "source_time": source_time,
                "history": history,
                "integrity": r
                    .get("integrity")
                    .cloned()
                    .unwrap_or_else(|| json!("source_read")),
                "visibility": visibility,
                "coverage": {
                    "representation": r
                        .get("content_representation")
                        .cloned()
                        .unwrap_or(serde_json::Value::Null),
                    "truncated": r
                        .get("content_truncated")
                        .cloned()
                        .unwrap_or(serde_json::Value::Null),
                    "exact_read_available": r
                        .get("exact_read_available")
                        .cloned()
                        .unwrap_or(json!(false)),
                },
            })
        })
        .collect();
    let shims: Vec<wm_memory::episodic::EpisodicSearchResult> = results
        .iter()
        .filter_map(|r| {
            let id = r.get("id").and_then(serde_json::Value::as_str)?;
            let key = uuid::Uuid::parse_str(id).ok()?;
            let record = store.episodic().get(key).ok().flatten()?;
            Some(wm_memory::episodic::EpisodicSearchResult {
                record,
                score: 0.0,
                matched_terms: 0,
            })
        })
        .collect();
    let conflicts = detect_conflicts(&shims);
    let pairs: Vec<serde_json::Value> = conflicts
        .iter()
        .map(|c| {
            json!({
                "later": c.later_record.to_string(),
                "earlier": c.earlier_record.to_string(),
                "marker": c.marker,
                "shared_terms": c.shared_terms,
            })
        })
        .collect();
    json!({
        "version": "v0",
        "count": entries.len(),
        "entries": entries,
        "conflicts": {"count": pairs.len(), "pairs": pairs},
    })
}

/// Resolve a memory id across all memory galaxies. Associations may point at
/// records in any galaxy; callers should not have to guess which one.
fn resolve_memory_across_galaxies(
    store: &MemoryStore,
    id: uuid::Uuid,
) -> Option<(wm_core::Galaxy, wm_memory::Memory)> {
    for galaxy in wm_core::Galaxy::memory_galaxies() {
        if let Ok(Some(mem)) = store.get(galaxy, id) {
            return Some((galaxy, mem));
        }
    }
    None
}

/// `memory.consolidate` — deduplicate memories by content_hash within a galaxy.
pub struct MemoryConsolidateTool {
    store: Arc<MemoryStore>,
    search: Option<Arc<SearchEngine>>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryConsolidateTool {
    pub fn new(store: Arc<MemoryStore>, search: Option<Arc<SearchEngine>>) -> Self {
        Self {
            store,
            search,
            stats: ToolStats::default(),
            effects: EffectRow {
                writes: super::common::memory_galaxy_writes(),
                reads: super::common::memory_galaxy_reads(),
                destructive: true,
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryConsolidateTool {
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to consolidate (optional; default codex)"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.consolidate"
    }
    fn gana(&self) -> Gana {
        Gana::Encampment
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Deduplicate memories by content_hash within a galaxy"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = args
            .get("galaxy")
            .and_then(|v| v.as_str())
            .unwrap_or("codex");
        let galaxy = parse_galaxy(galaxy)?;
        // Full scan: research/sessions galaxies exceed the legacy 10k scan cap,
        // which silently left the tail un-consolidated (B5 heritage dedupe).
        let memories = self.store.scan_all(galaxy)?;
        let mut seen_hashes: HashMap<String, uuid::Uuid> = HashMap::new();
        let mut duplicates = 0u32;
        for mem in &memories {
            let hash = &mem.metadata.content_hash;
            if let Some(existing_id) = seen_hashes.get(hash) {
                if *existing_id != mem.metadata.id {
                    self.store.delete(galaxy, mem.metadata.id)?;
                    super::common::deindex(self.search.as_deref(), &mem.metadata.id.to_string());
                    duplicates += 1;
                }
            } else {
                seen_hashes.insert(hash.clone(), mem.metadata.id);
            }
        }
        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "scanned": memories.len(),
            "duplicates_removed": duplicates,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.decay` — lower importance of old, low-access memories.
pub struct MemoryDecayTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryDecayTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow {
                writes: super::common::memory_galaxy_writes(),
                reads: super::common::memory_galaxy_reads(),
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryDecayTool {
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to decay (optional; default codex)"),
                "importance_threshold": super::common::num_prop("Decay memories below this importance (0-1)"),
                "decay_factor": super::common::num_prop("Multiplier applied to importance (0-1)"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.decay"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Lower importance of old, low-access memories (never deletes)"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = args
            .get("galaxy")
            .and_then(|v| v.as_str())
            .unwrap_or("codex");
        let galaxy = parse_galaxy(galaxy)?;
        let threshold = args
            .get("importance_threshold")
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(0.3) as f32;
        let decay_factor = args
            .get("decay_factor")
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(0.9) as f32;
        let memories = self.store.scan(galaxy, 10_000)?;
        let mut decayed = 0u32;
        for mem in &memories {
            if mem.metadata.importance < threshold {
                let mut updated = mem.clone();
                updated.metadata.importance =
                    (updated.metadata.importance * decay_factor).clamp(0.0, 1.0);
                if (updated.metadata.importance - mem.metadata.importance).abs() > 0.001 {
                    self.store.put(galaxy, &updated)?;
                    decayed += 1;
                }
            }
        }
        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "scanned": memories.len(),
            "decayed": decayed,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.batch_read` — read multiple memories by ID.
pub struct MemoryBatchReadTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryBatchReadTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryBatchReadTool {
    fn name(&self) -> &str {
        "memory.batch_read"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Read multiple memories by ID from a galaxy"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "ids": super::common::str_array_prop("Memory UUIDs to read"),
                "galaxy": super::common::str_prop("Galaxy (default: codex)"),
            }),
            &["ids"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = args
            .get("galaxy")
            .and_then(|v| v.as_str())
            .unwrap_or("codex");
        let galaxy = parse_galaxy(galaxy)?;
        let ids = args
            .get("ids")
            .and_then(|v| v.as_array())
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("Missing 'ids' array".into()))?;
        let mut results = Vec::new();
        let mut misses = 0u32;
        for id_val in ids {
            if let Some(id_str) = id_val.as_str() {
                if let Ok(id) = uuid::Uuid::parse_str(id_str) {
                    match self.store.get(galaxy, id)? {
                        Some(mem)
                            if crate::expansion::common::mcp_visible(&mem)
                                && crate::expansion::common::validity_visible(&mem) =>
                        {
                            results.push(json!({
                                "id": mem.metadata.id,
                                "content": mem.content,
                                "tags": mem.metadata.tags,
                                "importance": mem.metadata.importance,
                            }));
                        }
                        // Private memories are treated like misses — they never
                        // appear in MCP responses.
                        Some(_) => {
                            misses += 1;
                        }
                        None => {
                            misses += 1;
                        }
                    }
                }
            }
        }
        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "found": results.len(),
            "misses": misses,
            "memories": results,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.update` — update tags or importance of a memory.
///
/// If a `SearchEngine` is provided, the updated memory is re-indexed into
/// Tantivy (delete old doc, add new doc, commit).
pub struct MemoryUpdateTool {
    store: Arc<MemoryStore>,
    search: Option<Arc<SearchEngine>>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryUpdateTool {
    pub fn new(store: Arc<MemoryStore>, search: Option<Arc<SearchEngine>>) -> Self {
        Self {
            store,
            search,
            stats: ToolStats::default(),
            effects: EffectRow {
                writes: super::common::memory_galaxy_writes(),
                reads: super::common::memory_galaxy_reads(),
                // Landlock v1 first batch (P-SANDBOX-3): store-root-only body.
                sandbox: wm_core::Sandbox::StoreScoped,
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryUpdateTool {
    fn name(&self) -> &str {
        "memory.update"
    }
    fn gana(&self) -> Gana {
        Gana::Encampment
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Update tags, importance, title/topic, or content of an existing memory"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "id": super::common::str_prop("Memory UUID to update"),
                "content": super::common::str_prop("New content (optional)"),
                "tags": super::common::str_array_prop("Replacement tags (optional)"),
                "importance": super::common::bounded_num_prop("New importance 0.0-1.0 (optional)", 0.0, 1.0),
                "title": super::common::str_prop("New title (optional)"),
                "topic": super::common::str_prop("New topic label (optional)"),
                "galaxy": super::common::str_prop("Galaxy (default: codex)"),
            }),
            &["id"],
        )
    }
    async fn call(&self, ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let id_str = args
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("Missing 'id'".into()))?;
        let id = uuid::Uuid::parse_str(id_str)
            .map_err(|e| wm_core::CoreError::InvalidArgs(format!("Invalid UUID: {e}")))?;
        if let Some(search) = &self.search {
            if search.is_readonly() {
                return Err(wm_core::CoreError::InvalidArgs(
                    "read-only mode: memory.update disabled (another process owns the index)"
                        .into(),
                ));
            }
        }
        let mut mem = self.store.get(galaxy, id)?.ok_or_else(|| {
            wm_core::CoreError::NotFound(format!(
                "Memory {id} not found in {}",
                galaxy_name(galaxy)
            ))
        })?;
        let previous_hash = mem.metadata.content_hash.clone();
        let content_changed = args.get("content").and_then(|v| v.as_str()).is_some();
        if let Some(tags) = args.get("tags").and_then(|v| v.as_array()) {
            mem.metadata.tags = tags
                .iter()
                .filter_map(|t| t.as_str().map(String::from))
                .collect();
        }
        // Importance is applied verbatim: class ceilings/floors live in
        // the pipeline write gate (V8 S5/S11d), the single seam every
        // dispatch passes through. Direct tool calls bypass the gate by
        // construction — same contract as the create path. Range validation
        // still applies here: out-of-interval values are caller errors.
        if args.get("importance").is_some() && !args["importance"].is_null() {
            let importance =
                wm_dispatch::write_gate::parse_importance_value(args.get("importance"))
                    .map_err(wm_core::CoreError::InvalidArgs)?;
            if let Some(importance) = importance {
                mem.metadata.importance = importance;
            }
        }
        // Envelope v2 (S4): title/topic are settable and clearable
        // (explicit null clears; absent leaves untouched).
        if let Some(title) = args.get("title") {
            mem.metadata.title = title
                .as_str()
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(String::from);
        }
        if let Some(topic) = args.get("topic") {
            mem.metadata.topic = topic
                .as_str()
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(String::from);
        }
        if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
            mem.content = content.to_string();
            // Content changes invalidate the hash — keep it in sync so
            // dedup and content-hash lookups stay truthful.
            mem.metadata.content_hash = wm_memory::content_hash(content);
            // V8 S11c: content changes bump the revision counter; the
            // chain entry itself is recorded after the row lands.
            mem.metadata.revision_count = mem.metadata.revision_count.saturating_add(1);
        }
        self.store.put(galaxy, &mem)?;

        // V8 S11c: append the revision entry — seq, hashes, and the
        // attributed actor from the dispatch context. A chain failure
        // degrades loud (warn + disclosure), never silently.
        let mut revision_disclosure = None;
        if content_changed {
            let actor = wm_memory::RevisionActor {
                session: ctx.session_id.map(|sid| sid.to_string()),
                user: ctx.user_id.clone(),
                compartment: ctx.compartment.clone(),
            };
            match self.store.record_revision(
                galaxy,
                id,
                &previous_hash,
                &mem.metadata.content_hash,
                actor,
            ) {
                Ok(rev) => {
                    revision_disclosure = Some(serde_json::json!({
                        "seq": rev.seq,
                        "old_hash": rev.old_hash,
                        "new_hash": rev.new_hash,
                    }));
                }
                Err(e) => {
                    tracing::warn!(error = %e, "revision chain record failed for {id_str}");
                    revision_disclosure = Some(serde_json::json!({"record_failed": e.to_string()}));
                }
            }
        }

        // Phase 3 secrets hygiene: an update that introduces credential-
        // shaped content gets the same boundary warning as memory.create.
        let cred_kinds = args
            .get("content")
            .and_then(serde_json::Value::as_str)
            .map(wm_memory::credential_shaped_content)
            .unwrap_or_default();

        // mcp-input-boundary (2026-09-21): instruction-shaped content is
        // flagged (never rejected) exactly like credential-shaped content.
        let instruction_pattern = wm_memory::detect_injection(&mem.content);

        // Re-index in Tantivy if search engine is available (non-fatal, but a
        // failure is recorded in the durable pending-index ledger).
        super::common::replace_memory_index(&self.store, self.search.as_deref(), &mem);

        let mut response = json!({
            "status": "success",
            "id": mem.metadata.id,
            "galaxy": galaxy_name(galaxy),
            "tags": mem.metadata.tags,
            "importance": mem.metadata.importance,
            // V8 S11a: the write-audit journal scrapes `content_hash` from
            // tool output (pipeline record_write_audit), so disclosing it
            // here gives every update a hash-timeline journal entry;
            // `prev_content_hash` is the agent/human-facing amendment trail.
            "content_hash": mem.metadata.content_hash,
        });
        if content_changed {
            response["prev_content_hash"] = json!(previous_hash);
        }
        if let Some(rev) = revision_disclosure {
            response["revision"] = rev;
        }
        if !cred_kinds.is_empty() || instruction_pattern.is_some() {
            let mut warnings: Vec<String> = cred_kinds
                .iter()
                .map(|k| {
                    format!(
                        "content looks like a credential ({k}) — {}",
                        wm_memory::CREDENTIAL_ADVICE
                    )
                })
                .collect();
            if let Some(pattern) = instruction_pattern {
                warnings.push(format!(
                    "content contains an instruction-shaped pattern ({pattern}) — stored as data; \
                     review it before trusting it as context"
                ));
            }
            response["warnings"] = json!(warnings);
        }
        Ok(response)
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.revisions` — list or verify a memory's content revision chain
/// (V8 S11c).
///
/// `action: "list"` returns the entries; `action: "verify"` grades the
/// chain against the memory's current content hash (seq continuity, hash
/// linkage, head match) — the tamper-evidence walk.
pub struct MemoryRevisionsTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryRevisionsTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow {
                reads: super::common::memory_galaxy_reads(),
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryRevisionsTool {
    fn name(&self) -> &str {
        "memory.revisions"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "List or verify a memory's content revision chain (tamper evidence)"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "id": super::common::str_prop("Memory UUID to inspect"),
                "action": super::common::str_prop("Action: list (default) | verify"),
                "galaxy": super::common::str_prop("Galaxy (default: codex)"),
            }),
            &["id"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let id_str = args
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("Missing 'id'".into()))?;
        let id = uuid::Uuid::parse_str(id_str)
            .map_err(|e| wm_core::CoreError::InvalidArgs(format!("Invalid UUID: {e}")))?;
        let action = args
            .get("action")
            .and_then(|v| v.as_str())
            .unwrap_or("list");
        let revisions = self.store.revisions(galaxy, id)?;
        match action {
            "verify" => {
                let mem = self.store.get(galaxy, id)?.ok_or_else(|| {
                    wm_core::CoreError::NotFound(format!(
                        "Memory {id} not found in {}",
                        galaxy_name(galaxy)
                    ))
                })?;
                let report =
                    self.store
                        .verify_revision_chain(galaxy, id, &mem.metadata.content_hash)?;
                Ok(json!({
                    "status": "success",
                    "id": id,
                    "galaxy": galaxy_name(galaxy),
                    "action": "verify",
                    "valid": report.valid,
                    "entries": report.entries,
                    "matches_head": report.matches_head,
                    "breaks": report.breaks,
                    "note": if report.entries == 0 {
                        "no revisions recorded (never content-updated or pre-S11c)"
                    } else { "" },
                }))
            }
            "list" => Ok(json!({
                "status": "success",
                "id": id,
                "galaxy": galaxy_name(galaxy),
                "action": "list",
                "count": revisions.len(),
                "revisions": revisions,
            })),
            other => Err(wm_core::CoreError::InvalidArgs(format!(
                "Unknown action '{other}' (expected 'list' or 'verify')"
            ))),
        }
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.tag` — add or remove tags from a memory.
pub struct MemoryTagTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryTagTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow {
                writes: super::common::memory_galaxy_writes(),
                reads: super::common::memory_galaxy_reads(),
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryTagTool {
    fn name(&self) -> &str {
        "memory.tag"
    }
    fn gana(&self) -> Gana {
        Gana::Net
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Add or remove tags from a memory"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "id": super::common::str_prop("Memory UUID to tag"),
                "tags": super::common::str_array_prop("Tags to apply"),
                "action": super::common::str_prop("Action: add (default) | remove"),
                "galaxy": super::common::str_prop("Galaxy (default: codex)"),
            }),
            &["id", "tags"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let id_str = args
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("Missing 'id'".into()))?;
        let id = uuid::Uuid::parse_str(id_str)
            .map_err(|e| wm_core::CoreError::InvalidArgs(format!("Invalid UUID: {e}")))?;
        let mut mem = self
            .store
            .get(galaxy, id)?
            .ok_or_else(|| wm_core::CoreError::NotFound(format!("Memory {id} not found")))?;
        let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("add");
        let tags = args
            .get("tags")
            .and_then(|v| v.as_array())
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("Missing 'tags' array".into()))?;
        let tag_list: Vec<String> = tags
            .iter()
            .filter_map(|t| t.as_str().map(String::from))
            .collect();
        match action {
            "remove" => {
                mem.metadata.tags.retain(|t| !tag_list.contains(t));
            }
            _ => {
                for t in &tag_list {
                    if !mem.metadata.tags.contains(t) {
                        mem.metadata.tags.push(t.clone());
                    }
                }
            }
        }
        self.store.put(galaxy, &mem)?;
        Ok(json!({
            "status": "success",
            "id": mem.metadata.id,
            "action": action,
            "tags": mem.metadata.tags,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.stats` — statistics for a galaxy.
pub struct MemoryStatsTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryStatsTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryStatsTool {
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to summarize (optional; default codex)"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.stats"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Statistics for a galaxy (count, avg importance, tag frequency)"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let memories = self.store.scan(galaxy, 10_000)?;
        let total = memories.len();
        let avg_importance = if total > 0 {
            memories.iter().map(|m| m.metadata.importance).sum::<f32>() / total as f32
        } else {
            0.0
        };
        let mut tag_freq: HashMap<String, u32> = HashMap::new();
        for mem in &memories {
            for tag in &mem.metadata.tags {
                *tag_freq.entry(tag.clone()).or_insert(0) += 1;
            }
        }
        let top_tags: Vec<(String, u32)> = tag_freq.into_iter().filter(|(_, c)| *c >= 2).collect();
        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "count": total,
            "avg_importance": (avg_importance * 100.0).round() / 100.0,
            "tag_clusters": top_tags.len(),
            "top_tags": top_tags.into_iter().take(10).collect::<Vec<_>>(),
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// Shared retrieval implementation used by `memory.search` (public verb)
/// and `memory.hybrid_recall` (compatibility alias).
pub struct MemoryHybridRecallTool {
    store: Arc<MemoryStore>,
    search: Option<Arc<SearchEngine>>,
    recall: Option<Arc<RecallEngine>>,
    associations: Option<Arc<AssociationStore>>,
    stats: ToolStats,
    effects: EffectRow,
    route_name: &'static str,
}

impl MemoryHybridRecallTool {
    pub fn new(
        store: Arc<MemoryStore>,
        search: Option<Arc<SearchEngine>>,
        recall: Option<Arc<RecallEngine>>,
    ) -> Self {
        Self::named("memory.hybrid_recall", store, search, recall)
    }

    /// Public retrieval verb. Same implementation as `memory.hybrid_recall`.
    pub fn as_search(
        store: Arc<MemoryStore>,
        search: Option<Arc<SearchEngine>>,
        recall: Option<Arc<RecallEngine>>,
    ) -> Self {
        Self::named("memory.search", store, search, recall)
    }

    /// Attach the association graph for bounded spreading activation:
    /// top results seed a one-hop expansion over typed links, surfacing
    /// connected memories that lexical search alone cannot reach.
    #[must_use]
    pub fn with_associations(mut self, associations: Option<Arc<AssociationStore>>) -> Self {
        self.associations = associations;
        self
    }

    fn named(
        route_name: &'static str,
        store: Arc<MemoryStore>,
        search: Option<Arc<SearchEngine>>,
        recall: Option<Arc<RecallEngine>>,
    ) -> Self {
        Self {
            store,
            search,
            recall,
            associations: None,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
            route_name,
        }
    }
}

/// `memory.reembed` — backfill per-memory vectors for memories that lack them.
///
/// Dry-run by default (plan only); `dry_run: false` persists vectors.
/// Bounded by `limit` (default 200) so an interactive dispatch never runs
/// unbounded; re-run to continue. Requires a real embedder — the tool
/// refuses to store stub noise.
pub struct MemoryReembedTool {
    recall: Option<Arc<RecallEngine>>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryReembedTool {
    #[must_use]
    pub fn new(recall: Option<Arc<RecallEngine>>) -> Self {
        Self {
            recall,
            stats: ToolStats::default(),
            effects: EffectRow {
                writes: {
                    let mut writes = super::common::memory_galaxy_writes();
                    writes.push(Resource::Galaxy("embeddings".into()));
                    writes
                },
                reads: super::common::memory_galaxy_reads(),
                destructive: false,
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryReembedTool {
    fn name(&self) -> &str {
        "memory.reembed"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
    fn description(&self) -> &str {
        "Backfill per-memory embedding vectors for memories that have none (dry-run by default; requires a real embedder). Bounded by limit; re-run to continue. Populates the persistent vector index used by hybrid recall."
    }
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "galaxy": str_prop("Only this galaxy (optional; default: all memory galaxies)"),
                "limit": int_prop("Maximum vectors to embed this pass (default 200; 0 = no cap)"),
                "dry_run": bool_prop("Plan only, no writes (default true)"),
            }),
            &[],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = match args.get("galaxy").and_then(|v| v.as_str()) {
            Some(name) => Some(parse_galaxy(name)?),
            None => None,
        };
        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .map_or(200usize, |v| v as usize);
        let dry_run = args
            .get("dry_run")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(true);

        let Some(recall) = self.recall.as_ref() else {
            return Ok(json!({
                "status": "error",
                "error": "no real embedder wired in this server — set WM_EMBEDDER_ENDPOINT (or the onnx backend) and restart; memory.reembed will not store stub noise",
            }));
        };
        let report = recall.backfill_embeddings(galaxy, limit, dry_run)?;
        let mut out = serde_json::to_value(&report).unwrap_or_else(|_| json!({}));
        if let Some(obj) = out.as_object_mut() {
            obj.insert("status".into(), json!("success"));
            obj.insert(
                "hint".into(),
                json!(if dry_run {
                    "dry-run only — call again with dry_run: false to persist vectors"
                } else {
                    "vectors persisted; the shared vector index is updated in this process, and restarted processes rehydrate it on first hybrid search"
                }),
            );
        }
        Ok(out)
    }
}

/// Telemetry is evidence, not cognition: unfiltered recall must never surface
/// it, while an explicit galaxy filter (including `galaxy: "telemetry"`) stays
/// the only door. Applies to every retrieval phase — hybrid, episodic, FTS,
/// association expansion, and cold discovery. Regression: v9.1.5 default
/// `memory.search("invalid UUID")` returned RSI friction records from the
/// telemetry galaxy alongside project memory.
fn recall_visible(galaxy: Galaxy, galaxy_explicit: bool) -> bool {
    galaxy_explicit || galaxy != Galaxy::Telemetry
}

/// Build the empty-result guidance message: name where the content actually
/// lives so callers do not hit the "silent zero" class of failure (e.g.
/// stores whose memories live in `sessions`/`research`, not the default
/// `codex`).
fn empty_result_hint(store: &MemoryStore, galaxy: Galaxy) -> String {
    let mut populated: Vec<String> = Vec::new();
    let mut requested_total = 0usize;
    for g in Galaxy::memory_galaxies() {
        if g == galaxy {
            requested_total = store.count(g).unwrap_or(0);
            continue;
        }
        let n = store.count(g).unwrap_or(0);
        if n > 0 {
            populated.push(format!("{} ({})", g.db_name(), n));
        }
    }
    let location = if requested_total == 0 {
        format!("galaxy '{}' contains no memories", galaxy_name(galaxy))
    } else {
        format!(
            "no matches for this query in '{}' ({} memories)",
            galaxy_name(galaxy),
            requested_total
        )
    };
    if populated.is_empty() {
        format!("{location}; the store is empty")
    } else {
        format!(
            "{}; other galaxies with content: {}. Pass an explicit \"galaxy\" to search there.",
            location,
            populated.join(", ")
        )
    }
}

/// Same guidance for the galaxy-unfiltered search (no `galaxy` argument):
/// the query ran everywhere, so the hint reports the overall corpus shape.
fn empty_result_hint_all(store: &MemoryStore) -> String {
    let mut populated: Vec<String> = Vec::new();
    let mut total = 0usize;
    for g in Galaxy::memory_galaxies() {
        let n = store.count(g).unwrap_or(0);
        total += n;
        if n > 0 {
            populated.push(format!("{} ({})", g.db_name(), n));
        }
    }
    if populated.is_empty() {
        "no matches for this query; the store is empty".to_string()
    } else {
        format!(
            "no matches for this query across all memory galaxies ({} total); populated: {}",
            total,
            populated.join(", ")
        )
    }
}

#[async_trait]
impl Tool for MemoryHybridRecallTool {
    fn name(&self) -> &str {
        self.route_name
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Search memories: hybrid BM25+vector fusion with a real embedder; otherwise the episodic deterministic route, falling back to BM25 full-text. Every result discloses recall_mode (hybrid|bm25|episodic|fts|importance|cold|none) — bm25 means the fusion ranked with the vector weight configured to zero (the query embed is skipped when the vector half cannot contribute). memory.hybrid_recall is a compatibility alias."
    }
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "query": str_prop("Full-text query"),
                "galaxy": str_prop("Galaxy filter (optional; default: search all memory galaxies, results labeled; \"all\" is accepted as an alias for the unfiltered default)"),
                "limit": super::common::positive_int_prop("Maximum results (default 10; must be >= 1)"),
                "min_importance": num_prop("Minimum memory importance (0-1)"),
                "min_score": num_prop("Absolute BM25 score floor"),
                "min_score_ratio": num_prop("Relative floor: reject hits below this fraction of the top score"),
                "min_trust": num_prop("Minimum source_trust (0-1): drop results below this trust floor"),
                "include_cold": bool_prop("Opt-in unranked cold recovery (no thaw). Trust/importance floors apply; BM25 floors do not apply to unscored recovery. Search content is scrubbed navigation capped at 8192 characters; read by id/galaxy for the exact original."),
                "cold_scan_limit": int_prop("Maximum cold records to scan when include_cold is set (default 2048)"),
            }),
            &["query"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy_arg = galaxy_search_arg(args.get("galaxy").and_then(|v| v.as_str()));
        let galaxy_explicit = galaxy_arg.is_some();
        let galaxy = parse_galaxy_or(galaxy_arg, Galaxy::Codex)?;
        let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");
        // limit must be >= 1: zero used to reach Tantivy's TopDocs and panic
        // the process (2026-09-19 review). Caller error at the boundary.
        let limit = super::common::positive_usize_arg(&args, "limit", 10)
            .map_err(wm_core::CoreError::InvalidArgs)?;
        let include_cold = args
            .get("include_cold")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        let cold_scan_limit = args
            .get("cold_scan_limit")
            .and_then(serde_json::Value::as_u64)
            .map_or(2048, |v| v.clamp(1, 100_000) as usize);
        let min_importance = super::common::bounded_f64_arg(&args, "min_importance", 0.0, Some(1.0))
            .map_err(wm_core::CoreError::InvalidArgs)?
            .unwrap_or(0.0) as f32;
        // Absolute BM25 floor (0 / absent = disabled). Clients that set a
        // meaningful `minScore` finally get what they asked for. Negative
        // values are a caller error, not a silently disabled floor.
        let min_score = super::common::bounded_f64_arg(&args, "min_score", 0.0, None)
            .map_err(wm_core::CoreError::InvalidArgs)?
            .map(|v| v as f32)
            .filter(|v| *v > 0.0);
        // Relative floor: reject hits below `ratio * top_score`.
        // 0.0 or absent → use default 5%, or disable with an explicit 0.0.
        // Out-of-range values are caller errors (1.0+ previously fell back to
        // the 5% default, silently relaxing a stricter request).
        let min_score_ratio =
            super::common::bounded_f64_arg(&args, "min_score_ratio", 0.0, Some(1.0))
                .map_err(wm_core::CoreError::InvalidArgs)?
                .map_or(Some(0.05), |v| Some(v as f32));
        let mut results = Vec::new();

        // V8.1 trust weighting (evidence-gated): 0.0 = off by default.
        // See wm_memory::trust_weighted_score — enable after the recall
        // benchmark re-run, once heritage source_trust stamps are corrected
        // (wm trust survey / wm trust correct).
        let trust_weight = std::env::var("WM_TRUST_WEIGHT")
            .ok()
            .and_then(|v| v.parse::<f32>().ok())
            .unwrap_or(0.0)
            .clamp(0.0, 1.0);
        // V8 S8 disclosures, populated by Phase 0 when applicable.
        let mut result_extra: Option<serde_json::Value> = None;
        let mut trust_disclosure: Option<serde_json::Value> = None;

        // Recall-mode honesty (V8 ship list #1/#6): which route answered
        // this query is disclosed on the result — hybrid | bm25 | episodic |
        // fts | importance | none.
        let mut recall_mode = "none";
        // Hybrid fusion requires a REAL embedder: with the stub, vector
        // halves are noise, so a stub-wired engine must not claim the
        // hybrid route (the server already refuses to wire one; this gate
        // makes the tool honest even when constructed directly).
        let mut hybrid_available = self
            .recall
            .as_ref()
            .is_some_and(|recall| recall.embedder_is_real());
        // The fusion route with the vector weight configured to zero ranks
        // by BM25 alone (T0 finding F-T0-2: the tool used to disclose
        // `hybrid` regardless). Disclose `bm25` in that case — the label
        // follows the configured weights, not the code path taken.
        let fused_mode = fused_mode_label(
            self.recall
                .as_ref()
                .map_or(1.0, |recall| recall.config().vector_weight),
        );

        // Phase 0: If RecallEngine with a real embedder is available, use
        // hybrid BM25 + vector search for fused ranking. Trust weighting
        // lives INSIDE the fusion since V8 S8 (single application point —
        // applying it again here would double-count); the per-result
        // trust_factor + conformal set disclosure come straight from the
        // engine.
        if hybrid_available {
            let recall = self.recall.as_ref().expect("hybrid_available checked");
            if !query.is_empty() {
                let (hybrid_results, conformal) = recall.hybrid_search_with_disclosure(
                    query,
                    limit * 2,
                    galaxy_explicit.then_some(galaxy),
                );
                for hr in hybrid_results {
                    if !recall_visible(hr.galaxy, galaxy_explicit) {
                        continue;
                    }
                    if let Ok(Some(mem)) = self.store.get(hr.galaxy, hr.memory_id) {
                        if mem.metadata.importance >= min_importance
                            && crate::expansion::common::mcp_visible(&mem)
                            && crate::expansion::common::validity_visible(&mem)
                        {
                            let navigation = wm_memory::scrub_text(&mem.content);
                            results.push(with_navigation_disclosure(
                                json!({
                                    "id": mem.metadata.id,
                                    "galaxy": mem.metadata.galaxy.db_name(),
                                    "content": navigation,
                                    "importance": mem.metadata.importance,
                                    "score": hr.score,
                                    "raw_score": hr.raw_bm25_score,
                                    "trust_factor": hr.trust_factor,
                                    "corroboration": hr.corroboration,
                                    "in_conformal_set": hr.in_conformal_set,
                                    "bm25_score": hr.bm25_score,
                                    "vector_score": hr.vector_score,
                                    "trust": mem.metadata.source_trust,
                                    "source": fused_mode,
                                }),
                                &mem.content,
                            ));
                        }
                    }
                }
                // Set-level calibrated coverage disclosure (V8 S8) —
                // attached whenever conformal mode is configured, honest
                // about `uncalibrated` until feedback exists.
                if let Some(info) = conformal {
                    result_extra = serde_json::to_value(&info).ok();
                }
                if trust_weight > 0.0 {
                    trust_disclosure = Some(json!({
                        "wm_trust_weight": trust_weight,
                        "applied_in": "fuse_results",
                    }));
                }
                if !results.is_empty() {
                    recall_mode = fused_mode;
                }
            }
        }

        // Phase 0b: degradation honesty. A configured embedder that cannot
        // answer (server down, model missing) means the hybrid route is
        // actually unavailable — probe once and fall through to the
        // episodic lane instead of skipping it to FTS. The probe runs only
        // when hybrid produced nothing, so the happy path pays nothing.
        let mut hybrid_degraded: Option<String> = None;
        if hybrid_available && results.is_empty() && !query.is_empty() {
            if let Some(recall) = self.recall.as_ref() {
                if let Err(error) = recall.embedder_probe() {
                    hybrid_degraded = Some(error.to_string());
                    hybrid_available = false;
                }
            }
        }

        // Phase E: the episodic deterministic route (V8 ship list #1) —
        // preferred over plain FTS whenever the hybrid route is
        // unavailable. The episodic lane mirrors every v5 write
        // (capture_explicit_memory), its deterministic scorer measures
        // R@1 0.86 vs the BM25 fallback's 0.64 (LongMemEval-S 50q, S8
        // protocol 2026-09-01), and this wire is exactly the v26
        // "one fast brain" lesson: route to the best machinery by
        // default, disclose which one ran. Falls through to FTS only
        // when episodic yields nothing (legacy stores, empty lane,
        // genuine no-match). Pool 100 mirrors the acceptance protocol
        // (retrieve broad, truncate to `limit` below).
        if results.is_empty() && !query.is_empty() && !hybrid_available {
            const EPISODIC_RECALL_POOL: usize = 100;
            let pool = limit.max(EPISODIC_RECALL_POOL);
            // Degradation is never fatal: an episodic-lane error falls
            // through to the FTS phases like an empty lane would.
            let episodic_hits = match self
                .store
                .episodic()
                .search_with_limits(query, pool, pool, false)
            {
                Ok(hits) => hits,
                Err(error) => {
                    tracing::warn!("episodic default-route search failed: {error}");
                    Vec::new()
                }
            };
            for er in episodic_hits {
                // Record ids mirror the v5 memory id; resolve to carry
                // galaxy/importance/visibility from the source of truth.
                let Some((hit_galaxy, mem)) =
                    resolve_memory_across_galaxies(&self.store, er.record.id)
                else {
                    continue;
                };
                if galaxy_explicit && hit_galaxy != galaxy {
                    continue;
                }
                if !recall_visible(hit_galaxy, galaxy_explicit) {
                    continue;
                }
                if mem.metadata.importance < min_importance
                    || !crate::expansion::common::mcp_visible(&mem)
                    || !crate::expansion::common::validity_visible(&mem)
                {
                    continue;
                }
                let navigation = wm_memory::scrub_text(&mem.content);
                results.push(with_navigation_disclosure(
                    json!({
                        "id": mem.metadata.id,
                        "galaxy": hit_galaxy.db_name(),
                        "content": navigation,
                        "importance": mem.metadata.importance,
                        "score": er.score,
                        "matched_terms": er.matched_terms,
                        "trust": mem.metadata.source_trust,
                        "source": "episodic",
                    }),
                    &mem.content,
                ));
            }
            if !results.is_empty() {
                recall_mode = "episodic";
            }
        }

        // Phase 1: full-text search (OR + token-coverage + score floors)
        // Only run if hybrid search didn't produce results or no RecallEngine
        if results.is_empty() {
            if let Some(ref search) = self.search {
                if !query.is_empty() {
                    let opts = wm_memory::SearchOptions {
                        limit: limit * 2,
                        min_score,
                        relative_floor: min_score_ratio,
                        // Explicit galaxy filters at the index. Without one,
                        // the query runs across every memory galaxy — the
                        // Tantivy query was always galaxy-blind, but hits
                        // were resolved against the default galaxy only,
                        // which silently hid sessions/research/dreams
                        // content (found by the post-cutover federated
                        // verification, 2026-08-29).
                        galaxy: galaxy_explicit.then_some(galaxy),
                        ..wm_memory::SearchOptions::default()
                    };
                    let hits = search.search_opt(query, &opts)?;
                    for hit in hits {
                        if let Ok(id) = uuid::Uuid::parse_str(&hit.memory_id) {
                            // Resolve each hit in the galaxy its index
                            // document declares — with no explicit filter
                            // this is the only correct resolution.
                            let hit_galaxy = if galaxy_explicit {
                                Some(galaxy)
                            } else {
                                wm_core::Galaxy::all()
                                    .into_iter()
                                    .find(|g| g.db_name() == hit.galaxy)
                            };
                            let Some(hit_galaxy) = hit_galaxy else {
                                continue;
                            };
                            if !recall_visible(hit_galaxy, galaxy_explicit) {
                                continue;
                            }
                            if let Ok(Some(mem)) = self.store.get(hit_galaxy, id) {
                                if mem.metadata.importance >= min_importance
                                    && crate::expansion::common::mcp_visible(&mem)
                                    && crate::expansion::common::validity_visible(&mem)
                                {
                                    let navigation = wm_memory::scrub_text(&mem.content);
                                    results.push(with_navigation_disclosure(
                                        json!({
                                            "id": mem.metadata.id,
                                            "galaxy": hit_galaxy.db_name(),
                                            "content": navigation,
                                            "importance": mem.metadata.importance,
                                            "score": wm_memory::trust_weighted_score(
                                                hit.score,
                                                mem.metadata.source_trust,
                                                trust_weight,
                                            ),
                                            "raw_score": hit.score,
                                            "normalized_score": hit.normalized_score,
                                            "trust": mem.metadata.source_trust,
                                            "source": "fts",
                                        }),
                                        &mem.content,
                                    ));
                                    if recall_mode == "none" {
                                        recall_mode = "fts";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // Phase 2: only when NO query was given, return by importance.
        // (With a query, empty results are final — a score threshold must
        // not be bypassed by a scan-based fallback.)
        if results.is_empty() && query.is_empty() {
            let mut memories = self.store.scan(galaxy, 100)?;
            memories.sort_by(|a, b| {
                b.metadata
                    .importance
                    .partial_cmp(&a.metadata.importance)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            for mem in memories
                .iter()
                .filter(|m| {
                    m.metadata.importance >= min_importance
                        && crate::expansion::common::mcp_visible(m)
                        && crate::expansion::common::validity_visible(m)
                })
                .take(limit)
            {
                results.push(json!({
                    "id": mem.metadata.id,
                    "content": &mem.content,
                    "importance": mem.metadata.importance,
                    "trust": mem.metadata.source_trust,
                    "score": mem.metadata.importance,
                    "source": "importance",
                    "content_representation": "verbatim",
                    "content_truncated": false,
                    "content_scrubbed": false,
                    "exact_read_available": true,
                }));
                if recall_mode == "none" {
                    recall_mode = "importance";
                }
            }
        }
        // Phase 3: bounded spreading activation over the association graph.
        // Top seeds from Phases 0-2 activate their one-hop neighbors; neighbors
        // surface as discounted results marked source=association. Read-only:
        // no Hebbian writes, one hop, at most 5 expansions.
        if !results.is_empty() {
            if let Some(assoc_store) = &self.associations {
                let mut anchors: Vec<(uuid::Uuid, f32)> = results
                    .iter()
                    .filter_map(|r| {
                        let id = r.get("id")?.as_str()?;
                        uuid::Uuid::parse_str(id).ok().map(|u| {
                            (
                                u,
                                r.get("score")
                                    .and_then(serde_json::Value::as_f64)
                                    .unwrap_or(0.0) as f32,
                            )
                        })
                    })
                    .collect();
                anchors.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
                anchors.dedup_by(|a, b| a.0 == b.0);
                anchors.truncate(5);

                let mut expansions: Vec<(uuid::Uuid, f32, f32, String, uuid::Uuid)> = Vec::new();
                for (seed_id, seed_score) in &anchors {
                    let mut links = Vec::new();
                    if let Ok(outgoing) = assoc_store.find_from(self.store.env(), *seed_id) {
                        links.extend(outgoing);
                    }
                    if let Ok(incoming) = assoc_store.find_to(self.store.env(), *seed_id) {
                        links.extend(incoming);
                    }
                    for assoc in links {
                        if assoc.weight < 0.05 {
                            continue;
                        }
                        let neighbor = if assoc.target == *seed_id {
                            assoc.source
                        } else {
                            assoc.target
                        };
                        let score = seed_score * assoc.weight * 0.5;
                        if score <= 0.0 {
                            continue;
                        }
                        expansions.push((
                            neighbor,
                            score,
                            assoc.weight,
                            assoc.link_type.as_str().to_string(),
                            *seed_id,
                        ));
                    }
                }
                expansions.sort_by(|a, b| {
                    b.1.partial_cmp(&a.1)
                        .unwrap_or(std::cmp::Ordering::Equal)
                        .then_with(|| a.0.cmp(&b.0))
                });
                expansions.dedup_by(|a, b| a.0 == b.0);
                expansions.truncate(5);

                let direct_ids: Vec<String> = results
                    .iter()
                    .filter_map(|r| {
                        r.get("id")
                            .and_then(serde_json::Value::as_str)
                            .map(String::from)
                    })
                    .collect();
                for (neighbor_id, score, weight, link_type, seed_id) in expansions {
                    if direct_ids.iter().any(|id| id == &neighbor_id.to_string()) {
                        continue;
                    }
                    let Some((_, mem)) = resolve_memory_across_galaxies(&self.store, neighbor_id)
                    else {
                        continue;
                    };
                    if !recall_visible(mem.metadata.galaxy, galaxy_explicit) {
                        continue;
                    }
                    if mem.metadata.importance < min_importance
                        || !crate::expansion::common::mcp_visible(&mem)
                        || !crate::expansion::common::validity_visible(&mem)
                    {
                        continue;
                    }
                    let navigation = wm_memory::scrub_text(&mem.content);
                    results.push(with_navigation_disclosure(
                        json!({
                            "id": mem.metadata.id,
                            "content": navigation,
                            "importance": mem.metadata.importance,
                            "trust": mem.metadata.source_trust,
                            "score": score,
                            "weight": weight,
                            "link_type": link_type,
                            "via": seed_id.to_string(),
                            "source": "association",
                        }),
                        &mem.content,
                    ));
                }
            }
        }
        // Trust weighting re-orders (Phase 1 pushed in Tantivy's
        // unweighted order); re-sort so the cut at `limit` is honest.
        if trust_weight > 0.0 {
            results.sort_by(|a, b| {
                b.get("score")
                    .and_then(serde_json::Value::as_f64)
                    .partial_cmp(&a.get("score").and_then(serde_json::Value::as_f64))
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
        }
        // V8 T-b: explicit trust floor — a FILTER, not a ranking weight
        // (WM_TRUST_WEIGHT reorders; min_trust removes). Post-resolution
        // on every route: results carry `trust`, so the floor applies
        // uniformly, including the trust-inert episodic route. Out-of-range
        // values are caller errors — watching a "stricter" floor silently
        // disable itself is exactly the failure this validation prevents.
        let min_trust = super::common::bounded_f64_arg(&args, "min_trust", 0.0, Some(1.0))
            .map_err(wm_core::CoreError::InvalidArgs)?;
        let pre_filter = results.len();
        if let Some(min) = min_trust {
            results.retain(
                |r| match r.get("trust").and_then(serde_json::Value::as_f64) {
                    Some(t) => (t as f32) >= min as f32,
                    None => false,
                },
            );
        }
        let min_trust_filtered = pre_filter - results.len();
        results.truncate(limit);
        // Empty-result guidance: when a query matched nothing, tell the caller
        // where the content actually lives. Prevents the "silent zero" class
        // of failure (e.g. stores like the vault whose memories live in
        // `sessions`/`research`, not the default `codex`).
        // Cold discovery (opt-in, bounded, identity-bound): hydrate and
        // authorize candidates from the cold payload rather than trusting
        // stale index entries. Private records never surface over MCP;
        // superseded and tamper-failing records are refused; nothing is
        // thawed or mutated. Appended only after hot routes settle, and
        // only into remaining `limit` headroom.
        let cold_discovery: Option<serde_json::Value> = if include_cold && !query.is_empty() {
            let terms: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
            let remaining = limit.saturating_sub(results.len());
            if remaining == 0 {
                Some(
                    json!({"enabled":true,"scanned":0,"candidates":0,"matched":0,"appended":0,"integrity_rejected":0,"private_skipped":0,"non_current_skipped":0,"eligibility_skipped":0,"stop_reason":"no_headroom","exhausted":false,"no_thaw":true,"ranked":false,"scan_order":"uuid_key","score_floors":"not_applicable_unscored_recovery"}),
                )
            } else {
                let existing: std::collections::HashSet<String> = results
                    .iter()
                    .filter_map(|r| {
                        r.get("id")
                            .and_then(serde_json::Value::as_str)
                            .map(str::to_string)
                    })
                    .collect();
                let outcome = self.store.find_cold_matching_eligible(
                    &terms,
                    if galaxy_explicit { Some(galaxy) } else { None },
                    remaining,
                    cold_scan_limit,
                    |mem| {
                        recall_visible(mem.metadata.galaxy, galaxy_explicit)
                            && mem.metadata.importance >= min_importance
                            && min_trust
                                .is_none_or(|floor| f64::from(mem.metadata.source_trust) >= floor)
                            && !existing.contains(&mem.metadata.id.to_string())
                    },
                )?;
                let mut appended = 0usize;
                for record in &outcome.records {
                    if appended >= remaining {
                        break;
                    }
                    let id = record.id.to_string();
                    if existing.contains(&id) {
                        continue;
                    }
                    let mem = record.decompress()?;
                    let navigation = wm_memory::search::scrub_text(&mem.content);
                    results.push(with_navigation_disclosure(
                        json!({
                            "id": id,
                            "galaxy": mem.metadata.galaxy.db_name(),
                            "content": navigation,
                            "importance": mem.metadata.importance,
                            "trust": mem.metadata.source_trust,
                            "score": serde_json::Value::Null,
                            "source": "cold",
                            "cold": true,
                            "integrity": "verified",
                            "model_visible": !mem.metadata.model_exclude,
                            "tags": &mem.metadata.tags,
                        }),
                        &mem.content,
                    ));
                    appended += 1;
                }
                if appended > 0 && recall_mode == "none" {
                    recall_mode = "cold";
                }
                Some(json!({
                    "enabled": true,
                    "scanned": outcome.scanned,
                    "candidates": outcome.candidates,
                    "matched": outcome.matched,
                    "appended": appended,
                    "integrity_rejected": outcome.integrity_rejected,
                    "private_skipped": outcome.private_skipped,
                    "non_current_skipped": outcome.non_current_skipped,
                    "eligibility_skipped": outcome.eligibility_skipped,
                    "stop_reason": outcome.stop_reason,
                    "exhausted": outcome.stop_reason == wm_memory::cold_storage::ColdDiscoveryStop::Exhausted,
                    "ranked": false,
                    "scan_order": "uuid_key",
                    "score_floors": "not_applicable_unscored_recovery",
                    "no_thaw": true,
                }))
            }
        } else {
            None
        };
        let evidence_bundle = build_evidence_bundle(&self.store, &results);
        // Token-ledger v0 (2026-09-21): recall rows — what the store held vs
        // what actually entered context. Local-only diagnostic; attribution
        // rules in docs/TOKEN_LEDGER.md (cache is context, memory is
        // attribution).
        let bytes_injected: usize = results
            .iter()
            .filter_map(|r| r.get("content").and_then(serde_json::Value::as_str))
            .map(str::len)
            .sum();
        let bytes_available: usize = results
            .iter()
            .filter_map(|r| r.get("id").and_then(serde_json::Value::as_str))
            .filter_map(|id| uuid::Uuid::parse_str(id).ok())
            .filter_map(|id| resolve_memory_across_galaxies(&self.store, id))
            .map(|(_, mem)| mem.content.len())
            .sum();
        super::common::append_savings_row(
            &self.store,
            &json!({
                "ts_ms": wm_core::time::now_unix_millis(),
                "op": "recall",
                "tool": self.route_name,
                "recall_mode": recall_mode,
                "results": results.len(),
                "bytes_available": bytes_available,
                "bytes_injected": bytes_injected,
            }),
        );
        let hint = if results.is_empty() && !query.is_empty() {
            Some(if galaxy_explicit {
                empty_result_hint(&self.store, galaxy)
            } else {
                empty_result_hint_all(&self.store)
            })
        } else {
            None
        };
        let mut out = json!({
            "status": "success",
            "galaxy": if galaxy_explicit {
                serde_json::Value::from(galaxy_name(galaxy))
            } else {
                serde_json::Value::from("all")
            },
            "count": results.len(),
            "recall_mode": recall_mode,
            "results": results,
            "hint": hint,
        });
        // V8 S8 disclosures: the conformal set claim (active/uncalibrated)
        // and, when the trust knob is on, where the weighting was applied.
        if let Some(extra) = result_extra {
            out["conformal_set"] = extra;
        }
        if let Some(td) = trust_disclosure {
            out["trust_weighting"] = td;
        }
        // Degradation disclosure: the configured embedder failed its probe,
        // so the route fell through to the episodic lane. Named so callers
        // do not misread "no matches" as "nothing exists".
        if let Some(reason) = hybrid_degraded {
            out["hybrid_degraded"] = json!(reason);
        }
        if let Some(min) = min_trust {
            out["min_trust"] = json!(min);
            out["min_trust_filtered"] = json!(min_trust_filtered);
        }
        if let Some(cd) = cold_discovery {
            out["cold_discovery"] = cd;
        }
        out["evidence_bundle"] = evidence_bundle;
        if !query.is_empty() && results.is_empty() {
            out["abstention"] = json!({
                "status": "insufficient_evidence",
                "reason": "no_results_above_floors",
                "scope": "retrieval",
            });
        } else if !query.is_empty() {
            // Absolute-evidence gate (hosted-lane finding, 2026-09-22): per-query
            // normalization makes the top hit score 1.0 no matter how weak the
            // match, so nonsense queries look confident. `raw_score` on each
            // result is the absolute signal; these opt-in knobs turn it into an
            // explicit abstention object without dropping results.
            if let Some(abstention) = weak_evidence_abstention(&results, query) {
                out["abstention"] = abstention;
            }
        }
        Ok(out)
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.recall_feedback` — record relevance feedback into the recall
/// engine's conformal calibrator (V8 S8).
///
/// This is how retrieval earns the right to claim coverage: explicit
/// labels (human feedback or a harness with ground truth) become
/// calibration samples; results then carry set membership against a
/// threshold with a real guarantee. Refuses honestly when
/// `WM_RECALL_CONFORMAL_ALPHA` is unset — there is no calibrated set to
/// feed.
pub struct MemoryRecallFeedbackTool {
    recall: Option<Arc<RecallEngine>>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryRecallFeedbackTool {
    #[must_use]
    pub fn new(recall: Option<Arc<RecallEngine>>) -> Self {
        Self {
            recall,
            stats: ToolStats::default(),
            // Persists the fitted classifier JSON to the store root when
            // the calibrator crosses its fit threshold — a filesystem
            // write outside LMDB, declared as a capability (usage is
            // conditional on WM_RECALL_CONFORMAL_ALPHA + fit state).
            effects: EffectRow {
                writes: vec![Resource::Filesystem],
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryRecallFeedbackTool {
    fn name(&self) -> &str {
        "memory.recall_feedback"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Record relevance feedback for conformal retrieval calibration (V8 S8). Args: samples (array of {score: number 0-1, relevant: bool}) or score+relevant for a single sample. Requires WM_RECALL_CONFORMAL_ALPHA."
    }
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "samples": {"type": "array", "items": {"type": "object"}, "description": "Feedback samples: [{score: 0-1 fused score, relevant: bool}]"},
                "score": num_prop("Single-sample fused score (0-1)"),
                "relevant": {"type": "boolean", "description": "Single-sample relevance label"},
            }),
            &[],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let Some(ref recall) = self.recall else {
            return Ok(json!({
                "status": "error",
                "message": "no recall engine on this server (hybrid search unavailable) — nothing to calibrate",
            }));
        };
        let mut samples: Vec<(f32, bool)> = Vec::new();
        if let Some(list) = args.get("samples").and_then(Value::as_array) {
            for s in list {
                let score = s.get("score").and_then(Value::as_f64).unwrap_or(-1.0);
                let relevant = s.get("relevant").and_then(Value::as_bool);
                if !(0.0..=1.0).contains(&score) || relevant.is_none() {
                    return Err(wm_core::CoreError::InvalidArgs(
                        "each sample needs score in [0,1] and a boolean 'relevant'".into(),
                    ));
                }
                samples.push((score as f32, relevant.unwrap_or(false)));
            }
        } else if let Some(score) = args.get("score").and_then(Value::as_f64) {
            let relevant = args
                .get("relevant")
                .and_then(Value::as_bool)
                .ok_or_else(|| {
                    wm_core::CoreError::InvalidArgs("'relevant' is required with 'score'".into())
                })?;
            if !(0.0..=1.0).contains(&score) {
                return Err(wm_core::CoreError::InvalidArgs(
                    "'score' must be within [0,1]".into(),
                ));
            }
            samples.push((score as f32, relevant));
        } else {
            return Err(wm_core::CoreError::InvalidArgs(
                "provide 'samples' (array of {score, relevant}) or a single 'score' + 'relevant'"
                    .into(),
            ));
        }

        let mut recorded = 0usize;
        let mut count = 0usize;
        for (score, relevant) in samples {
            count = recall.record_relevance_feedback(score, relevant)?;
            recorded += 1;
        }
        // Honest post-state disclosure so the caller can see whether the
        // calibrator crossed its fit threshold.
        let status = recall
            .conformal_disclosure(&mut Vec::new())?
            .map_or_else(|| "off".into(), |info| info.status);
        Ok(json!({
            "status": "success",
            "recorded": recorded,
            "calibration_samples": count,
            "conformal_status": status,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.episodic_search` — v6 raw episodic search for controlled evaluation.
///
/// This route is explicit-only and is not part of the curated v5 surface.
pub struct MemoryEpisodicSearchTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryEpisodicSearchTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("episodic_records".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryEpisodicSearchTool {
    fn name(&self) -> &str {
        "memory.episodic_search"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "[V6 Experimental] Search explicit episodic records with provenance and lifecycle filtering"
    }
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "query": str_prop("Full-text query"),
                "limit": int_prop("Maximum results (default 10)"),
                "candidate_limit": int_prop("Maximum candidates to score (default 2x limit). This is the deterministic retrieval width — keep it wide for tail recall; bound rerank embedding cost with rerank_pool instead (measured on the 50q set: wide retrieval + small pool beat narrowed retrieval on R@1 and R@10)"),
                "include_historical": {
                    "type": "boolean",
                    "description": "Include superseded, revoked, and archived records",
                },
                "rerank": {
                    "type": "boolean",
                    "description": "Enable vector reranking (requires embedder, default false)",
                },
                "rerank_alpha": {
                    "type": "number",
                    "description": "Rerank mode selector (default 0.7): <1.0 hybrid blend weight; >=1.0 near-tie cosine tiebreaker; >=2.0 protected top-K full cosine reorder (recall@limit preserved by construction when the candidate set is not narrowed). Blending alphas can drop correct items out of top-K — prefer >=2.0 when recall@limit matters",
                },
                "rerank_pool": int_prop("Embedding/reorder width for rerank (default 0 = auto: min(50, max(limit, candidate_limit)), capped at 50). Lower it on CPU embedders to cut latency without narrowing candidate_limit (the deterministic retrieval width)"),
                "min_score": {
                    "type": "number",
                    "description": "Minimum score threshold; results below this are dropped (abstention). Default 0.0 (no threshold)",
                },
                "min_coverage": {
                    "type": "number",
                    "description": "Minimum query-term coverage ratio (0.0-1.0); results with lower coverage are dropped. E.g. 0.5 requires at least half the query terms to match. Default 0.0 (no threshold)",
                },
            }),
            &["query"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let query = args.get("query").and_then(Value::as_str).unwrap_or("");
        let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(10) as usize;
        let candidate_limit =
            args.get("candidate_limit")
                .and_then(Value::as_u64)
                .unwrap_or_else(|| limit.saturating_mul(2) as u64) as usize;
        let include_historical = args
            .get("include_historical")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let rerank = args.get("rerank").and_then(Value::as_bool).unwrap_or(false);
        let rerank_alpha = args
            .get("rerank_alpha")
            .and_then(Value::as_f64)
            .unwrap_or(0.7) as f32;
        let rerank_pool = args.get("rerank_pool").and_then(Value::as_u64).unwrap_or(0) as usize;
        let min_score = args
            .get("min_score")
            .and_then(Value::as_f64)
            .map(|v| v as f32);
        let min_coverage = args
            .get("min_coverage")
            .and_then(Value::as_f64)
            .map(|v| v as f32);
        // Compute query content-term count for coverage ratio.
        // We use a simple split on non-alphanumeric after removing common
        // stopwords, matching the episodic search tokenization.
        let query_term_count: usize = {
            const STOPWORDS: &[&str] = &[
                "the", "a", "an", "is", "are", "was", "were", "be", "been", "being", "have", "has",
                "had", "do", "does", "did", "will", "would", "could", "should", "may", "might",
                "must", "can", "shall", "to", "of", "in", "on", "at", "by", "for", "with", "about",
                "as", "into", "like", "through", "after", "over", "between", "out", "against",
                "during", "without", "before", "under", "around", "among", "i", "me", "my", "we",
                "us", "our", "you", "your", "he", "him", "his", "she", "her", "it", "its", "they",
                "them", "their", "what", "whats", "who", "when", "where", "why", "how", "and",
                "or", "but", "not", "no", "nor", "so", "yet", "both", "either", "neither", "this",
                "that", "these", "those", "there", "here", "now", "then", "than",
            ];
            query
                .split(|c: char| !c.is_alphanumeric())
                .filter(|t| t.len() > 1)
                .map(str::to_ascii_lowercase)
                .filter(|t| !STOPWORDS.contains(&t.as_str()))
                .collect::<std::collections::HashSet<_>>()
                .len()
        };
        let raw_results = if rerank {
            self.store.episodic().search_with_rerank(
                query,
                limit,
                candidate_limit,
                include_historical,
                rerank_alpha,
                rerank_pool,
            )?
        } else {
            self.store.episodic().search_with_limits(
                query,
                limit,
                candidate_limit,
                include_historical,
            )?
        };
        // Coverage-based abstention: if the query has 3+ content terms and
        // NO result matches 2+ terms, all matches are likely on a single
        // generic term (e.g. "favorite") rather than the actual topic.
        // In that case, abstain entirely. If even one result matches 2+
        // terms, keep all results (the query has real matches in the haystack).
        // Skip abstention for count-style queries ("how many") since they
        // need all candidates for count verification.
        let is_count_query = query.to_ascii_lowercase().contains("how many");
        let abstain = min_coverage.is_some()
            && !is_count_query
            && query_term_count >= 3
            && !raw_results.iter().any(|hit| hit.matched_terms >= 2);
        let visible: Vec<_> = raw_results
            .into_iter()
            .filter(|hit| !hit.record.is_private && !hit.record.model_exclude)
            .filter(|hit| min_score.is_none_or(|ms| hit.score >= ms))
            .filter(|_| !abstain)
            .take(limit)
            .collect();
        // Read-time contradiction detection over the visible results only
        // (TANGLE semantics: surface both sides with provenance, never
        // silently resolve).
        let conflicts = detect_conflicts(&visible);
        let results = visible
            .into_iter()
            .map(|hit| {
                json!({
                    "id": hit.record.id,
                    "content": wm_memory::scrub_text(&hit.record.content),
                    "score": hit.score,
                    "matched_terms": hit.matched_terms,
                    "session_id": hit.record.session_id,
                    "sequence": hit.record.sequence,
                    "created_at": hit.record.created_at,
                    "validity": hit.record.validity,
                    "provenance": hit.record.provenance,
                    "source": "episodic",
                })
            })
            .collect::<Vec<_>>();
        Ok(json!({
            "status": "success",
            "count": results.len(),
            // Temporal resolution: true when the query asked for the
            // current/latest value and the topic cluster was reordered by
            // deterministic chronology (see episodic::resolve_current).
            "current_resolution": wm_memory::episodic::is_current_query(query),
            // Detected contradictions among the results, when any: both
            // statements with provenance; the caller decides (TANGLE).
            "conflicts": conflicts,
            "results": results,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.aggregate` — post-retrieval aggregation over matching memories.
///
/// Retrieves memories with a full-text query (same BM25 path as
/// `memory.search`) and computes an aggregate over the results. Session
/// metrics derive from `session_<n>` tags (a common client convention),
/// letting callers answer cross-session synthesis questions like "how long
/// from X to Y" without scanning raw results themselves.
///
/// For span metrics, the anchor set is narrowed to results matching the
/// rarest query term (fewest matches, ties broken by query order) so that
/// unrelated-but-similar turns (e.g. the same question about a different
/// skill) do not distort the span.
pub struct MemoryAggregateTool {
    search: Option<Arc<SearchEngine>>,
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryAggregateTool {
    pub fn new(search: Option<Arc<SearchEngine>>, store: Arc<MemoryStore>) -> Self {
        Self {
            search,
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

/// Extract a session ordinal from `session_<n>` tags.
fn session_ordinal(tags: &[String]) -> Option<u64> {
    tags.iter().find_map(|tag| {
        let rest = tag.strip_prefix("session_")?;
        rest.parse::<u64>().ok()
    })
}

/// Word-boundary match of a lowercase query term against content (with a
/// light suffix-stripped variant for morphological tolerance).
fn contains_term(content: &str, term: &str) -> bool {
    let lowered = content.to_ascii_lowercase();
    let variants = [term.to_string(), strip_suffix(term)];
    for variant in &variants {
        if variant.len() < 2 {
            continue;
        }
        let mut start = 0;
        while let Some(pos) = lowered[start..].find(variant.as_str()) {
            let before_ok = pos == 0
                || !lowered[start + pos - 1..start + pos]
                    .chars()
                    .next()
                    .is_some_and(char::is_alphanumeric);
            let end = start + pos + variant.len();
            let after_ok = end >= lowered.len()
                || !lowered[end..]
                    .chars()
                    .next()
                    .is_some_and(char::is_alphanumeric);
            if before_ok && after_ok {
                return true;
            }
            start += pos + variant.len();
        }
    }
    false
}

/// Strip a common English suffix for tolerant matching (mirrors the
/// simple stemmer used by the search tokenizer).
fn strip_suffix(term: &str) -> String {
    for suffix in ["ing", "ed", "es", "s"] {
        if let Some(stem) = term.strip_suffix(suffix) {
            if stem.len() >= 2 {
                return stem.to_string();
            }
        }
    }
    term.to_string()
}

#[async_trait]
impl Tool for MemoryAggregateTool {
    fn name(&self) -> &str {
        "memory.aggregate"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Aggregate over memories matching a query: count, distinct session count, or session span (cross-session synthesis)"
    }
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "query": str_prop("Full-text query selecting the memories to aggregate over"),
                "metric": str_prop("Aggregate metric: count | session_count | session_span"),
                "limit": super::common::positive_int_prop("Maximum candidates considered (default 50; must be >= 1)"),
            }),
            &["query", "metric"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let query = args
            .get("query")
            .and_then(Value::as_str)
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("query (string) required".into()))?;
        let metric = args
            .get("metric")
            .and_then(Value::as_str)
            .ok_or_else(|| wm_core::CoreError::InvalidArgs("metric (string) required".into()))?;
        let limit = super::common::positive_usize_arg(&args, "limit", 50)
            .map_err(wm_core::CoreError::InvalidArgs)?;
        let Some(search) = self.search.as_ref() else {
            return Err(wm_core::CoreError::Memory(
                "search engine unavailable for aggregation".into(),
            ));
        };

        let results = search.search(query, limit)?;
        // Load full memories (for tags) and drop non-visible ones.
        let mut memories = Vec::new();
        for r in &results {
            let Some(galaxy) = wm_core::Galaxy::from_db_name(&r.galaxy) else {
                continue;
            };
            let Ok(id) = uuid::Uuid::parse_str(&r.memory_id) else {
                continue;
            };
            let Ok(Some(mem)) = self.store.get(galaxy, id) else {
                continue;
            };
            if super::common::mcp_visible(&mem) && super::common::validity_visible(&mem) {
                memories.push((r.score, mem));
            }
        }

        let evidence: Vec<Value> = memories
            .iter()
            .map(|(score, mem)| {
                json!({
                    "memory_id": mem.metadata.id.to_string(),
                    "score": score,
                    "content": wm_memory::scrub_text(&mem.content),
                    "tags": mem.metadata.tags,
                })
            })
            .collect();

        // Anchor narrowing for session metrics: keep only results matching
        // the rarest query term (fewest matches; ties by query order).
        // Honesty fallbacks (previously both yielded an empty anchor set,
        // reporting session_count 0 / span null DESPITE session-tagged
        // evidence): with fewer than 2 session-tagged hits there is nothing
        // to disambiguate, so the session-tagged set IS the anchor; when no
        // term matches (stopword-only query, vocab mismatch) the same
        // fallback applies. The `anchor` disclosure says which ran.
        let session_tagged: Vec<_> = memories
            .iter()
            .filter(|(_, mem)| session_ordinal(&mem.metadata.tags).is_some())
            .collect();
        let (anchored, anchor): (Vec<_>, &str) = if metric == "count" {
            (Vec::new(), "none")
        } else if session_tagged.len() < 2 {
            (session_tagged.clone(), "session_tagged_fallback")
        } else {
            let terms: Vec<String> = wm_memory::strip_stopwords(query)
                .split(|c: char| !c.is_alphanumeric())
                .filter(|t| t.len() > 1)
                .map(str::to_ascii_lowercase)
                .collect();
            let mut best: Option<(String, usize)> = None;
            for term in &terms {
                let count = session_tagged
                    .iter()
                    .filter(|(_, mem)| contains_term(&mem.content, term))
                    .count();
                if count == 0 {
                    continue;
                }
                let better = best
                    .as_ref()
                    .is_none_or(|(_, best_count)| count < *best_count);
                if better {
                    best = Some((term.clone(), count));
                }
            }
            match best {
                Some((term, _)) => (
                    session_tagged
                        .iter()
                        .filter(|(_, mem)| contains_term(&mem.content, &term))
                        .copied()
                        .collect(),
                    "rarest_term",
                ),
                None => (session_tagged.clone(), "session_tagged_fallback"),
            }
        };

        let aggregate = match metric {
            "count" => json!({
                "metric": "count",
                "value": memories.len(),
                "content": format!("{} memories", memories.len()),
            }),
            "session_count" => {
                let sessions: std::collections::HashSet<u64> = anchored
                    .iter()
                    .filter_map(|(_, mem)| session_ordinal(&mem.metadata.tags))
                    .collect();
                json!({
                    "metric": "session_count",
                    "value": sessions.len(),
                    "content": format!("{} distinct sessions", sessions.len()),
                })
            }
            "session_span" => {
                let ordinals: Vec<u64> = anchored
                    .iter()
                    .filter_map(|(_, mem)| session_ordinal(&mem.metadata.tags))
                    .collect();
                if ordinals.is_empty() {
                    json!({
                        "metric": "session_span",
                        "value": null,
                        "content": "no session-tagged evidence found",
                    })
                } else {
                    let span = ordinals.iter().max().unwrap() - ordinals.iter().min().unwrap();
                    json!({
                        "metric": "session_span",
                        "value": span,
                        "unit": "sessions",
                        "content": format!("{span} sessions"),
                    })
                }
            }
            other => {
                return Err(wm_core::CoreError::InvalidArgs(format!(
                    "unknown metric '{other}' (count | session_count | session_span)"
                )));
            }
        };

        Ok(json!({
            "status": "success",
            "query": query,
            "total": memories.len(),
            "session_tagged": session_tagged.len(),
            "anchor": anchor,
            "limit_hit": results.len() >= limit,
            "aggregate": aggregate,
            "results": evidence,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.sort` — sort memories by importance, recency, or access count.
pub struct MemorySortTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemorySortTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemorySortTool {
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to sort (optional; default codex)"),
                "sort_by": super::common::str_prop("Sort key: importance | created_at | accessed_at | access_count"),
                "order": super::common::str_prop("Order: asc | desc (default desc)"),
                "limit": super::common::int_prop("Maximum entries (default 50)"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.sort"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Sort memories by importance, recency, or access count"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let sort_by = args
            .get("sort_by")
            .and_then(|v| v.as_str())
            .unwrap_or("importance");
        let order = args.get("order").and_then(|v| v.as_str()).unwrap_or("desc");
        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(50) as usize;

        let mut memories = self.store.scan(galaxy, 10_000)?;
        // Private memories never appear in MCP responses. Non-current
        // validity likewise hides while enforced (Slice B, off by default).
        memories.retain(|m| {
            crate::expansion::common::mcp_visible(m)
                && crate::expansion::common::validity_visible(m)
        });

        match sort_by {
            "importance" => memories.sort_by(|a, b| {
                b.metadata
                    .importance
                    .partial_cmp(&a.metadata.importance)
                    .unwrap_or(std::cmp::Ordering::Equal)
            }),
            "recency" => memories.sort_by_key(|x| std::cmp::Reverse(x.metadata.created_at)),
            "accessed" => {
                memories.sort_by_key(|x| std::cmp::Reverse(x.metadata.accessed_at));
            }
            "access_count" => {
                memories.sort_by_key(|x| std::cmp::Reverse(x.metadata.access_count));
            }
            _ => {
                return Err(wm_core::CoreError::InvalidArgs(format!(
                    "Unknown sort_by: '{sort_by}'. Use importance, recency, accessed, or access_count"
                )));
            }
        }

        if order == "asc" {
            memories.reverse();
        }

        let total = memories.len();
        memories.truncate(limit);

        let results: Vec<Value> = memories
            .iter()
            .map(|m| {
                json!({
                    "id": m.metadata.id,
                    "content": &m.content,
                    "importance": m.metadata.importance,
                    "created_at": m.metadata.created_at.to_rfc3339(),
                    "accessed_at": m.metadata.accessed_at.to_rfc3339(),
                    "access_count": m.metadata.access_count,
                    "tags": &m.metadata.tags,
                })
            })
            .collect();

        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "sort_by": sort_by,
            "order": order,
            "total": total,
            "returned": results.len(),
            "memories": results,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.filter` — filter memories by tags, date range, importance.
pub struct MemoryFilterTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryFilterTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryFilterTool {
    fn name(&self) -> &str {
        "memory.filter"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Filter memories by tags, date range, importance thresholds, and a content query substring"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to filter (default codex)"),
                "tags": super::common::str_array_prop("Filter: memories with all of these tags"),
                "exclude_tags": super::common::str_array_prop("Filter: drop memories carrying any of these tags"),
                "min_importance": super::common::num_prop("Filter: minimum importance (0-1)"),
                "max_importance": super::common::num_prop("Filter: maximum importance (0-1)"),
                "query": super::common::str_prop("Filter: every whitespace-separated term must appear (case-insensitive) in the content or title"),
                "created_after": super::common::str_prop("Filter: only memories created at or after this RFC 3339 timestamp (e.g. 2026-08-01T00:00:00Z)"),
                "created_before": super::common::str_prop("Filter: only memories created at or before this RFC 3339 timestamp"),
                "limit": super::common::int_prop("Maximum entries (default 50)"),
                "offset": super::common::int_prop("Skip this many matching entries before returning (default 0)"),
            }),
            &[],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let tags: Vec<String> = args
            .get("tags")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|t| t.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        let exclude_tags: Vec<String> = args
            .get("exclude_tags")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|t| t.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        let min_importance = args
            .get("min_importance")
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(0.0) as f32;
        let max_importance = args
            .get("max_importance")
            .and_then(serde_json::Value::as_f64)
            .unwrap_or(1.0) as f32;
        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(50) as usize;
        let offset = args
            .get("offset")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0) as usize;
        // Date range — promised by the description, previously ignored.
        // Bounds are inclusive RFC 3339 timestamps (e.g. "2026-08-01T00:00:00Z").
        let parse_bound = |name: &str| -> wm_core::Result<Option<chrono::DateTime<chrono::Utc>>> {
            match args.get(name).and_then(|v| v.as_str()) {
                Some(s) if !s.trim().is_empty() => chrono::DateTime::parse_from_rfc3339(s.trim())
                    .map(|t| Some(t.with_timezone(&chrono::Utc)))
                    .map_err(|_| {
                        wm_core::CoreError::InvalidArgs(format!(
                            "{name} must be an RFC 3339 timestamp (e.g. \"2026-08-01T00:00:00Z\"), got: {s}"
                        ))
                    }),
                _ => Ok(None),
            }
        };
        let created_after = parse_bound("created_after")?;
        let created_before = parse_bound("created_before")?;
        // Content query — previously accepted-and-ignored (the arg was
        // silently dropped). Every term must appear case-insensitively in
        // the content or title; empty/absent means no content filtering.
        let query_terms: Vec<String> = args
            .get("query")
            .and_then(|v| v.as_str())
            .map(|q| q.split_whitespace().map(str::to_lowercase).collect())
            .unwrap_or_default();

        let memories = self.store.scan(galaxy, 10_000)?;

        let matched: Vec<&wm_memory::Memory> = memories
            .iter()
            .filter(|m| {
                // Private memories never appear in MCP responses.
                if !crate::expansion::common::mcp_visible(m) {
                    return false;
                }
                // Non-current validity hides while enforced (Slice B).
                if !crate::expansion::common::validity_visible(m) {
                    return false;
                }
                if m.metadata.importance < min_importance || m.metadata.importance > max_importance
                {
                    return false;
                }
                if !tags.is_empty() && !tags.iter().all(|t| m.metadata.tags.contains(t)) {
                    return false;
                }
                if exclude_tags
                    .iter()
                    .any(|t| m.metadata.tags.iter().any(|mt| mt == t))
                {
                    return false;
                }
                if let Some(after) = created_after {
                    if m.metadata.created_at < after {
                        return false;
                    }
                }
                if let Some(before) = created_before {
                    if m.metadata.created_at > before {
                        return false;
                    }
                }
                if !query_terms.is_empty() {
                    let haystack = match &m.metadata.title {
                        Some(title) => format!("{}\n{}", m.content, title).to_lowercase(),
                        None => m.content.to_lowercase(),
                    };
                    if !query_terms.iter().all(|t| haystack.contains(t)) {
                        return false;
                    }
                }
                true
            })
            .collect();
        // Page AFTER filtering: offset/limit address the visible surface.
        let filtered: Vec<&&wm_memory::Memory> = matched.iter().skip(offset).take(limit).collect();

        let total_scanned = memories.len();
        let results: Vec<Value> = filtered
            .iter()
            .map(|m| {
                json!({
                    "id": m.metadata.id,
                    "content": &m.content,
                    "importance": m.metadata.importance,
                    "tags": &m.metadata.tags,
                    "created_at": m.metadata.created_at.to_rfc3339(),
                })
            })
            .collect();

        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "scanned": total_scanned,
            "matched": matched.len(),
            "offset": offset,
            "returned": results.len(),
            "filters": {
                "tags": tags,
                "exclude_tags": exclude_tags,
                "min_importance": min_importance,
                "max_importance": max_importance,
                "query_terms": query_terms,
                "created_after": created_after.map(|t| t.to_rfc3339()),
                "created_before": created_before.map(|t| t.to_rfc3339()),
            },
            "memories": results,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.deduplicate` — find and merge duplicate memories by content similarity.
pub struct MemoryDeduplicateTool {
    store: Arc<MemoryStore>,
    search: Option<Arc<SearchEngine>>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryDeduplicateTool {
    pub fn new(store: Arc<MemoryStore>, search: Option<Arc<SearchEngine>>) -> Self {
        Self {
            store,
            search,
            stats: ToolStats::default(),
            effects: EffectRow {
                writes: super::common::memory_galaxy_writes(),
                reads: super::common::memory_galaxy_reads(),
                destructive: true,
                ..Default::default()
            },
        }
    }
}

#[async_trait]
impl Tool for MemoryDeduplicateTool {
    fn name(&self) -> &str {
        "memory.deduplicate"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Find and merge duplicate memories by content hash or similarity"
    }
    fn input_schema(&self) -> Value {
        super::common::schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to deduplicate"),
                "mode": super::common::str_prop("Strategy: hash | similarity (default: hash)"),
                "limit": super::common::int_prop("Maximum entries to scan"),
                "dry_run": super::common::bool_prop("Preview only (default: true)"),
            }),
            &["galaxy"],
        )
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let mode = args.get("mode").and_then(|v| v.as_str()).unwrap_or("hash");
        let dry_run = args
            .get("dry_run")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(true);
        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(10_000) as usize;

        let memories = self.store.scan(galaxy, limit)?;

        match mode {
            "hash" => {
                let mut seen_hashes: HashMap<String, uuid::Uuid> = HashMap::new();
                let mut duplicates: Vec<Value> = Vec::new();

                for mem in &memories {
                    let hash = &mem.metadata.content_hash;
                    if let Some(existing_id) = seen_hashes.get(hash) {
                        if *existing_id != mem.metadata.id {
                            duplicates.push(json!({
                                "id": mem.metadata.id,
                                "duplicate_of": existing_id,
                                "content_preview": mem.content.chars().take(100).collect::<String>(),
                                "importance": mem.metadata.importance,
                            }));
                            if !dry_run {
                                self.store.delete(galaxy, mem.metadata.id)?;
                                super::common::deindex(
                                    self.search.as_deref(),
                                    &mem.metadata.id.to_string(),
                                );
                            }
                        }
                    } else {
                        seen_hashes.insert(hash.clone(), mem.metadata.id);
                    }
                }

                let removed = if dry_run { 0 } else { duplicates.len() };

                Ok(json!({
                    "status": "success",
                    "galaxy": galaxy_name(galaxy),
                    "mode": mode,
                    "dry_run": dry_run,
                    "scanned": memories.len(),
                    "duplicates_found": duplicates.len(),
                    "removed": removed,
                    "duplicates": duplicates,
                }))
            }
            "content" => {
                let mut duplicates: Vec<Value> = Vec::new();
                let mut removed_count = 0u32;

                for i in 0..memories.len() {
                    for j in (i + 1)..memories.len() {
                        if memories[i].content == memories[j].content {
                            duplicates.push(json!({
                                "id": memories[j].metadata.id,
                                "duplicate_of": memories[i].metadata.id,
                                "content_preview": memories[j].content.chars().take(100).collect::<String>(),
                            }));
                            if !dry_run {
                                self.store.delete(galaxy, memories[j].metadata.id)?;
                                super::common::deindex(
                                    self.search.as_deref(),
                                    &memories[j].metadata.id.to_string(),
                                );
                                removed_count += 1;
                            }
                            break;
                        }
                    }
                }

                Ok(json!({
                    "status": "success",
                    "galaxy": galaxy_name(galaxy),
                    "mode": mode,
                    "dry_run": dry_run,
                    "scanned": memories.len(),
                    "duplicates_found": duplicates.len(),
                    "removed": removed_count,
                    "duplicates": duplicates,
                }))
            }
            _ => Err(wm_core::CoreError::InvalidArgs(format!(
                "Unknown mode: '{mode}'. Use 'hash' or 'content'"
            ))),
        }
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

/// `memory.export` — export memories in JSON, CSV, or Markdown format.
pub struct MemoryExportTool {
    store: Arc<MemoryStore>,
    stats: ToolStats,
    effects: EffectRow,
}

impl MemoryExportTool {
    pub fn new(store: Arc<MemoryStore>) -> Self {
        Self {
            store,
            stats: ToolStats::default(),
            effects: EffectRow::read_only(vec![Resource::Galaxy("codex".into())]),
        }
    }
}

#[async_trait]
impl Tool for MemoryExportTool {
    fn input_schema(&self) -> Value {
        schema(
            &json!({
                "galaxy": super::common::str_prop("Galaxy to export (optional; default codex)"),
                "format": super::common::str_prop("Export format: json | jsonl | markdown"),
                "limit": super::common::int_prop("Maximum entries to export"),
            }),
            &[],
        )
    }
    fn name(&self) -> &str {
        "memory.export"
    }
    fn gana(&self) -> Gana {
        Gana::WinnowingBasket
    }
    fn effects(&self) -> &EffectRow {
        &self.effects
    }
    fn description(&self) -> &str {
        "Export memories in JSON, CSV, or Markdown format"
    }
    async fn call(&self, _ctx: &mut Context, args: Value) -> wm_core::Result<Value> {
        let galaxy = parse_galaxy_or(args.get("galaxy").and_then(|v| v.as_str()), Galaxy::Codex)?;
        let format = args
            .get("format")
            .and_then(|v| v.as_str())
            .unwrap_or("json");
        let limit = args
            .get("limit")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(1000) as usize;

        let memories = self.store.scan(galaxy, limit)?;

        let exported = match format {
            "json" => {
                let entries: Vec<Value> = memories
                    .iter()
                    .map(|m| {
                        json!({
                            "id": m.metadata.id,
                            "content": &m.content,
                            "tags": &m.metadata.tags,
                            "importance": m.metadata.importance,
                            "created_at": m.metadata.created_at.to_rfc3339(),
                            "access_count": m.metadata.access_count,
                        })
                    })
                    .collect();
                serde_json::to_string_pretty(&entries).unwrap_or_default()
            }
            "csv" => {
                let mut csv = String::from("id,content,tags,importance,created_at,access_count\n");
                for m in &memories {
                    let tags = m.metadata.tags.join(";");
                    let content = m.content.replace('\n', " ").replace('"', "'");
                    let _ = writeln!(
                        csv,
                        "{},{},{},{:.3},{},{}",
                        m.metadata.id,
                        content,
                        tags,
                        m.metadata.importance,
                        m.metadata.created_at.to_rfc3339(),
                        m.metadata.access_count,
                    );
                }
                csv
            }
            "markdown" => {
                let mut md = format!("# Memory Export: {}\n\n", galaxy_name(galaxy));
                let _ = write!(md, "Total memories: {}\n\n", memories.len());
                for m in &memories {
                    let _ = write!(
                        md,
                        "## {}\n\n- **Importance**: {:.2}\n- **Tags**: {}\n- **Created**: {}\n- **Access Count**: {}\n\n{}\n\n---\n\n",
                        m.metadata.id,
                        m.metadata.importance,
                        m.metadata.tags.join(", "),
                        m.metadata.created_at.to_rfc3339(),
                        m.metadata.access_count,
                        m.content,
                    );
                }
                md
            }
            _ => {
                return Err(wm_core::CoreError::InvalidArgs(format!(
                    "Unknown format: '{format}'. Use json, csv, or markdown"
                )));
            }
        };

        Ok(json!({
            "status": "success",
            "galaxy": galaxy_name(galaxy),
            "format": format,
            "count": memories.len(),
            "export": exported,
        }))
    }
    fn stats(&self) -> &ToolStats {
        &self.stats
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wm_core::{EpisodicKind, EpisodicRecord, Galaxy, Provenance, ProvenanceSource};
    use wm_memory::{Association, AssociationStore, LinkType, Memory, MemoryStore};

    fn test_store() -> Arc<MemoryStore> {
        let dir = tempfile::tempdir().unwrap();
        Arc::new(MemoryStore::open_default(dir.path()).unwrap())
    }

    fn populate_memories(store: &Arc<MemoryStore>, galaxy: Galaxy) {
        let mut m1 = Memory::new(galaxy, "First memory about rust".into());
        m1.metadata.importance = 0.9;
        m1.metadata.tags = vec!["rust".into(), "programming".into()];
        let _ = store.put(galaxy, &m1);

        let mut m2 = Memory::new(galaxy, "Second memory about python".into());
        m2.metadata.importance = 0.5;
        m2.metadata.tags = vec!["python".into()];
        let _ = store.put(galaxy, &m2);

        let mut m3 = Memory::new(galaxy, "Third memory about rust".into());
        m3.metadata.importance = 0.3;
        m3.metadata.tags = vec!["rust".into(), "tutorial".into()];
        let _ = store.put(galaxy, &m3);
    }

    #[tokio::test]
    async fn episodic_search_filters_private_records() {
        let store = test_store();
        let public = EpisodicRecord::new(
            None,
            1,
            EpisodicKind::Observation,
            "public retrieval evidence",
            Provenance::new(ProvenanceSource::User),
        );
        let private = EpisodicRecord::new(
            None,
            2,
            EpisodicKind::Observation,
            "private retrieval evidence",
            Provenance::new(ProvenanceSource::User),
        )
        .with_visibility(true, false);
        store.episodic().append(&public).unwrap();
        store.episodic().append(&private).unwrap();

        let tool = MemoryEpisodicSearchTool::new(store);
        let mut ctx = Context::default();
        let result = tool
            .call(
                &mut ctx,
                json!({"query": "retrieval evidence", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(result["count"], 1);
        assert_eq!(result["results"][0]["id"], json!(public.id));
    }

    /// Mirror a v5 memory into the episodic lane exactly like the write
    /// path does (capture_explicit_memory): record id = memory id.
    fn mirror_memory(
        store: &Arc<MemoryStore>,
        mem: &Memory,
        session: Option<uuid::Uuid>,
        sequence: u64,
    ) {
        use wm_core::EpisodicCapturePolicy;
        let record = EpisodicRecord::new(
            session,
            sequence,
            EpisodicKind::Observation,
            mem.content.clone(),
            Provenance::new(ProvenanceSource::User),
        )
        .with_id(mem.metadata.id)
        .with_visibility(mem.metadata.is_private, mem.metadata.model_exclude);
        store
            .episodic()
            .append_explicit(&record, EpisodicCapturePolicy::explicit_only())
            .unwrap();
    }

    fn default_search_tool(
        store: Arc<MemoryStore>,
        search: Option<Arc<SearchEngine>>,
    ) -> MemoryHybridRecallTool {
        MemoryHybridRecallTool::as_search(store, search, None)
    }

    #[tokio::test]
    async fn default_route_prefers_episodic_and_discloses_mode() {
        // V8 ship list #1: with no real embedder, memory.search must route
        // through the episodic deterministic machinery by default and
        // disclose `recall_mode: episodic` + per-result `source`.
        let (_dir, store, search) = hybrid_fixture();
        let needle = Memory::new(
            Galaxy::Codex,
            "Kotlin coroutine budget meeting notes".into(),
        );
        let needle_id = needle.metadata.id;
        let other = Memory::new(Galaxy::Codex, "Grocery list eggs and flour".into());
        store.put(Galaxy::Codex, &needle).unwrap();
        store.put(Galaxy::Codex, &other).unwrap();
        mirror_memory(&store, &needle, None, 1);
        mirror_memory(&store, &other, None, 2);

        let tool = default_search_tool(store.clone(), Some(search));
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "kotlin coroutine budget", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v["recall_mode"], "episodic");
        assert_eq!(v["results"][0]["source"], "episodic");
        assert_eq!(v["results"][0]["id"], json!(needle_id.to_string()));
        assert!(v["results"][0]["score"].as_f64().unwrap() > 0.0);
    }

    #[test]
    fn fused_mode_label_follows_the_configured_vector_weight() {
        // F-T0-2: the label follows the weights, not the code path.
        assert_eq!(fused_mode_label(0.3), "hybrid");
        assert_eq!(fused_mode_label(1.0), "hybrid");
        assert_eq!(fused_mode_label(0.0), "bm25");
    }

    #[tokio::test]
    async fn zero_vector_weight_discloses_bm25_not_hybrid() {
        // T0 finding F-T0-2: `bm25-baseline` ran the fusion path with the
        // vector/importance weights zeroed (ranking = BM25) yet disclosed
        // `recall_mode: hybrid` on every result. The disclosure must say
        // bm25 for that configuration.
        let (_dir, store, search) = hybrid_fixture();
        let needle = Memory::new(
            Galaxy::Codex,
            "Kotlin coroutine budget meeting notes".into(),
        );
        let needle_id = needle.metadata.id;
        store.put(Galaxy::Codex, &needle).unwrap();
        wm_memory::reindex::rebuild_index(&store, &search, &[]).unwrap();

        // Any embed call would be a regression: the vector half is inert
        // under this config, so the tool path must answer from BM25 alone
        // (F-T0-2 follow-up — before the fast path this config still paid
        // the query embed).
        struct NoEmbedEmbedder;
        impl wm_memory::Embedder for NoEmbedEmbedder {
            fn embed_batch(&self, _texts: &[&str]) -> wm_core::Result<Vec<Vec<f32>>> {
                panic!("zeroed vector weight must not call the embedder");
            }
            fn dimension(&self) -> usize {
                16
            }
            fn is_available(&self) -> bool {
                true
            }
            fn backend_name(&self) -> &'static str {
                "no-embed-test"
            }
        }

        let config = wm_memory::RecallConfig {
            bm25_weight: 1.0,
            vector_weight: 0.0,
            importance_weight: 0.0,
            ..wm_memory::RecallConfig::default()
        };
        let recall = Arc::new(
            RecallEngine::new(
                store.clone(),
                search.clone(),
                wm_memory::VectorStore::new(),
                Arc::new(NoEmbedEmbedder),
                config,
            )
            .unwrap(),
        );
        let tool = MemoryHybridRecallTool::as_search(store.clone(), Some(search), Some(recall));
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "kotlin coroutine budget", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v["recall_mode"], "bm25", "{v}");
        assert_eq!(v["results"][0]["source"], "bm25", "{v}");
        assert_eq!(v["results"][0]["id"], json!(needle_id.to_string()));
    }

    #[tokio::test]
    async fn search_rejects_non_positive_limit() {
        // 2026-09-19 review: limit 0 passed through to Tantivy and panicked
        // the server process (exit 101). The boundary must reject it —
        // zero, negative, and non-integer forms alike — and the boundary
        // value 1 must still work.
        let (_dir, store, search) = hybrid_fixture();
        index_memory(&store, &search, Galaxy::Codex, "kotlin coroutine budget");
        let tool = MemoryHybridRecallTool::as_search(store, Some(search), None);
        let mut ctx = Context::default();
        for bad in [json!(0), json!(-1), json!("0"), json!(0.5)] {
            let err = tool
                .call(&mut ctx, json!({"query": "kotlin", "limit": bad}))
                .await
                .unwrap_err();
            assert!(
                err.to_string().contains("limit"),
                "limit={bad} must be rejected, got: {err}"
            );
        }
        let v = tool
            .call(&mut ctx, json!({"query": "kotlin", "limit": 1}))
            .await
            .unwrap();
        assert_eq!(v["status"], "success", "{v}");
        assert_eq!(v["results"].as_array().map(Vec::len), Some(1), "{v}");
    }

    #[tokio::test]
    async fn default_route_matches_the_episodic_machinery_ranking() {
        // The default route must BE the episodic machinery, not a lookalike:
        // same corpus, same query, first result identical to
        // memory.episodic_search's top hit.
        let (_dir, store, search) = hybrid_fixture();
        let contents = [
            "Deployed the telemetry agent on Tuesday",
            "Cancun trip booked for the twelfth",
            "Telemetry agent rollout postponed to Friday",
            "Deadline for the quarterly report moved",
        ];
        let mut memories: Vec<(uuid::Uuid, &str)> = Vec::new();
        for (i, content) in contents.iter().enumerate() {
            let mem = Memory::new(Galaxy::Codex, (*content).to_string());
            memories.push((mem.metadata.id, content));
            store.put(Galaxy::Codex, &mem).unwrap();
            mirror_memory(&store, &mem, None, i as u64 + 1);
        }
        let query = "when was the telemetry agent deployed";

        let default_tool = default_search_tool(store.clone(), Some(search.clone()));
        let mut ctx = Context::default();
        let default_v = default_tool
            .call(&mut ctx, json!({"query": query, "limit": 10}))
            .await
            .unwrap();
        let episodic_tool = MemoryEpisodicSearchTool::new(store);
        let episodic_v = episodic_tool
            .call(&mut ctx, json!({"query": query, "limit": 10}))
            .await
            .unwrap();
        assert_eq!(
            default_v["results"][0]["id"], episodic_v["results"][0]["id"],
            "default route must rank exactly like the episodic machinery"
        );
        let top = memories
            .iter()
            .find(|(id, _)| id.to_string() == default_v["results"][0]["id"])
            .map(|(_, c)| *c)
            .unwrap();
        assert_eq!(top, "Deployed the telemetry agent on Tuesday");
    }

    #[tokio::test]
    async fn default_route_falls_back_to_fts_when_episodic_yields_nothing() {
        // Legacy store shape: memories indexed but the episodic lane never
        // populated. The default route must disclose `fts` honestly.
        let (_dir, store, search) = hybrid_fixture();
        let mem = Memory::new(Galaxy::Codex, "Zebra quotas revised upward".into());
        let id = mem.metadata.id;
        store.put(Galaxy::Codex, &mem).unwrap();
        {
            let mut writer = search.writer().unwrap();
            search
                .add_document(
                    &mut writer,
                    &id.to_string(),
                    "codex",
                    "Zebra quotas revised upward",
                    &mem.metadata.tags,
                    mem.metadata.created_at.timestamp(),
                )
                .unwrap();
            search.commit(&mut writer).unwrap();
        }

        let tool = default_search_tool(store, Some(search));
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "zebra quotas", "limit": 10}))
            .await
            .unwrap();
        assert_eq!(v["recall_mode"], "fts");
        assert_eq!(v["results"][0]["source"], "fts");
        assert_eq!(v["results"][0]["id"], json!(id.to_string()));
    }

    #[tokio::test]
    async fn episodic_default_route_respects_galaxy_filter() {
        let (_dir, store, search) = hybrid_fixture();
        let in_galaxy = Memory::new(Galaxy::Codex, "Marble fountain restoration plan".into());
        let other_galaxy =
            Memory::new(Galaxy::Sessions, "Marble fountain restoration notes".into());
        store.put(Galaxy::Codex, &in_galaxy).unwrap();
        store.put(Galaxy::Sessions, &other_galaxy).unwrap();
        mirror_memory(&store, &in_galaxy, None, 1);
        mirror_memory(&store, &other_galaxy, None, 2);

        let tool = default_search_tool(store, Some(search));
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "marble fountain", "galaxy": "sessions", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v["recall_mode"], "episodic");
        for r in v["results"].as_array().unwrap() {
            assert_eq!(r["galaxy"], "sessions", "galaxy filter must hold");
        }
        assert_eq!(
            v["results"][0]["id"],
            json!(other_galaxy.metadata.id.to_string())
        );
    }

    #[tokio::test]
    async fn episodic_default_route_filters_private_and_stale() {
        let (_dir, store, search) = hybrid_fixture();
        let public = Memory::new(
            Galaxy::Codex,
            "Lighthouse maintenance schedule confirmed".into(),
        );
        let mut private = Memory::new(Galaxy::Codex, "Lighthouse access code renewal".into());
        private.metadata.is_private = true;
        let stale = Memory::new(Galaxy::Codex, "Lighthouse inspection legacy draft".into());
        let stale_id = stale.metadata.id;
        store.put(Galaxy::Codex, &public).unwrap();
        store.put(Galaxy::Codex, &private).unwrap();
        store.put(Galaxy::Codex, &stale).unwrap();
        mirror_memory(&store, &public, None, 1);
        mirror_memory(&store, &private, None, 2);
        mirror_memory(&store, &stale, None, 3);
        // The stale record's v5 memory is gone — the mirror survived, the
        // source of truth did not.
        store.delete(Galaxy::Codex, stale_id).unwrap();

        let tool = default_search_tool(store, Some(search));
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "lighthouse", "limit": 10}))
            .await
            .unwrap();
        assert_eq!(v["recall_mode"], "episodic");
        let ids: Vec<&str> = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|r| r["id"].as_str())
            .collect();
        assert!(
            !ids.contains(&private.metadata.id.to_string().as_str()),
            "private memories must never surface on the default route"
        );
        assert!(
            !ids.contains(&stale_id.to_string().as_str()),
            "episodic records without a live v5 memory must be skipped"
        );
        assert!(!ids.is_empty(), "the public hit must still surface");
    }

    #[tokio::test]
    async fn memory_sort_by_importance_desc() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemorySortTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"sort_by": "importance", "order": "desc"}))
            .await
            .unwrap();
        assert_eq!(v["status"], "success");
        assert_eq!(v["returned"], 3);
        let mems = v["memories"].as_array().unwrap();
        assert!(mems[0]["importance"].as_f64().unwrap() >= mems[1]["importance"].as_f64().unwrap());
    }

    #[tokio::test]
    async fn memory_update_cannot_mutate_tier() {
        // S5 phase 2: tier moves are dream-cycle-ONLY. The update tool
        // whitelists its fields — a `tier` argument in the payload must be
        // ignored, not applied.
        let store = test_store();
        let mem = Memory::new(Galaxy::Codex, "tier is not client-settable".into());
        let id = mem.metadata.id;
        store.put(Galaxy::Codex, &mem).unwrap();

        let tool = MemoryUpdateTool::new(store.clone(), None);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "id": id.to_string(), "tier": "archival", "tags": ["x"]}),
            )
            .await
            .unwrap();
        assert_eq!(v["status"], "success");

        let after = store.get(Galaxy::Codex, id).unwrap().unwrap();
        assert_eq!(
            after.metadata.tier,
            wm_memory::Tier::Working,
            "memory.update must never move the tier"
        );
        assert_eq!(
            after.metadata.tags,
            vec!["x".to_string()],
            "whitelisted fields still apply"
        );
    }

    #[tokio::test]
    async fn empty_search_hints_at_populated_galaxies() {
        // Content lives in `sessions`, not `codex` (the vault-store shape).
        // The galaxy-unfiltered default (no `galaxy` arg) must FIND it and
        // label the result with its galaxy — that is the post-cutover fix
        // (2026-08-29): hits used to be resolved against `codex` only.
        let (_dir, store, search) = hybrid_fixture();
        index_memory(&store, &search, Galaxy::Sessions, "gate plan decision");
        let tool = MemoryHybridRecallTool::new(store.clone(), Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "gate plan"}))
            .await
            .unwrap();
        assert_eq!(
            v["count"], 1,
            "unfiltered search must find cross-galaxy content: {v}"
        );
        assert_eq!(v["galaxy"], "all");
        assert_eq!(v["results"][0]["galaxy"], "sessions");
        assert!(v["hint"].is_null());

        // An explicit galaxy still filters at the index and hints on a miss.
        let v2 = tool
            .call(
                &mut ctx,
                json!({"query": "zzz-no-match", "galaxy": "sessions"}),
            )
            .await
            .unwrap();
        assert_eq!(v2["count"], 0);
        let hint2 = v2["hint"].as_str().unwrap();
        assert!(hint2.contains("no matches for this query"), "{hint2}");

        // A no-match query WITHOUT a galaxy filter searches everywhere and
        // reports the overall corpus shape instead of a per-galaxy view.
        let v3 = tool
            .call(&mut ctx, json!({"query": "zzz-no-match"}))
            .await
            .unwrap();
        assert_eq!(v3["count"], 0);
        let hint3 = v3["hint"].as_str().expect("hint present on empty result");
        assert!(hint3.contains("across all memory galaxies"), "{hint3}");
    }

    #[tokio::test]
    async fn unfiltered_search_labels_hits_from_every_galaxy() {
        // Content spread across three galaxies; the default search (no
        // `galaxy` arg) must surface all of them, each labeled. This is the
        // federated-recall regression: every backing's rich content lived
        // outside `codex` and the old resolution path returned silent zeros.
        let (_dir, store, search) = hybrid_fixture();
        index_memory(
            &store,
            &search,
            Galaxy::Sessions,
            "lineage ledger phase four",
        );
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "lineage ledger codex mirror note",
        );
        index_memory(&store, &search, Galaxy::Dreams, "lineage ledger dream echo");
        let tool = MemoryHybridRecallTool::new(store.clone(), Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "lineage ledger", "limit": 10}))
            .await
            .unwrap();
        assert_eq!(v["count"], 3, "got: {v}");
        let galaxies: Vec<&str> = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["galaxy"].as_str().unwrap())
            .collect();
        assert!(galaxies.contains(&"sessions"), "got: {galaxies:?}");
        assert!(galaxies.contains(&"codex"), "got: {galaxies:?}");
        assert!(galaxies.contains(&"dreams"), "got: {galaxies:?}");

        // Explicit galaxy filters to exactly that galaxy.
        let v2 = tool
            .call(
                &mut ctx,
                json!({"query": "lineage ledger", "galaxy": "dreams"}),
            )
            .await
            .unwrap();
        assert_eq!(v2["count"], 1, "got: {v2}");
        assert_eq!(v2["results"][0]["galaxy"], "dreams");
    }

    #[tokio::test]
    async fn galaxy_all_alias_matches_unfiltered_search() {
        // P0 round-trip fix (2026-09-14): unfiltered responses emit
        // `"galaxy": "all"`; echoing that value back must behave exactly
        // like omitting the argument instead of "Unknown galaxy: 'all'".
        let (_dir, store, search) = hybrid_fixture();
        index_memory(&store, &search, Galaxy::Sessions, "alias probe session");
        index_memory(&store, &search, Galaxy::Dreams, "alias probe dream");
        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "alias probe", "galaxy": "all", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v["count"], 2, "got: {v}");
        assert_eq!(v["galaxy"], "all");
        let galaxies: Vec<&str> = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["galaxy"].as_str().unwrap())
            .collect();
        assert!(galaxies.contains(&"sessions"), "got: {galaxies:?}");
        assert!(galaxies.contains(&"dreams"), "got: {galaxies:?}");

        // Mixed case normalizes the same way.
        let v2 = tool
            .call(
                &mut ctx,
                json!({"query": "alias probe", "galaxy": "ALL", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v2["count"], 2, "got: {v2}");
    }

    #[tokio::test]
    async fn unfiltered_search_excludes_telemetry_unless_explicit() {
        // P0 regression (v9.1.5): default `memory.search` returned RSI
        // friction records from the telemetry galaxy when the query text
        // happened to match. Telemetry is evidence, not cognition: only an
        // explicit galaxy filter may reach it.
        let (_dir, store, search) = hybrid_fixture();
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "telemetry probe project note",
        );
        index_memory(
            &store,
            &search,
            Galaxy::Telemetry,
            "telemetry probe diagnostic record",
        );
        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "telemetry probe", "limit": 10}))
            .await
            .unwrap();
        assert_eq!(v["count"], 1, "unfiltered search must skip telemetry: {v}");
        assert_eq!(v["results"][0]["galaxy"], "codex");

        let v2 = tool
            .call(
                &mut ctx,
                json!({"query": "telemetry probe", "galaxy": "telemetry", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v2["count"], 1, "explicit telemetry must still work: {v2}");
        assert_eq!(v2["results"][0]["galaxy"], "telemetry");
    }

    #[tokio::test]
    async fn successful_search_carries_no_hint() {
        let (_dir, store, search) = hybrid_fixture();
        index_memory(&store, &search, Galaxy::Sessions, "gate plan decision");
        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "gate plan", "galaxy": "sessions"}),
            )
            .await
            .unwrap();
        assert_eq!(v["count"], 1);
        assert!(v["hint"].is_null());
    }

    #[tokio::test]
    async fn associative_expansion_surfaces_linked_memory() {
        // The core spreading-activation contract: a direct hit on memory A
        // activates its one-hop neighbor B even though B shares no query
        // terms, and B is marked source=association with its link metadata.
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(MemoryStore::open_default(dir.path()).unwrap());
        let tantivy_dir = dir.path().join("tantivy");
        std::fs::create_dir_all(&tantivy_dir).unwrap();
        let search = Arc::new(SearchEngine::open(&tantivy_dir).unwrap());
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "gate plan for the v7 alpha release",
        );
        let mut linked = Memory::new(
            Galaxy::Codex,
            "backup automation runs nightly at 03:30".into(),
        );
        linked.metadata.importance = 0.7;
        let linked_id = linked.metadata.id;
        store.put(Galaxy::Codex, &linked).unwrap();
        search
            .writer()
            .and_then(|mut w| {
                search.add_document(
                    &mut w,
                    &linked_id.to_string(),
                    "codex",
                    &linked.content,
                    &linked.metadata.tags,
                    linked.metadata.created_at.timestamp(),
                )?;
                search.commit(&mut w)
            })
            .unwrap();

        // The association must NOT share vocabulary with the query.
        let assoc = Association::new(
            find_id(&store, "gate plan"),
            linked_id,
            LinkType::Extends,
            0.8,
        );
        let associations = Arc::new(AssociationStore::open(store.env()).unwrap());
        associations.put(store.env(), &assoc).unwrap();

        let tool = MemoryHybridRecallTool::as_search(store.clone(), Some(search), None)
            .with_associations(Some(associations));
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "gate plan alpha release"}))
            .await
            .unwrap();
        assert_eq!(v["count"], 2, "direct hit + associated memory: {v}");
        let assoc_hit = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .find(|r| r["source"] == "association")
            .expect("association-sourced result present");
        assert_eq!(assoc_hit["id"], json!(linked_id.to_string()));
        assert_eq!(assoc_hit["link_type"], "extends");
        assert!(assoc_hit["via"].is_string());
        assert!(assoc_hit["weight"].as_f64().unwrap() > 0.7);
    }

    fn find_id(store: &MemoryStore, needle: &str) -> uuid::Uuid {
        store
            .scan(Galaxy::Codex, 100)
            .unwrap()
            .into_iter()
            .find(|m| m.content.contains(needle))
            .map(|m| m.metadata.id)
            .unwrap()
    }

    #[tokio::test]
    async fn associative_expansion_skips_private_and_dedupes() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(MemoryStore::open_default(dir.path()).unwrap());
        let mut a = Memory::new(Galaxy::Codex, "quarterly revenue planning notes".into());
        a.metadata.importance = 0.8;
        let a_id = a.metadata.id;
        store.put(Galaxy::Codex, &a).unwrap();
        // Private neighbor: must never surface through expansion.
        let mut private = Memory::new(Galaxy::Codex, "private salary bands".into());
        private.metadata.is_private = true;
        private.metadata.importance = 0.8;
        store.put(Galaxy::Codex, &private).unwrap();
        // Public neighbor linked twice (both directions) — must appear once.
        let mut b = Memory::new(Galaxy::Codex, "hiring plan for next quarter".into());
        b.metadata.importance = 0.7;
        let b_id = b.metadata.id;
        store.put(Galaxy::Codex, &b).unwrap();

        let associations = Arc::new(AssociationStore::open(store.env()).unwrap());
        associations
            .put(
                store.env(),
                &Association::new(a_id, private.metadata.id, LinkType::Related, 0.9),
            )
            .unwrap();
        associations
            .put(
                store.env(),
                &Association::new(a_id, b_id, LinkType::Related, 0.9),
            )
            .unwrap();
        associations
            .put(
                store.env(),
                &Association::new(b_id, a_id, LinkType::Related, 0.9),
            )
            .unwrap();

        let tool = MemoryHybridRecallTool::as_search(store.clone(), None, None)
            .with_associations(Some(associations.clone()));
        let mut ctx = Context::default();
        // No SearchEngine: scan-free importance path still seeds anchors? No —
        // with no query there is no seed; use a query but no FTS: results come
        // from Phase 1 only when search is present. So attach a search engine.
        let _ = &tool;
        let tantivy_dir = dir.path().join("tantivy");
        std::fs::create_dir_all(&tantivy_dir).unwrap();
        let search = Arc::new(SearchEngine::open(&tantivy_dir).unwrap());
        for (content, id) in [
            ("quarterly revenue planning notes", a_id),
            ("private salary bands", private.metadata.id),
            ("hiring plan for next quarter", b_id),
        ] {
            search
                .writer()
                .and_then(|mut w| {
                    search.add_document(&mut w, &id.to_string(), "codex", content, &[], 0)?;
                    search.commit(&mut w)
                })
                .unwrap();
        }
        let tool = MemoryHybridRecallTool::as_search(store.clone(), Some(search), None)
            .with_associations(Some(associations));
        let v = tool
            .call(&mut ctx, json!({"query": "quarterly revenue planning"}))
            .await
            .unwrap();
        let ids: Vec<&str> = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|r| r["id"].as_str())
            .collect();
        assert!(
            !ids.iter().any(|id| *id == private.metadata.id.to_string()),
            "private memory must not surface via association: {ids:?}"
        );
        assert_eq!(
            ids.iter().filter(|id| **id == b_id.to_string()).count(),
            1,
            "neighbor linked both directions appears exactly once: {ids:?}"
        );
    }

    #[tokio::test]
    async fn memory_update_content_recomputes_hash() {
        let store = test_store();
        let mem = Memory::new(Galaxy::Codex, "original text".into());
        store.put(Galaxy::Codex, &mem).unwrap();
        let id = mem.metadata.id;
        let original_hash = mem.metadata.content_hash.clone();

        let tool = MemoryUpdateTool::new(store.clone(), None);
        let v = tool
            .call(
                &mut Context::default(),
                json!({"galaxy": "codex", "id": id.to_string(), "content": "changed text"}),
            )
            .await
            .unwrap();
        assert_eq!(v["status"], "success");

        // Regression: content updates used to keep the old content hash,
        // leaving dedup and hash lookups pointing at stale content.
        let stored = store.get(Galaxy::Codex, id).unwrap().unwrap();
        assert_eq!(stored.content, "changed text");
        assert_eq!(
            stored.metadata.content_hash,
            wm_memory::content_hash("changed text")
        );
        assert_ne!(stored.metadata.content_hash, original_hash);
    }

    #[tokio::test]
    async fn memory_update_discloses_hash_timeline() {
        // V8 S11a: every update response carries the (new) content_hash so
        // the write-audit journal records a hash timeline per memory; a
        // content-changing update additionally carries prev_content_hash.
        let store = test_store();
        let mem = Memory::new(Galaxy::Codex, "original text".into());
        store.put(Galaxy::Codex, &mem).unwrap();
        let id = mem.metadata.id;
        let original_hash = mem.metadata.content_hash.clone();
        let tool = MemoryUpdateTool::new(store.clone(), None);
        let mut ctx = Context::default();

        let v = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "id": id.to_string(), "content": "changed text"}),
            )
            .await
            .unwrap();
        assert_eq!(
            v["content_hash"],
            json!(wm_memory::content_hash("changed text"))
        );
        assert_eq!(v["prev_content_hash"], json!(original_hash));

        // A metadata-only update discloses the current hash and no prev.
        let v = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "id": id.to_string(), "tags": ["amended"]}),
            )
            .await
            .unwrap();
        assert_eq!(
            v["content_hash"],
            json!(wm_memory::content_hash("changed text"))
        );
        assert!(v.get("prev_content_hash").is_none());
    }

    #[tokio::test]
    async fn memory_update_appends_revision_chain() {
        // V8 S11c: content changes append hash-linked revision entries;
        // metadata-only edits do not; the actor rides in from the context.
        let store = test_store();
        let mem = Memory::new(Galaxy::Codex, "original text".into());
        store.put(Galaxy::Codex, &mem).unwrap();
        let id = mem.metadata.id;
        let tool = MemoryUpdateTool::new(store.clone(), None);
        let mut ctx = Context {
            user_id: Some("agent-b".to_string()),
            session_id: Some(uuid::Uuid::nil()),
            compartment: Some("production".to_string()),
            ..Default::default()
        };
        let v = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "id": id.to_string(), "content": "second text"}),
            )
            .await
            .unwrap();
        assert_eq!(v["revision"]["seq"], 0);
        assert_eq!(
            v["revision"]["old_hash"],
            json!(wm_memory::content_hash("original text"))
        );
        assert_eq!(
            v["revision"]["new_hash"],
            json!(wm_memory::content_hash("second text"))
        );

        let v = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "id": id.to_string(), "content": "third text"}),
            )
            .await
            .unwrap();
        assert_eq!(v["revision"]["seq"], 1);

        let revisions = store.revisions(Galaxy::Codex, id).unwrap();
        assert_eq!(revisions.len(), 2);
        assert_eq!(revisions[1].old_hash, revisions[0].new_hash, "chain links");
        assert_eq!(revisions[0].actor_user.as_deref(), Some("agent-b"));
        assert_eq!(
            revisions[0].actor_compartment.as_deref(),
            Some("production")
        );
        assert_eq!(
            revisions[0].actor_session.as_deref(),
            Some(uuid::Uuid::nil().to_string().as_str())
        );

        let stored = store.get(Galaxy::Codex, id).unwrap().unwrap();
        assert_eq!(stored.metadata.revision_count, 2);

        // The honest chain verifies clean against the live content hash.
        let report = store
            .verify_revision_chain(Galaxy::Codex, id, &stored.metadata.content_hash)
            .unwrap();
        assert!(report.valid, "{:?}", report.breaks);
        assert!(report.matches_head);
    }

    #[tokio::test]
    async fn memory_update_out_of_band_edit_breaks_chain() {
        // Content changed WITHOUT the update tool (the write path the
        // journal sees but cannot describe) must break the head match.
        let store = test_store();
        let mem = Memory::new(Galaxy::Codex, "original text".into());
        store.put(Galaxy::Codex, &mem).unwrap();
        let id = mem.metadata.id;
        let tool = MemoryUpdateTool::new(store.clone(), None);
        tool.call(
            &mut Context::default(),
            json!({"galaxy": "codex", "id": id.to_string(), "content": "second text"}),
        )
        .await
        .unwrap();

        // Out-of-band rewrite: hash moved, no revision appended.
        let mut row = store.get(Galaxy::Codex, id).unwrap().unwrap();
        row.content = "smuggled text".to_string();
        row.metadata.content_hash = wm_memory::content_hash("smuggled text");
        store.put(Galaxy::Codex, &row).unwrap();

        let report = store
            .verify_revision_chain(Galaxy::Codex, id, &row.metadata.content_hash)
            .unwrap();
        assert!(!report.valid);
        assert!(!report.matches_head);
        assert!(report.breaks.iter().any(|b| b.contains("head mismatch")));
    }

    #[tokio::test]
    async fn memory_revisions_tool_list_and_verify() {
        let store = test_store();
        let mem = Memory::new(Galaxy::Codex, "v1".into());
        store.put(Galaxy::Codex, &mem).unwrap();
        let id = mem.metadata.id;
        let update = MemoryUpdateTool::new(store.clone(), None);
        update
            .call(
                &mut Context::default(),
                json!({"galaxy": "codex", "id": id.to_string(), "content": "v2"}),
            )
            .await
            .unwrap();

        let tool = MemoryRevisionsTool::new(store.clone());
        let v = tool
            .call(&mut Context::default(), json!({"id": id.to_string()}))
            .await
            .unwrap();
        assert_eq!(v["action"], "list");
        assert_eq!(v["count"], 1);

        let v = tool
            .call(
                &mut Context::default(),
                json!({"id": id.to_string(), "action": "verify"}),
            )
            .await
            .unwrap();
        assert_eq!(v["valid"], true);
        assert_eq!(v["entries"], 1);

        // An injected splice is detectable: entry 1 claims an old_hash the
        // chain never produced.
        store
            .record_revision(
                Galaxy::Codex,
                id,
                "forged_old_hash",
                &wm_memory::content_hash("v2"),
                wm_memory::RevisionActor::default(),
            )
            .unwrap();
        let v = tool
            .call(
                &mut Context::default(),
                json!({"id": id.to_string(), "action": "verify"}),
            )
            .await
            .unwrap();
        assert_eq!(v["valid"], false);
        let breaks: Vec<String> = v["breaks"]
            .as_array()
            .unwrap()
            .iter()
            .map(|b| b.as_str().unwrap().to_string())
            .collect();
        assert!(
            breaks.iter().any(|b| b.contains("hash-linkage")),
            "{breaks:?}"
        );
    }

    #[tokio::test]
    async fn memory_update_applies_importance_verbatim() {
        // V8 S11d: class ceilings/floors live in the pipeline write gate,
        // the single seam every dispatch passes through (same contract as
        // the create path). The tool itself applies the arg verbatim, so a
        // direct call performs no policy — gate coverage is pinned in
        // `wm-dispatch/src/write_gate.rs` instead.
        let store = test_store();

        let tel = Memory::new(
            Galaxy::Codex,
            "## Auto-logged Friction: dispatch error\n\nbody".into(),
        );
        store.put(Galaxy::Codex, &tel).unwrap();

        let tool = MemoryUpdateTool::new(store.clone(), None);
        let mut ctx = Context::default();

        let v = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "id": tel.metadata.id.to_string(), "importance": 0.9}),
            )
            .await
            .unwrap();
        assert!(v.get("class_policy").is_none());
        assert!(v.get("write_gate").is_none());
        let stored = store.get(Galaxy::Codex, tel.metadata.id).unwrap().unwrap();
        assert!((stored.metadata.importance - 0.9).abs() < 1e-5);
    }

    #[tokio::test]
    async fn memory_search_min_trust_filter_drops_low_trust() {
        // V8 T-b: min_trust is a post-resolution FILTER on every route —
        // user-confirmed (1.0) survives a 0.9 floor, tool-ingested (0.7)
        // does not; the response discloses what it filtered.
        let (_dir, store, search) = hybrid_fixture();
        let mut confirmed = Memory::new(Galaxy::Codex, "Quantum foal registry minutes".into());
        confirmed.metadata.source_trust = 1.0;
        confirmed.metadata.source = "user".to_string();
        let mut ingested = Memory::new(Galaxy::Codex, "Quantum foal registry draft".into());
        ingested.metadata.source_trust = 0.7;
        ingested.metadata.source = "tool".to_string();
        store.put(Galaxy::Codex, &confirmed).unwrap();
        store.put(Galaxy::Codex, &ingested).unwrap();
        mirror_memory(&store, &confirmed, None, 1);
        mirror_memory(&store, &ingested, None, 2);

        let tool = default_search_tool(store, Some(search));
        let mut ctx = Context::default();

        let v = tool
            .call(
                &mut ctx,
                json!({"query": "quantum foal registry", "limit": 10}),
            )
            .await
            .unwrap();
        assert_eq!(v["count"], 2, "no floor: both results surface");
        assert!(v.get("min_trust").is_none());

        let v = tool
            .call(
                &mut ctx,
                json!({"query": "quantum foal registry", "limit": 10, "min_trust": 0.9}),
            )
            .await
            .unwrap();
        assert_eq!(v["min_trust"], 0.9);
        assert_eq!(v["min_trust_filtered"], 1);
        let trusts: Vec<f64> = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["trust"].as_f64().unwrap())
            .collect();
        assert!(trusts.iter().all(|t| *t >= 0.9), "{trusts:?}");
    }

    #[tokio::test]
    async fn memory_sort_by_importance_asc() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemorySortTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"sort_by": "importance", "order": "asc"}))
            .await
            .unwrap();
        let mems = v["memories"].as_array().unwrap();
        assert!(mems[0]["importance"].as_f64().unwrap() <= mems[1]["importance"].as_f64().unwrap());
    }

    #[tokio::test]
    async fn memory_sort_by_recency() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemorySortTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"sort_by": "recency"}))
            .await
            .unwrap();
        assert_eq!(v["returned"], 3);
    }

    #[tokio::test]
    async fn memory_sort_invalid_field() {
        let store = test_store();
        let tool = MemorySortTool::new(store);
        let mut ctx = Context::default();
        let result = tool.call(&mut ctx, json!({"sort_by": "invalid"})).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn memory_sort_with_limit() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemorySortTool::new(store);
        let mut ctx = Context::default();
        let v = tool.call(&mut ctx, json!({"limit": 2})).await.unwrap();
        assert_eq!(v["returned"], 2);
        assert_eq!(v["total"], 3);
    }

    #[tokio::test]
    async fn memory_filter_by_tag() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryFilterTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"tags": ["rust"]}))
            .await
            .unwrap();
        assert_eq!(v["matched"], 2);
    }

    #[tokio::test]
    async fn memory_filter_by_importance_range() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryFilterTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"min_importance": 0.4, "max_importance": 0.6}),
            )
            .await
            .unwrap();
        assert_eq!(v["matched"], 1);
    }

    /// The `query` arg was silently dropped before this fix — every term
    /// must now match (case-insensitive) against content or title, and the
    /// terms are echoed in `filters` so callers can see what ran.
    #[tokio::test]
    async fn memory_filter_query_matches_content_and_title() {
        let store = test_store();
        let tool = MemoryFilterTool::new(store.clone());
        let mut ctx = Context::default();

        let mut titled = Memory::new(Galaxy::Codex, "unrelated body text".into());
        titled.metadata.title = Some("Rust Borrow Checker".into());
        let plain = Memory::new(Galaxy::Codex, "rust ownership rules".into());
        let other = Memory::new(Galaxy::Codex, "gardening tips".into());
        for m in [&titled, &plain, &other] {
            store.put(Galaxy::Codex, m).unwrap();
        }

        let v = tool.call(&mut ctx, json!({"query": "RUST"})).await.unwrap();
        assert_eq!(v["matched"], 2, "content hit + title hit: {v}");
        assert_eq!(v["filters"]["query_terms"], json!(["rust"]));

        let v = tool
            .call(&mut ctx, json!({"query": "rust borrow"}))
            .await
            .unwrap();
        assert_eq!(v["matched"], 1, "all terms must match: {v}");
        assert_eq!(v["memories"][0]["content"], "unrelated body text");
    }

    #[tokio::test]
    async fn memory_filter_no_matches() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryFilterTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"tags": ["nonexistent"]}))
            .await
            .unwrap();
        assert_eq!(v["matched"], 0);
    }

    #[tokio::test]
    async fn memory_filter_combined_tags_and_importance() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryFilterTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"tags": ["rust"], "min_importance": 0.5}))
            .await
            .unwrap();
        assert_eq!(v["matched"], 1);
    }

    /// API honesty (§8): `offset`, `exclude_tags`, and the date range the
    /// description always promised are real. Paging addresses the VISIBLE
    /// surface.
    #[tokio::test]
    async fn memory_filter_offset_exclude_tags_and_date_range() {
        let store = test_store();
        let tool = MemoryFilterTool::new(store.clone());
        let mut ctx = Context::default();

        let mut recent_a = Memory::new(Galaxy::Codex, "recent a".into());
        recent_a.metadata.created_at = chrono::Utc::now() - chrono::Duration::hours(2);
        let mut recent_b = Memory::new(Galaxy::Codex, "recent b".into());
        recent_b.metadata.created_at = chrono::Utc::now() - chrono::Duration::hours(1);
        recent_b.metadata.tags = vec!["noise".into()];
        let mut recent_priv = Memory::new(Galaxy::Codex, "recent private".into());
        recent_priv.metadata.created_at = chrono::Utc::now() - chrono::Duration::minutes(90);
        recent_priv.metadata.is_private = true;
        let mut old = Memory::new(Galaxy::Codex, "old relic".into());
        old.metadata.created_at = chrono::Utc::now() - chrono::Duration::days(60);
        for m in [&recent_a, &recent_b, &recent_priv, &old] {
            store.put(Galaxy::Codex, m).unwrap();
        }

        let cutoff = (chrono::Utc::now() - chrono::Duration::days(1))
            .to_rfc3339_opts(chrono::SecondsFormat::Millis, true);

        // Date range + exclude_tags + privacy all compose.
        let v = tool
            .call(
                &mut ctx,
                json!({
                    "galaxy": "codex",
                    "created_after": cutoff,
                    "exclude_tags": ["noise"],
                }),
            )
            .await
            .unwrap();
        assert_eq!(v["matched"], 1, "only recent-a is visible in range: {v}");
        assert_eq!(v["returned"], 1);
        assert_eq!(v["memories"][0]["content"], "recent a");
        assert_eq!(v["filters"]["exclude_tags"], json!(["noise"]));
        assert!(v["filters"]["created_after"].is_string());

        // Offset pages the matched surface (recent-a, recent-b, old —
        // the private memory is invisible and never counted).
        let page2 = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "offset": 3, "limit": 2}),
            )
            .await
            .unwrap();
        assert_eq!(
            page2["matched"], 3,
            "private memory must not count: {page2}"
        );
        assert_eq!(
            page2["returned"], 0,
            "offset past the match set is an honest empty page"
        );
        assert_eq!(page2["offset"], 3);

        // Malformed date bounds are a loud InvalidArgs.
        let bad = tool
            .call(
                &mut ctx,
                json!({"galaxy": "codex", "created_before": "yesterday"}),
            )
            .await;
        assert!(bad.is_err(), "non-RFC-3339 bound must be refused");
    }

    #[tokio::test]
    async fn memory_deduplicate_hash_dry_run() {
        let store = test_store();
        let m1 = Memory::new(Galaxy::Codex, "duplicate content".into());
        let m2 = Memory::new(Galaxy::Codex, "duplicate content".into());
        let _ = store.put(Galaxy::Codex, &m1);
        let _ = store.put(Galaxy::Codex, &m2);
        let _ = store.put(
            Galaxy::Codex,
            &Memory::new(Galaxy::Codex, "unique content".into()),
        );

        let tool = MemoryDeduplicateTool::new(store.clone(), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"mode": "hash", "dry_run": true}))
            .await
            .unwrap();
        assert_eq!(v["duplicates_found"], 1);
        assert_eq!(v["removed"], 0);

        let memories = store.scan(Galaxy::Codex, 100).unwrap();
        assert_eq!(memories.len(), 3);
    }

    #[tokio::test]
    async fn memory_deduplicate_hash_execute() {
        let store = test_store();
        let m1 = Memory::new(Galaxy::Codex, "duplicate content".into());
        let m2 = Memory::new(Galaxy::Codex, "duplicate content".into());
        let _ = store.put(Galaxy::Codex, &m1);
        let _ = store.put(Galaxy::Codex, &m2);
        let _ = store.put(
            Galaxy::Codex,
            &Memory::new(Galaxy::Codex, "unique content".into()),
        );

        let tool = MemoryDeduplicateTool::new(store.clone(), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"mode": "hash", "dry_run": false}))
            .await
            .unwrap();
        assert_eq!(v["duplicates_found"], 1);
        assert_eq!(v["removed"], 1);

        let memories = store.scan(Galaxy::Codex, 100).unwrap();
        assert_eq!(memories.len(), 2);
    }

    #[tokio::test]
    async fn memory_deduplicate_deindexes_removed_memories() {
        // Regression: deduplicate used to delete from LMDB without de-indexing,
        // so full-text search kept returning the removed duplicate.
        let (_dir, store, search) = hybrid_fixture();

        let m1 = Memory::new(Galaxy::Codex, "index drift duplicate".into());
        let m2 = Memory::new(Galaxy::Codex, "index drift duplicate".into());
        let id1 = m1.metadata.id;
        let id2 = m2.metadata.id;
        let _ = store.put(Galaxy::Codex, &m1);
        let _ = store.put(Galaxy::Codex, &m2);
        for mem in [&m1, &m2] {
            let mut writer = search.writer().unwrap();
            search
                .add_document(
                    &mut writer,
                    &mem.metadata.id.to_string(),
                    mem.metadata.galaxy.db_name(),
                    &mem.content,
                    &mem.metadata.tags,
                    mem.metadata.created_at.timestamp(),
                )
                .unwrap();
            search.commit(&mut writer).unwrap();
        }

        // Precondition: both duplicates are searchable.
        let before = search.search_ids("index drift", 100).unwrap();
        assert_eq!(before.len(), 2);

        let tool = MemoryDeduplicateTool::new(store.clone(), Some(search.clone()));
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"mode": "hash", "dry_run": false}))
            .await
            .unwrap();
        assert_eq!(v["removed"], 1);

        // The surviving memory is still searchable; the removed one is gone.
        // (LMDB scan order is by UUID, so either duplicate may be the keeper.)
        let after = search.search_ids("index drift", 100).unwrap();
        assert_eq!(after.len(), 1, "search index should only contain survivors");
        assert!(
            after.contains(&id1) || after.contains(&id2),
            "survivor should be one of the original memories"
        );
    }

    #[tokio::test]
    async fn memory_deduplicate_content_mode() {
        let store = test_store();
        let m1 = Memory::new(Galaxy::Codex, "same text".into());
        let m2 = Memory::new(Galaxy::Codex, "same text".into());
        let _ = store.put(Galaxy::Codex, &m1);
        let _ = store.put(Galaxy::Codex, &m2);

        let tool = MemoryDeduplicateTool::new(store, None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"mode": "content", "dry_run": true}))
            .await
            .unwrap();
        assert_eq!(v["duplicates_found"], 1);
    }

    #[tokio::test]
    async fn memory_deduplicate_no_duplicates() {
        let store = test_store();
        let _ = store.put(
            Galaxy::Codex,
            &Memory::new(Galaxy::Codex, "content a".into()),
        );
        let _ = store.put(
            Galaxy::Codex,
            &Memory::new(Galaxy::Codex, "content b".into()),
        );

        let tool = MemoryDeduplicateTool::new(store, None);
        let mut ctx = Context::default();
        let v = tool.call(&mut ctx, json!({})).await.unwrap();
        assert_eq!(v["duplicates_found"], 0);
    }

    #[tokio::test]
    async fn memory_deduplicate_invalid_mode() {
        let store = test_store();
        let tool = MemoryDeduplicateTool::new(store, None);
        let mut ctx = Context::default();
        let result = tool.call(&mut ctx, json!({"mode": "invalid"})).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn memory_export_json() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryExportTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"format": "json"}))
            .await
            .unwrap();
        assert_eq!(v["format"], "json");
        assert_eq!(v["count"], 3);
        assert!(v["export"].as_str().unwrap().contains("First memory"));
    }

    #[tokio::test]
    async fn memory_export_csv() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryExportTool::new(store);
        let mut ctx = Context::default();
        let v = tool.call(&mut ctx, json!({"format": "csv"})).await.unwrap();
        let csv = v["export"].as_str().unwrap();
        assert!(csv.contains("id,content,tags"));
        assert!(csv.contains("First memory"));
    }

    #[tokio::test]
    async fn memory_export_markdown() {
        let store = test_store();
        populate_memories(&store, Galaxy::Codex);
        let tool = MemoryExportTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"format": "markdown"}))
            .await
            .unwrap();
        let md = v["export"].as_str().unwrap();
        assert!(md.contains("# Memory Export"));
        assert!(md.contains("First memory"));
    }

    #[tokio::test]
    async fn memory_export_invalid_format() {
        let store = test_store();
        let tool = MemoryExportTool::new(store);
        let mut ctx = Context::default();
        let result = tool.call(&mut ctx, json!({"format": "xml"})).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn memory_export_empty_galaxy() {
        let store = test_store();
        let tool = MemoryExportTool::new(store);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"format": "json"}))
            .await
            .unwrap();
        assert_eq!(v["count"], 0);
    }

    #[tokio::test]
    async fn memory_sort_and_filter_are_winnowing_basket_gana() {
        let store = test_store();
        assert_eq!(
            MemorySortTool::new(store.clone()).gana(),
            Gana::WinnowingBasket
        );
        assert_eq!(
            MemoryFilterTool::new(store.clone()).gana(),
            Gana::WinnowingBasket
        );
        assert_eq!(
            MemoryDeduplicateTool::new(store.clone(), None).gana(),
            Gana::WinnowingBasket
        );
        assert_eq!(MemoryExportTool::new(store).gana(), Gana::WinnowingBasket);
    }

    // ── hybrid_recall incident regression tests ─────────────────────────
    //
    // Mirrors the 2026-08-11 incident: `memory.hybrid_recall` with query
    // "smoke test from wmClient" and limit 20 returned 20 unrelated memories
    // at BM25 scores 0.5–1.0 with zero query-token overlap. The fix uses
    // OR semantics with a token-coverage floor and score floors, replacing
    // the old `scan(galaxy, 100)` lottery.

    #[test]
    fn hybrid_recall_routes_expose_query_schema() {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(MemoryStore::open_default(dir.path()).unwrap());
        for tool in [
            MemoryHybridRecallTool::new(store.clone(), None, None),
            MemoryHybridRecallTool::as_search(store, None, None),
        ] {
            let schema = tool.input_schema();
            assert_eq!(schema["type"], "object");
            assert!(schema["properties"].get("query").is_some());
            assert_eq!(schema["required"], json!(["query"]));
        }
    }

    /// Build a store + tantivy index pair where the memory and its index
    /// document are kept in sync (as the write path does).
    fn hybrid_fixture() -> (tempfile::TempDir, Arc<MemoryStore>, Arc<SearchEngine>) {
        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(MemoryStore::open_default(dir.path()).unwrap());
        let tantivy_dir = dir.path().join("tantivy");
        std::fs::create_dir_all(&tantivy_dir).unwrap();
        let search = Arc::new(SearchEngine::open(&tantivy_dir).unwrap());
        (dir, store, search)
    }

    fn index_memory(
        store: &Arc<MemoryStore>,
        search: &Arc<SearchEngine>,
        galaxy: Galaxy,
        content: &str,
    ) {
        let mem = Memory::new(galaxy, content.to_string());
        let id = mem.metadata.id;
        store.put(galaxy, &mem).unwrap();
        let mut writer = search.writer().unwrap();
        search
            .add_document(
                &mut writer,
                &id.to_string(),
                galaxy.db_name(),
                content,
                &mem.metadata.tags,
                mem.metadata.created_at.timestamp(),
            )
            .unwrap();
        search.commit(&mut writer).unwrap();
    }

    #[tokio::test]
    async fn hybrid_recall_excludes_private_memories() {
        let (_dir, store, search) = hybrid_fixture();

        // Private memory, indexed exactly like the write path.
        let mut priv_mem = Memory::new(Galaxy::Codex, "private secret plan alpha".to_string());
        priv_mem.metadata.is_private = true;
        let id = priv_mem.metadata.id;
        store.put(Galaxy::Codex, &priv_mem).unwrap();
        {
            let mut writer = search.writer().unwrap();
            search
                .add_document(
                    &mut writer,
                    &id.to_string(),
                    "codex",
                    "private secret plan alpha",
                    &[],
                    priv_mem.metadata.created_at.timestamp(),
                )
                .unwrap();
            search.commit(&mut writer).unwrap();
        }

        // Public memory with overlapping terms.
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "public plan alpha documentation",
        );

        let tool = MemoryHybridRecallTool::new(store.clone(), Some(search.clone()), None);
        let v = tool
            .call(
                &mut Context::default(),
                json!({"query": "plan alpha", "galaxy": "codex"}),
            )
            .await
            .unwrap();
        let results = v["results"].as_array().unwrap();
        let contents: Vec<&str> = results
            .iter()
            .filter_map(|r| r["content"].as_str())
            .collect();
        assert!(
            !contents.iter().any(|c| c.contains("private")),
            "private memory leaked through hybrid recall: {results:?}"
        );
        assert!(
            contents.iter().any(|c| c.contains("public")),
            "public memory missing from hybrid recall: {results:?}"
        );
    }

    #[tokio::test]
    async fn batch_read_treats_private_as_miss() {
        let store = test_store();
        let mut priv_mem = Memory::new(Galaxy::Codex, "private batch note".into());
        priv_mem.metadata.is_private = true;
        let priv_id = priv_mem.metadata.id;
        store.put(Galaxy::Codex, &priv_mem).unwrap();
        let pub_mem = Memory::new(Galaxy::Codex, "public batch note".into());
        let pub_id = pub_mem.metadata.id;
        store.put(Galaxy::Codex, &pub_mem).unwrap();

        let tool = MemoryBatchReadTool::new(store);
        let v = tool
            .call(
                &mut Context::default(),
                json!({"galaxy": "codex", "ids": [priv_id.to_string(), pub_id.to_string()]}),
            )
            .await
            .unwrap();
        assert_eq!(v["found"], 1);
        assert_eq!(v["misses"], 1);
        assert!(
            !v["memories"]
                .as_array()
                .unwrap()
                .iter()
                .any(|m| m["content"].as_str().unwrap_or("").contains("private")),
            "private memory leaked through batch_read: {v}"
        );
    }

    #[tokio::test]
    async fn hybrid_recall_incident_query_returns_only_relevant() {
        let (_dir, store, search) = hybrid_fixture();
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "smoke test from wmClient: verify recall",
        );
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "NES Evolution and Impact: a history of the console wars",
        );
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "Insights on The Gateless Gate: koans and zen practice",
        );
        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "smoke test", "galaxy": "codex", "limit": 5}),
            )
            .await
            .unwrap();
        let results = v["results"].as_array().unwrap();
        assert_eq!(
            results.len(),
            1,
            "incident query must not return unrelated memories: {results:?}"
        );
        let hit = &results[0];
        assert_eq!(hit["source"], "fts");
        assert!(
            hit["content"]
                .as_str()
                .unwrap()
                .contains("smoke test from wmClient")
        );
        assert!(hit["normalized_score"].as_f64().unwrap() > 0.0);
        assert_eq!(v["count"], 1);
    }

    #[tokio::test]
    async fn hybrid_recall_filters_stale_index_entries() {
        // A document indexed in tantivy but absent from LMDB must not be
        // returned (the old code wasted top-K slots on these).
        let (_dir, store, search) = hybrid_fixture();
        index_memory(
            &store,
            &search,
            Galaxy::Codex,
            "rust memory about ownership",
        );
        {
            let mut writer = search.writer().unwrap();
            search
                .add_document(
                    &mut writer,
                    "99999999-9999-9999-9999-999999999999",
                    "codex",
                    "rust ghost memory",
                    &[],
                    1700000000,
                )
                .unwrap();
            search.commit(&mut writer).unwrap();
        }

        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "rust", "limit": 10}))
            .await
            .unwrap();
        let results = v["results"].as_array().unwrap();
        assert_eq!(results.len(), 1);
        assert_ne!(
            results[0]["id"].as_str().unwrap(),
            "99999999-9999-9999-9999-999999999999"
        );
    }

    #[tokio::test]
    async fn hybrid_recall_respects_min_score_arg() {
        let (_dir, store, search) = hybrid_fixture();
        index_memory(&store, &search, Galaxy::Codex, "alpha");
        let filler = format!("alpha {}", "zzz ".repeat(400));
        index_memory(&store, &search, Galaxy::Codex, &filler);

        // No threshold: both match.
        let tool = MemoryHybridRecallTool::new(store.clone(), Some(search.clone()), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "alpha", "limit": 10}))
            .await
            .unwrap();
        assert_eq!(v["count"], 2);

        // min_score between the two scores: only the strong match remains.
        let scores: Vec<f64> = v["results"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["score"].as_f64().unwrap())
            .collect();
        let lo = scores.iter().copied().fold(f64::MAX, f64::min);
        let hi = scores.iter().copied().fold(0.0, f64::max);
        let mid = f64::midpoint(hi, lo);

        let v = tool
            .call(
                &mut ctx,
                json!({"query": "alpha", "limit": 10, "min_score": mid}),
            )
            .await
            .unwrap();
        assert_eq!(v["count"], 1);
        assert!((v["results"][0]["score"].as_f64().unwrap() - hi).abs() < 1e-3);
    }

    #[tokio::test]
    async fn hybrid_recall_or_coverage_finds_partial_matches() {
        // OR + token-coverage finds partial matches without a separate
        // fallback phase.  The doc covering 3/4 query terms survives the
        // 2/4 coverage floor; the 1/4 doc is filtered out.
        let (_dir, store, search) = hybrid_fixture();
        index_memory(&store, &search, Galaxy::Codex, "alpha only here");
        index_memory(&store, &search, Galaxy::Codex, "alpha beta gamma delta");

        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();
        let v = tool
            .call(&mut ctx, json!({"query": "alpha beta gamma", "limit": 10}))
            .await
            .unwrap();
        let results = v["results"].as_array().unwrap();
        // 3-term query: 2/3 coverage floor.  "alpha beta gamma delta" covers
        // 3/3, "alpha only here" covers 1/3 → filtered.
        assert_eq!(results.len(), 1);
        assert!(
            results[0]["content"]
                .as_str()
                .unwrap()
                .contains("alpha beta gamma")
        );

        // 4-term query: 2/4 coverage floor.  "alpha beta gamma delta" covers
        // 3/4, "alpha only here" covers 1/4 → filtered.
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "alpha beta gamma zeta", "limit": 10}),
            )
            .await
            .unwrap();
        let results = v["results"].as_array().unwrap();
        assert_eq!(
            results.len(),
            1,
            "OR + coverage must require 2/4 token coverage: {results:?}"
        );
        assert!(
            results[0]["content"]
                .as_str()
                .unwrap()
                .contains("alpha beta gamma")
        );
        for r in results {
            assert!(
                matches!(r["source"].as_str(), Some("fts")),
                "results should be tagged fts"
            );
        }
    }

    fn index_tagged_memory(
        store: &Arc<MemoryStore>,
        search: &Arc<SearchEngine>,
        galaxy: Galaxy,
        content: &str,
        tags: &[&str],
    ) {
        let mut mem = Memory::new(galaxy, content.to_string());
        mem.metadata.tags = tags.iter().map(ToString::to_string).collect();
        let id = mem.metadata.id;
        store.put(galaxy, &mem).unwrap();
        let mut writer = search.writer().unwrap();
        search
            .add_document(
                &mut writer,
                &id.to_string(),
                galaxy.db_name(),
                content,
                &mem.metadata.tags,
                mem.metadata.created_at.timestamp(),
            )
            .unwrap();
        search.commit(&mut writer).unwrap();
    }

    fn aggregate_fixture() -> (tempfile::TempDir, Arc<MemoryStore>, Arc<SearchEngine>) {
        let (dir, store, search) = hybrid_fixture();
        // A Rust learning journey across sessions 2, 7, 12 …
        index_tagged_memory(
            &store,
            &search,
            Galaxy::Codex,
            "I started learning Rust.",
            &["user", "session_002"],
        );
        index_tagged_memory(
            &store,
            &search,
            Galaxy::Codex,
            "I finished my first Rust project, a CLI tool.",
            &["user", "session_007"],
        );
        index_tagged_memory(
            &store,
            &search,
            Galaxy::Codex,
            "I got a job as a systems engineer using Rust.",
            &["user", "session_012"],
        );
        // …and a Go journey that must not distort the Rust span (all its
        // turns also match the generic terms "started"/"job").
        index_tagged_memory(
            &store,
            &search,
            Galaxy::Codex,
            "I started learning Go.",
            &["user", "session_003"],
        );
        index_tagged_memory(
            &store,
            &search,
            Galaxy::Codex,
            "I got a job as a backend engineer using Go.",
            &["user", "session_015"],
        );
        (dir, store, search)
    }

    #[tokio::test]
    async fn aggregate_session_span_isolated_by_rarest_term() {
        let (_dir, store, search) = aggregate_fixture();
        let tool = MemoryAggregateTool::new(Some(search), store);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({
                    "query": "How long did it take from starting Rust to getting a job using it?",
                    "metric": "session_span",
                }),
            )
            .await
            .unwrap();
        assert_eq!(v["aggregate"]["value"], 10, "session_012 - session_002");
        assert_eq!(v["aggregate"]["unit"], "sessions");
        assert_eq!(v["aggregate"]["content"], "10 sessions");
    }

    #[tokio::test]
    async fn aggregate_session_count() {
        let (_dir, store, search) = aggregate_fixture();
        let tool = MemoryAggregateTool::new(Some(search), store);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({
                    "query": "How long did it take from starting Rust to getting a job using it?",
                    "metric": "session_count",
                }),
            )
            .await
            .unwrap();
        // The anchor cluster is the Rust turns; the middle turn ("finished
        // my first Rust project") matches only one query term and is held
        // back by the search engine's token-coverage floor, so the distinct
        // session count is 2 (start and end sessions) — span is unaffected
        // because min/max need only the endpoints.
        assert_eq!(v["aggregate"]["value"], 2);
    }

    #[tokio::test]
    async fn aggregate_count_needs_no_session_tags() {
        let (_dir, store, search) = aggregate_fixture();
        let tool = MemoryAggregateTool::new(Some(search), store);
        let mut ctx = Context::default();
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "Rust project", "metric": "count"}),
            )
            .await
            .unwrap();
        // OR semantics: all three Rust turns match "rust".
        assert_eq!(v["aggregate"]["value"], 3);
    }

    /// Previously a single session-tagged hit (or a stopword-only query
    /// with no anchor term) reported session_count 0 / span null DESPITE
    /// evidence. The fallback anchors on the session-tagged set instead.
    #[tokio::test]
    async fn aggregate_single_session_falls_back_honestly() {
        let (_dir, store, search) = aggregate_fixture();
        let tool = MemoryAggregateTool::new(Some(search), store);
        let mut ctx = Context::default();
        // "CLI tool" narrows to the session_007 turn alone.
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "CLI tool", "metric": "session_count"}),
            )
            .await
            .unwrap();
        assert_eq!(v["aggregate"]["value"], 1, "one session in evidence: {v}");
        assert_eq!(v["anchor"], "session_tagged_fallback");
        let v = tool
            .call(
                &mut ctx,
                json!({"query": "CLI tool", "metric": "session_span"}),
            )
            .await
            .unwrap();
        assert_eq!(v["aggregate"]["value"], 0, "single point spans 0: {v}");
    }

    #[tokio::test]
    async fn aggregate_rejects_unknown_metric() {
        let (_dir, store, search) = aggregate_fixture();
        let tool = MemoryAggregateTool::new(Some(search), store);
        let mut ctx = Context::default();
        let err = tool
            .call(&mut ctx, json!({"query": "x", "metric": "median"}))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("unknown metric"));
    }

    /// 2026-09-15 audit: bounded floors must reject out-of-range values
    /// instead of silently dropping the filter (watching `min_trust: 2.0`
    /// quietly disable the trust floor is the failure this pins).
    #[tokio::test]
    async fn hybrid_recall_rejects_out_of_range_floors() {
        let (_dir, store, search) = hybrid_fixture();
        let tool = MemoryHybridRecallTool::new(store, Some(search), None);
        let mut ctx = Context::default();

        for (key, value) in [
            ("min_trust", json!(2.0)),
            ("min_trust", json!(-0.1)),
            ("min_importance", json!(1.5)),
            ("min_importance", json!(-0.5)),
            ("min_score_ratio", json!(1.5)),
            ("min_score_ratio", json!(-1.0)),
            ("min_score", json!(-3.0)),
            ("min_trust", json!("2.0")),
        ] {
            let err = tool
                .call(&mut ctx, json!({"query": "x", key: value}))
                .await
                .unwrap_err();
            assert!(
                err.to_string().contains(key),
                "{key}={value} must be rejected by name, got: {err}"
            );
        }

        // Boundary values at the edge of the valid interval are accepted.
        let v = tool
            .call(
                &mut ctx,
                json!({
                    "query": "x",
                    "min_trust": 1.0,
                    "min_importance": 0.0,
                    "min_score_ratio": 0.0,
                    "min_score": 0.0,
                }),
            )
            .await
            .unwrap();
        assert_eq!(v["min_trust"], 1.0, "valid boundary floor disclosed: {v}");
    }

    /// 2026-09-15 audit: importance is defined on 0.0-1.0; out-of-range
    /// updates are caller errors, not values stored verbatim.
    #[tokio::test]
    async fn memory_update_rejects_out_of_range_importance() {
        let store = test_store();
        let mut mem = Memory::new(Galaxy::Codex, "audit validation target".into());
        mem.metadata.importance = 0.5;
        store.put(Galaxy::Codex, &mem).unwrap();
        let id = mem.metadata.id;

        let tool = MemoryUpdateTool::new(store.clone(), None);
        let mut ctx = Context::default();
        for bad in [json!(2.0), json!(999), json!(-0.25), json!("1.5")] {
            let err = tool
                .call(&mut ctx, json!({"id": id, "importance": bad}))
                .await
                .unwrap_err();
            assert!(
                err.to_string().contains("importance"),
                "importance={bad} must be rejected, got: {err}"
            );
        }
        let stored = store.get(Galaxy::Codex, id).unwrap().unwrap();
        assert!(
            (stored.metadata.importance - 0.5).abs() < f32::EPSILON,
            "rejected updates must not mutate the record: {}",
            stored.metadata.importance
        );

        // A valid update still lands.
        let v = tool
            .call(&mut ctx, json!({"id": id, "importance": 0.75}))
            .await
            .unwrap();
        assert_eq!(v["status"], "success", "{v}");
        let stored = store.get(Galaxy::Codex, id).unwrap().unwrap();
        assert!((stored.metadata.importance - 0.75).abs() < f32::EPSILON);
    }

    // ── Absolute-evidence abstention (2026-09-22) ──────────────────────

    #[test]
    fn weak_evidence_abstention_floor_and_coverage() {
        // Knobs off: never abstains.
        let fts = vec![json!({"source": "fts", "raw_score": 0.5})];
        assert!(weak_evidence_abstention_with(&fts, "alpha", 0.0, 0.0).is_none());

        // FTS/hybrid top below the absolute BM25 floor.
        let weak =
            weak_evidence_abstention_with(&fts, "alpha", 2.0, 0.0).expect("below floor abstains");
        assert_eq!(weak["reason"], "top_below_floor");
        assert_eq!(weak["signal"], "bm25");
        assert_eq!(weak["scope"], "retrieval");
        assert_eq!(weak["status"], "insufficient_evidence");

        // Above the floor: no abstention.
        let strong = vec![json!({"source": "hybrid", "raw_score": 4.0})];
        assert!(weak_evidence_abstention_with(&strong, "alpha", 2.0, 0.0).is_none());

        // Vector-only evidence (raw 0.0) is not judged by the BM25 floor.
        let vector_only = vec![json!({"source": "hybrid", "raw_score": 0.0, "vector_score": 0.9})];
        assert!(weak_evidence_abstention_with(&vector_only, "alpha", 2.0, 0.0).is_none());

        // Episodic coverage: 1 of 4 stopword-stripped terms matched.
        let episodic = vec![json!({"source": "episodic", "matched_terms": 1})];
        let low = weak_evidence_abstention_with(&episodic, "alpha beta gamma delta", 0.0, 0.5)
            .expect("low coverage abstains");
        assert_eq!(low["reason"], "coverage_below_floor");
        assert_eq!(low["signal"], "coverage");
        assert_eq!(low["matched_terms"], 1);

        // Full coverage passes.
        let full = vec![json!({"source": "episodic", "matched_terms": 4})];
        assert!(weak_evidence_abstention_with(&full, "alpha beta gamma delta", 0.0, 0.5).is_none());

        // Non-retrieval sources are not judged.
        let association = vec![json!({"source": "association", "score": 0.1})];
        assert!(weak_evidence_abstention_with(&association, "alpha", 2.0, 0.5).is_none());
    }
}