kimetsu-brain 2.8.0

Project + user-scope memory, hybrid retrieval (lexical + cosine), ambient context, secret redaction at ingest for kimetsu.
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
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
#[path = "delivery.rs"]
pub mod delivery;

use std::cmp::Ordering;
use std::collections::HashMap;

use kimetsu_core::config::{BrokerWeights, StageWeights};
use kimetsu_core::memory::MemoryScope;
use kimetsu_core::{KimetsuResult, ids::new_id};
use rusqlite::{Connection, OptionalExtension, params};
use serde::{Deserialize, Serialize};

// -----------------------------------------------------------------------
// E3: task-kind classification + adaptive retrieval routing
// -----------------------------------------------------------------------

/// The inferred kind of the current coding task. Classified once at
/// intake from the task description string — deterministic keyword
/// scan, no model call, zero allocation-heavy work.
///
/// `Feature` is the NEUTRAL default: it does not change weights or
/// prefer_roles at all, so every existing `..Default::default()`
/// construction produces exactly the prior retrieval behaviour.
///
/// Precedence when multiple keyword sets match:
///   Debug > Investigation > Refactor > Docs > Feature
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TaskKind {
    /// Neutral / catch-all (add, implement, build, create, support, …).
    /// Must NOT alter weights or prefer_roles — keeps existing tests green.
    #[default]
    Feature,
    /// fix, bug, error, fail, crash, panic, regression, broken, debug,
    /// stack trace, exception — up freshness, prefer failure_pattern.
    Debug,
    /// refactor, rename, cleanup, restructure, simplify, extract,
    /// deduplicate, reorganize — up scope, prefer convention.
    Refactor,
    /// document, readme, changelog, comment, docstring, docs, tutorial,
    /// guide — near-neutral mild adjustments.
    Docs,
    /// investigate, analyze, understand, why, explore, find out,
    /// root cause, audit, trace — up relevance, prefer fact + preference.
    Investigation,
}

/// Classify a task description string into a [`TaskKind`] using a
/// deterministic keyword scan over the lowercased text. No model call.
///
/// Precedence (highest wins when multiple sets match):
///   Debug > Investigation > Refactor > Docs > Feature
pub fn classify_task(task: &str) -> TaskKind {
    let lower = task.to_ascii_lowercase();

    // Debug keywords (highest priority)
    const DEBUG_KW: &[&str] = &[
        "fix",
        "bug",
        "error",
        "fail",
        "crash",
        "panic",
        "regression",
        "broken",
        "debug",
        "stack trace",
        "exception",
    ];
    if DEBUG_KW.iter().any(|kw| lower.contains(kw)) {
        return TaskKind::Debug;
    }

    // Investigation keywords
    const INVESTIGATE_KW: &[&str] = &[
        "investigate",
        "analyze",
        "understand",
        " why ",
        "explore",
        "find out",
        "root cause",
        "audit",
        "trace",
    ];
    if INVESTIGATE_KW.iter().any(|kw| lower.contains(kw)) {
        return TaskKind::Investigation;
    }

    // Refactor keywords
    const REFACTOR_KW: &[&str] = &[
        "refactor",
        "rename",
        "cleanup",
        "clean up",
        "restructure",
        "simplify",
        "extract",
        "deduplicate",
        "reorganize",
    ];
    if REFACTOR_KW.iter().any(|kw| lower.contains(kw)) {
        return TaskKind::Refactor;
    }

    // Docs keywords
    const DOCS_KW: &[&str] = &[
        "document",
        "readme",
        "changelog",
        "comment",
        "docstring",
        "docs",
        "tutorial",
        "guide",
    ];
    if DOCS_KW.iter().any(|kw| lower.contains(kw)) {
        return TaskKind::Docs;
    }

    // Default: Feature (neutral)
    TaskKind::Feature
}

/// Compose task-kind weight biases on top of the stage weights.
///
/// For `Feature`, returns `base` UNCHANGED — this is the neutrality
/// guarantee that keeps all existing retrieval tests green.
///
/// For other kinds, one component is multiplied by a bias factor and
/// the result is renormalized so the four weights still sum to the same
/// total as `base`, preserving overall scoring magnitude (just the mix
/// changes).
///
/// Bias factors (applied before renorm):
/// - Debug       → freshness × 1.6  (recent failures matter most)
/// - Refactor    → scope × 1.6      (project/repo conventions matter most)
/// - Investigation → relevance × 1.4 (broad fact/preference recall)
/// - Docs        → mild (confidence × 1.15, near-neutral)
fn weights_for_task_kind(base: StageWeights, kind: TaskKind) -> StageWeights {
    match kind {
        TaskKind::Feature => base,
        TaskKind::Debug => renorm(StageWeights {
            freshness: base.freshness * 1.6,
            ..base
        }),
        TaskKind::Refactor => renorm(StageWeights {
            scope: base.scope * 1.6,
            ..base
        }),
        TaskKind::Investigation => renorm(StageWeights {
            relevance: base.relevance * 1.4,
            ..base
        }),
        TaskKind::Docs => renorm(StageWeights {
            confidence: base.confidence * 1.15,
            ..base
        }),
    }
}

/// Renormalize `StageWeights` so the four components sum to the same
/// total as before the bias was applied. This preserves scoring
/// magnitude — only the mix changes.
fn renorm(w: StageWeights) -> StageWeights {
    let sum = w.relevance + w.confidence + w.freshness + w.scope;
    if sum <= f32::EPSILON {
        return w;
    }
    // The original sum (before any bias) isn't available here; instead
    // we scale to 1.0 and then the absolute scores are comparable
    // because normalize_and_score already places components in [0,1].
    // NOTE: the stage weights themselves don't need to sum to 1.0 —
    // the existing defaults (0.5+0.2+0.2+0.1=1.0) do, but the
    // renormalization target should be the unbiased sum so we don't
    // change the overall scale. Since we only modify ONE component by a
    // small factor, we scale back to 1.0 (the natural target).
    StageWeights {
        relevance: w.relevance / sum,
        confidence: w.confidence / sum,
        freshness: w.freshness / sum,
        scope: w.scope / sum,
    }
}

/// Return the additional `prefer_roles` hints implied by `kind`.
///
/// These are MERGED with any caller-supplied `prefer_roles` (not
/// clobbered), so the task-kind bias is additive.
/// For `Feature`, returns an empty slice — zero effect on existing behaviour.
fn task_kind_prefer_roles(kind: TaskKind) -> &'static [&'static str] {
    match kind {
        TaskKind::Feature => &[],
        TaskKind::Debug => &["failure_pattern"],
        TaskKind::Refactor => &["convention"],
        TaskKind::Investigation => &["fact", "preference"],
        TaskKind::Docs => &["convention"],
    }
}
use time::OffsetDateTime;

use crate::embeddings::{
    self, DEFAULT_HYBRID_ALPHA, Embedder, cosine_similarity, decode_embedding,
};

/// v0.4.2: a pre-computed query embedding paired with the producing
/// model's id. Threaded down into [`memory_candidates`] so each row
/// can decide whether to contribute a cosine term (only when the
/// row's `embedding_model` matches the active query's `model_id`).
///
/// S5.1: `pub(crate)` so `backend.rs` can name the type in the
/// `RetrievalBackend` trait signature without exposing it outside the crate.
#[derive(Debug, Clone)]
pub(crate) struct QueryEmbedding {
    pub(crate) vector: Vec<f32>,
    pub(crate) model_id: String,
}

impl QueryEmbedding {
    fn from_embedder(embedder: &dyn Embedder, query: &str) -> Option<Self> {
        if embedder.is_noop() {
            return None;
        }
        match embedder.embed(query) {
            Ok(v) if v.len() == embedder.dim() => Some(Self {
                vector: v,
                model_id: embedder.model_id().to_string(),
            }),
            // NotImplemented / dim-mismatch / load failure → silently
            // skip the cosine blend. v0.4.2 surfaces no warning here
            // by design — the broker stays usable on best-effort
            // semantic retrieval.
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextCapsule {
    pub id: String,
    pub kind: String,
    pub summary: String,
    pub token_estimate: u32,
    pub expansion_handle: String,
    pub provenance: Vec<ProvenanceRef>,
    pub confidence: f32,
    pub freshness: f32,
    pub relevance: f32,
    pub scope_weight: f32,
    pub score: f32,
    /// v2.7: set by [`apply_supersession_penalty`] when a newer near-duplicate
    /// sibling was also a candidate. Carried on the capsule so the penalty can
    /// be REAPPLIED after cross-encoder reranking — the reranker scores pure
    /// query relevance and would otherwise resurrect the older twin whenever
    /// the query's wording happens to match it better (measured: resolution
    /// 0.58 → 0.36 when reranking landed without this flag).
    #[serde(default)]
    pub superseded_hint: bool,
    /// Legacy serialized usefulness sign; bounded when reranking old capsules.
    #[serde(default)]
    pub rerank_policy_tier: i8,
    /// Claim identity read in the same SQLite snapshot as the hydrated text.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub claim_revision: Option<String>,
    /// Structured evidence read alongside this capsule text and revision.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub facts: Vec<crate::fact_store::StoredFact>,
    /// Decayed usefulness multiplier and provenance discount carried to reranking.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rerank_usefulness: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rerank_trust: Option<f32>,
}

/// Revision bindings for the actual delivered capsules. Conflicting versions of
/// one ID are omitted because the legacy event map can represent only one claim.
pub fn memory_revision_bindings(
    capsules: &[ContextCapsule],
) -> std::collections::BTreeMap<String, String> {
    let mut bindings = std::collections::BTreeMap::new();
    let mut ambiguous = std::collections::HashSet::new();
    for c in capsules {
        if let (Some(id), Some(revision)) = (
            c.expansion_handle.strip_prefix("memory:"),
            c.claim_revision.as_ref(),
        ) {
            if bindings.get(id).is_some_and(|old| old != revision) {
                ambiguous.insert(id.to_string());
            }
            bindings.insert(id.to_string(), revision.clone());
        }
    }
    for id in ambiguous {
        bindings.remove(&id);
    }
    bindings
}

impl ContextCapsule {
    /// v1.0.0: build a render-only capsule from daemon wire data. Only the
    /// fields the hook renders (`summary`, `kind`, `score`) are meaningful;
    /// the rest are zeroed — this capsule is never re-scored or expanded.
    pub fn wire_minimal(summary: String, kind: String, score: f32) -> Self {
        Self {
            id: String::new(),
            kind,
            summary,
            token_estimate: 0,
            expansion_handle: String::new(),
            provenance: Vec::new(),
            confidence: 0.0,
            freshness: 0.0,
            relevance: 0.0,
            scope_weight: 0.0,
            score,
            superseded_hint: false,
            rerank_policy_tier: 0,
            claim_revision: None,
            facts: vec![],
            rerank_usefulness: None,
            rerank_trust: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceRef {
    pub source: String,
    pub id: String,
    pub excerpt: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct ContextRequest {
    /// Hydrate structured evidence only for consumers that explicitly request it.
    pub include_fact_evidence: bool,
    /// Defer intermediate budgeting to a final evidence-aware renderer; requires a bounded pool.
    pub defer_fact_budget: bool,
    pub stage: String,
    pub query: String,
    pub budget_tokens: u32,
    /// v2.6: per-request override for how the lexical and semantic rankings
    /// are merged (`"linear"` / `"rrf"`; see [`crate::fusion`]).
    ///
    /// Empty (the default) means "use `[broker] fusion`". This exists so
    /// `kimetsu brain tune` can sweep the two rules against one corpus in one
    /// process — the reason the shipped default is still `linear` is that
    /// nothing had measured the alternative on a real brain.
    pub fusion: String,
    /// v2.6: per-request override for how `raw_relevance` is normalized into
    /// the `relevance` term (`"per_kind"` / `"global"`; see
    /// [`Normalization`]).
    ///
    /// Empty (the default) means "use `[broker] normalization`". Exists for
    /// the same reason `fusion` does: the alternative had to be measurable on
    /// one corpus in one process before it could be argued for.
    pub normalization: String,
    /// v0.6: domain-hint tags. Capsules whose text or kind contains any
    /// of these strings receive a 1.4× score boost, pushing on-domain
    /// capsules above the `min_score` threshold when they would otherwise
    /// be filtered out.
    pub tags: Vec<String>,
    /// v0.6: minimum composite score for inclusion. When > 0.0 and the
    /// top-scoring capsule falls below this threshold, `ContextBundle`
    /// is returned with `skipped: true` and an empty capsule list —
    /// zero tokens injected. 0.0 (default) disables the check.
    pub min_score: f32,
    /// v0.6: hard cap on returned capsules regardless of token budget.
    /// 0 = no cap (budget-only limit, prior behaviour).
    pub max_capsules: usize,
    /// v0.6: role-preference boost. Capsules whose `kind` matches one
    /// of these strings receive an additional 1.3× multiplier after the
    /// tag boost (e.g. `["semantic_operator", "anti_pattern"]` for bench).
    pub prefer_roles: Vec<String>,
    /// v0.8: hard kind filter applied BEFORE scoring + capping. When
    /// non-empty, only candidates whose capsule `kind` is in this list
    /// survive — so a higher-ranked repo file or off-kind memory can't
    /// consume a (often single) slot. Used by the proactive engine to
    /// restrict recall to actionable kinds (failure_pattern, command,
    /// convention). Empty (default) keeps all kinds, prior behaviour.
    pub kinds: Vec<String>,
    /// D1e: absolute cosine-similarity floor. On embeddings builds,
    /// memory candidates whose cosine to the query is below this
    /// threshold are dropped before budgeting. 0.0 (default) disables
    /// the floor — matches pre-D1e behaviour. Repo-file and manifest
    /// candidates are unaffected (they have no cosine score). Populated
    /// from `BrokerSection.min_semantic_score` by the pipeline; callers
    /// that don't set it get the prior behaviour automatically.
    pub min_semantic_score: f32,
    /// Explicit public override: None preserves legacy zero=inherited; Some(0)
    /// disables, Some(-1) selects model auto, Some(positive) sets a floor.
    pub min_semantic_score_override: Option<f32>,
    /// v1.0.0: absolute *lexical* relevance floor for memory candidates,
    /// as the fraction of the query's IDF-weighted discriminating power a
    /// memory must cover. Unlike `min_semantic_score` this needs no query
    /// embedding, so it protects the FTS-only hook path. When > 0.0, memory
    /// candidates below the floor are dropped BEFORE scoring (so they don't
    /// even set the per-kind normalization max). Repo-file/manifest
    /// candidates are unaffected. 0.0 (default) disables it — every existing
    /// `..Default::default()` construction is unchanged. Populated from
    /// `BrokerSection.min_lexical_coverage` by the pipeline.
    pub min_lexical_coverage: f32,
    /// Some(0) explicitly disables the lexical floor; None inherits legacy behavior.
    pub min_lexical_coverage_override: Option<f32>,
    /// E3: inferred kind of the current task. Defaults to `Feature`
    /// (the neutral kind) so every existing `..Default::default()`
    /// construction is unchanged — Feature does NOT alter weights or
    /// prefer_roles. Set by the pipeline via `classify_task` at intake.
    pub task_kind: TaskKind,
    /// v2.7: ABSOLUTE abstention floor. `min_score` above compares against the
    /// normalized composite, whose top candidate always carries relevance 1.0
    /// — it can rank candidates but cannot express "nothing here is genuinely
    /// relevant", so it never abstains on a plausible-but-wrong corpus (the
    /// workflow benchmark measured false-injection 1.00 at a 60-memory brain).
    /// This floor gates on absolute evidence instead: the best raw cosine any
    /// memory candidate achieved. When > 0.0 and no cosine-backed memory
    /// candidate clears it — and the bundle would contain only memory capsules
    /// — the retrieval returns `skipped: true` with zero tokens injected.
    /// Lexical-only and cross-model candidates are unmeasured on this scale and
    /// therefore exempt. Repo-file/manifest capsules also suppress the gate: an
    /// FTS hit on real repo content is its own evidence the bundle is useful.
    /// 0.0 (default) disables the gate. Populated from
    /// `BrokerSection.abstain_min_score` by the pipeline.
    pub abstain_evidence: f32,
    /// Some(0) disables abstention; Some(-1) uses model auto; None inherits.
    pub abstain_evidence_override: Option<f32>,
}

#[derive(Debug, Clone)]
pub struct ContextBundle {
    pub stage: String,
    pub budget_tokens: u32,
    pub used_tokens: u32,
    pub capsules: Vec<ContextCapsule>,
    pub excluded: Vec<ContextCapsule>,
    /// v0.6: true when the top capsule score was below `min_score`.
    /// All capsules are empty; no tokens were injected.
    pub skipped: bool,
    /// v0.6: best composite score observed before the skip check.
    /// Useful for diagnostics ("why was the brain silent?").
    pub top_score: f32,
    /// v2.7: best ABSOLUTE cosine evidence any memory candidate achieved.
    /// Unlike `top_score` this is not normalized, so "0.42" means the same
    /// thing on a 3-memory brain and a 3000-memory brain. `-1.0` means no
    /// comparable cosine was available (lean builds or cross-model rows), so
    /// the cosine-calibrated gate has no verdict. Exposed for diagnostics and
    /// threshold sweeps.
    pub top_abs_evidence: f32,
    /// v2.6: what fraction of the query's discriminating power the returned
    /// capsules cover, *collectively*, in `[0, 1]`.
    ///
    /// Kimetsu already abstains at the bundle level — nothing above
    /// `min_score` means an empty bundle and zero tokens. What it never did is
    /// say anything about a bundle it *does* return, so a reader handed three
    /// capsules that touch half the question has no way to tell that from
    /// three that answer it, and confabulates the rest. That is what BEAM's
    /// abstention track measures, and where Kimetsu scores worst (45% / 30%).
    ///
    /// IDF-weighted against the corpus, so a query term present in every
    /// memory contributes nothing and a rare one dominates — the same weighting
    /// the per-memory lexical floor uses, applied to the bundle as a whole.
    /// 1.0 when there is no discriminating term to measure against.
    pub evidence_coverage: f32,
    /// v2.6: the discriminating query terms *no* returned capsule mentions.
    ///
    /// The actionable half of `evidence_coverage`: a reader can be told
    /// precisely what memory does not know about, rather than being handed a
    /// number. Empty when coverage is complete or unmeasurable.
    pub uncovered_terms: Vec<String>,
    /// v2.6: true when the query asked about order and the capsules were
    /// re-rendered chronologically, oldest first, each carrying its date.
    ///
    /// The reader needs to be told, or a time-ordered bundle looks like a
    /// relevance-ranked one whose ranking has gone wrong. See
    /// [`crate::ordering`] for why ordering is rendered rather than retrieved.
    pub chronological: bool,
    /// Conflicts observed in eligible evidence before delivery trimming.
    pub known_fact_conflicts: Vec<String>,
}

/// Discriminating weight per query token, for *bundle* coverage.
///
/// Deliberately not [`corpus_token_idf`]. That one zeroes a token the corpus
/// has never seen (`df == 0`), because for the per-memory floor an
/// out-of-corpus word would sink every candidate — the on-topic memory that
/// matches the rare in-corpus word would be wrongly pruned.
///
/// For coverage the same fact means the opposite. A query term that appears in
/// **no** memory is the strongest possible evidence that memory does not cover
/// this question, which is precisely what the reader needs to be told. Zeroing
/// it would make "how do I checkpoint the WAL during a Kubernetes rollout"
/// report full coverage on the strength of the WAL half alone — the exact
/// confabulation this is meant to prevent.
///
/// So `df == 0` gets the maximal weight, and only `df == N` (present in every
/// memory, e.g. the project name) is zeroed.
fn coverage_token_idf(conn: &Connection, tokens: &[String]) -> KimetsuResult<HashMap<String, f32>> {
    token_idf(conn, tokens, false)
}

/// Render the partial-evidence warning for a bundle, if it needs one.
///
/// The point is to let a reader abstain on Kimetsu's advice rather than
/// confabulate from partial evidence. Naming the missing terms is what makes
/// that actionable — "memory does not cover X" is a fact the reader can act on,
/// where a coverage number is not.
///
/// Returns `None` when coverage is adequate, so a complete bundle costs nothing.
pub fn partial_evidence_notice(bundle: &ContextBundle) -> Option<String> {
    if bundle.skipped || bundle.capsules.is_empty() {
        return None; // an empty bundle already says everything it can
    }
    if bundle.evidence_coverage > PARTIAL_EVIDENCE_COVERAGE || bundle.uncovered_terms.is_empty() {
        return None;
    }
    // Cap the list: naming twenty terms is noise, and the first few are the
    // highest-IDF ones anyway (content_tokens preserves query order, and the
    // uncovered list is filtered from it).
    const MAX_NAMED: usize = 6;
    let named: Vec<&str> = bundle
        .uncovered_terms
        .iter()
        .take(MAX_NAMED)
        .map(String::as_str)
        .collect();
    let more = bundle.uncovered_terms.len().saturating_sub(named.len());
    let suffix = if more > 0 {
        format!(" (and {more} more)")
    } else {
        String::new()
    };
    Some(format!(
        "Partial memory: nothing above covers {}{}. Treat the rest as unknown \
         rather than inferring it.",
        named.join(", "),
        suffix
    ))
}

/// Coverage at or below which a bundle is worth flagging as partial.
///
/// Chosen to mirror `min_lexical_coverage`'s default (0.5): a bundle that
/// collectively covers less of the query than a single memory would need to
/// survive the per-memory floor is, by the system's own standard, thin.
pub const PARTIAL_EVIDENCE_COVERAGE: f32 = 0.5;

/// Measure how much of `query`'s discriminating power `capsules` collectively
/// cover, and which terms none of them mention.
///
/// Deliberately computed over the *union* of the capsules rather than the best
/// one: the question is whether the bundle answers the query, not whether any
/// single memory does.
pub(crate) fn evidence_coverage(
    conn: &Connection,
    query: &str,
    capsules: &[ContextCapsule],
) -> (f32, Vec<String>) {
    let content = content_tokens(query);
    if content.is_empty() {
        return (1.0, Vec::new());
    }
    let Ok(idf) = coverage_token_idf(conn, &content) else {
        return (1.0, Vec::new());
    };
    // Everything the bundle says, lowercased once.
    let haystack = capsules
        .iter()
        .map(|c| c.summary.to_ascii_lowercase())
        .collect::<Vec<_>>()
        .join(" ");

    let mut total = 0.0f32;
    let mut hit = 0.0f32;
    let mut uncovered = Vec::new();
    for token in &content {
        let weight = idf.get(token).copied().unwrap_or(0.0);
        if weight <= 0.0 {
            continue; // corpus-ubiquitous or out-of-corpus: no signal either way
        }
        total += weight;
        if haystack.contains(token.as_str()) {
            hit += weight;
        } else {
            uncovered.push(token.clone());
        }
    }
    if total <= f32::EPSILON {
        // No discriminating term to measure against — claiming a gap here
        // would make every vague query look like a memory failure.
        return (1.0, Vec::new());
    }
    (hit / total, uncovered)
}

/// S5.1: a single memory candidate produced by candidate generation and
/// consumed by the broker (scoring, floors, rerank).
///
/// `pub(crate)` so `backend.rs` can name the type in the `RetrievalBackend`
/// trait signature without exposing it outside the crate.
#[derive(Debug, Clone)]
pub(crate) struct Candidate {
    pub(crate) capsule: ContextCapsule,
    pub(crate) raw_relevance: f32,
    /// D1e: the row's embedding vector, present when the row's
    /// `embedding_model` matches the active query embedder's id.
    /// `None` for repo-file/manifest candidates and for memory rows
    /// whose model differs from the active embedder (cross-model
    /// rows). Used by the candidate-stage embedding-MMR pass.
    pub(crate) embedding: Option<Vec<f32>>,
    /// D1e: raw cosine similarity between this candidate and the
    /// query embedding. Present when `embedding` is `Some`. Used for
    /// the absolute semantic relevance floor (min_semantic_score).
    pub(crate) cosine: Option<f32>,
    /// v2.6: the memory's RFC 3339 creation time, carried so the bundle can be
    /// re-rendered in time order when the query asks about sequence (see
    /// [`crate::ordering`]). `None` for repo files and manifests, which have no
    /// position in the memory timeline.
    pub(crate) created_at: Option<String>,
}

pub fn retrieve_context(
    conn: &Connection,
    repo_root: &str,
    weights: &BrokerWeights,
    request: ContextRequest,
) -> KimetsuResult<ContextBundle> {
    retrieve_context_multi(conn, repo_root, weights, request, &[])
}

/// v0.4.1: multi-conn variant. `extra_memory_conns` is searched for
/// memory candidates only (repo files + manifests stay project-local).
/// The candidate stream is concatenated BEFORE normalization so the
/// blended set is normalized together — keeping a user-brain capsule
/// and a project-brain capsule comparable on the same `raw_relevance`
/// scale.
///
/// Today `extra_memory_conns` carries at most one entry (the user
/// brain at `~/.kimetsu/brain.db`); the slice shape leaves room for
/// future scope tiers (team brain, org brain) without breaking the
/// signature.
///
/// v0.4.2: uses [`embeddings::open_default_embedder`] for the cosine
/// term. Pre-v0.4.3 the default is `NoopEmbedder`, which short-
/// circuits the cosine path so retrieval stays FTS-only — exact
/// v0.4.1 behavior. v0.4.3 swaps the default to a real embedder.
pub fn retrieve_context_multi(
    conn: &Connection,
    repo_root: &str,
    weights: &BrokerWeights,
    request: ContextRequest,
    extra_memory_conns: &[&Connection],
) -> KimetsuResult<ContextBundle> {
    let embedder = embeddings::open_default_embedder();
    retrieve_context_with_embedder(
        conn,
        repo_root,
        weights,
        request,
        extra_memory_conns,
        embedder,
    )
}

/// v0.4.2: explicit-embedder variant. Lets tests inject `StubEmbedder`
/// or any other [`Embedder`] without going through
/// [`embeddings::open_default_embedder`]. v0.4.3 callers (chat REPL,
/// MCP server) can also use this directly to hold one embedder
/// instance for the lifetime of a session instead of paying the
/// model-load cost on every retrieval.
///
/// S5.1: delegates to [`retrieve_context_with_embedder_and_backend`] with
/// the default [`crate::backend::FlatBackend`]. All existing call sites
/// (including the full test suite) are unchanged and continue to get exactly
/// the pre-S5.1 FTS + ANN behaviour.
pub fn retrieve_context_with_embedder(
    conn: &Connection,
    repo_root: &str,
    weights: &BrokerWeights,
    request: ContextRequest,
    extra_memory_conns: &[&Connection],
    embedder: &dyn Embedder,
) -> KimetsuResult<ContextBundle> {
    retrieve_context_with_embedder_and_backend(
        conn,
        repo_root,
        weights,
        request,
        extra_memory_conns,
        embedder,
        &crate::backend::FlatBackend {
            fusion: crate::fusion::Fusion::Linear,
        },
    )
}

/// S5.1: backend-aware variant of [`retrieve_context_with_embedder`].
///
/// Identical to `retrieve_context_with_embedder` except that the memory
/// candidate step is delegated to `backend.memory_candidates()` instead of
/// the hard-coded [`memory_candidates`] call. The broker (lexical/semantic
/// floors, scoring, MMR, compression, budgeting) runs ABOVE the backend and
/// is backend-agnostic.
///
/// [`BrainSession`] methods call this variant so the `[storage] backend`
/// config field takes effect. Tests that call `retrieve_context_with_embedder`
/// directly still use [`crate::backend::FlatBackend`] implicitly — zero
/// behaviour change.
pub(crate) fn retrieve_context_with_embedder_and_backend(
    conn: &Connection,
    repo_root: &str,
    weights: &BrokerWeights,
    request: ContextRequest,
    extra_memory_conns: &[&Connection],
    embedder: &dyn Embedder,
    backend: &dyn crate::backend::RetrievalBackend,
) -> KimetsuResult<ContextBundle> {
    let query_embedding = QueryEmbedding::from_embedder(embedder, &request.query);
    let half_life_days = weights.decay_half_life_days;
    let mut candidates = Vec::new();
    candidates.extend(backend.memory_candidates(
        conn,
        &request.query,
        query_embedding.as_ref(),
        half_life_days,
        request.include_fact_evidence,
    )?);
    for extra in extra_memory_conns {
        candidates.extend(backend.memory_candidates(
            extra,
            &request.query,
            query_embedding.as_ref(),
            half_life_days,
            request.include_fact_evidence,
        )?);
    }
    // v2.5.2 consolidation v1: bounded query-association routing boost —
    // memories that repeatedly answered SIMILAR past queries (per the
    // citation-derived query_routes table) gain up to ROUTING_BOOST_CAP
    // relevance from a fixed per-retrieval budget. Applied to memory
    // candidates only, before file/manifest candidates join the pool.
    crate::reinforce::apply_query_routing(
        conn,
        &request.query,
        query_embedding.as_ref(),
        &mut candidates,
    );

    candidates.extend(repo_file_candidates(conn, repo_root, &request.query, 30)?);
    candidates.extend(manifest_candidates(conn, repo_root, &request.query)?);

    // v0.8: proactive kind filter — restrict to actionable kinds BEFORE
    // scoring + capping so a higher-ranked repo file or off-kind memory
    // can't take the proactive slot and get filtered out afterwards.
    // Memory capsules carry the generic `kind: "memory"` and encode the
    // real memory kind in the summary prefix ("scope:kind - text"), so
    // match against that for memories.
    if !request.kinds.is_empty() {
        candidates.retain(|c| {
            request
                .kinds
                .iter()
                .any(|k| capsule_matches_kind(&c.capsule, k))
        });
    }

    // v1.0.0: absolute LEXICAL relevance floor. The FTS-only hook path has
    // no cosine, so the `min_semantic_score` floor below can't protect it —
    // a broad conceptual query whose only matching tokens are corpus-
    // ubiquitous (e.g. the project name) would otherwise surface unrelated
    // memories, which per-kind normalization later promotes to relevance=1.0
    // regardless of how weak the match is.
    //
    // We compute an IDF-weighted coverage in [0,1] over the query's CONTENT
    // tokens (stopwords removed; ubiquitous tokens carry ~0 IDF so they don't
    // drive coverage) and drop a memory candidate when its coverage is below
    // the floor AND it has no semantic support. Applied BEFORE scoring so
    // pruned rows don't even set the per-kind normalization max. Only memory
    // candidates are floored — repo_file/manifest capsules pass through (an
    // FTS match on file content is itself a relevance signal, and overview
    // queries *want* the README). Inert when the floor is 0.0 or the query
    // has no discriminating (non-ubiquitous) content token.
    if request.min_lexical_coverage > 0.0 {
        let content = content_tokens(&request.query);
        if !content.is_empty() {
            let idf = corpus_token_idf(conn, &content)?;
            let total_idf: f32 = content
                .iter()
                .map(|t| idf.get(t).copied().unwrap_or(0.0))
                .sum();
            // Skip the floor when no content token is discriminating — every
            // token is corpus-ubiquitous, so we have no signal to floor on.
            if total_idf > f32::EPSILON {
                candidates.retain(|c| {
                    if c.capsule.kind != "memory" {
                        return true; // repo_file / manifest pass through
                    }
                    // Semantic support keeps a lexically-thin but on-topic
                    // memory on embeddings builds (cosine is None on the hook).
                    if c.cosine.is_some_and(|cos| cos >= SEMANTIC_KEEP_COSINE) {
                        return true;
                    }
                    weighted_coverage(&content, &idf, &c.capsule.summary)
                        >= request.min_lexical_coverage
                });
            }
        }
    }

    // E3: compose task-kind weight bias over stage weights, then renormalize.
    // For Feature (default), weights_for_task_kind returns the base unchanged.
    let stage_weights = weights_for_stage(weights, &request.stage);
    let effective_weights = weights_for_task_kind(stage_weights, request.task_kind);
    normalize_and_score(
        &mut candidates,
        effective_weights,
        Normalization::from_config(&request.normalization),
    );

    // E3: merge task-kind prefer_role hints with caller-supplied prefer_roles.
    // For Feature the hints are empty so this is a no-op (neutral).
    let kind_role_hints = task_kind_prefer_roles(request.task_kind);
    let mut effective_prefer_roles: Vec<String> = request.prefer_roles.clone();
    for &hint in kind_role_hints {
        let hint_s = hint.to_string();
        if !effective_prefer_roles.contains(&hint_s) {
            effective_prefer_roles.push(hint_s);
        }
    }

    // v0.6: apply tag boost (1.4×) and role-preference boost (1.3×) after
    // normalisation so the multipliers operate on the [0,1]-normalised score
    // rather than the raw pre-normalisation values.
    //
    // E3: the role-preference check uses `capsule_matches_kind` so that
    // memory capsules (whose outer `kind` is always `"memory"`) are matched
    // against the real sub-kind embedded in their summary prefix
    // (`"scope:kind - text"`). This makes task-kind prefer_role hints
    // (e.g. "failure_pattern" for Debug) actually work for memory capsules.
    // For non-memory capsules (repo_file, manifest) the outer kind is checked
    // directly — same behaviour as before for caller-supplied prefer_roles.
    if !request.tags.is_empty() || !effective_prefer_roles.is_empty() {
        let tags_lc: Vec<String> = request
            .tags
            .iter()
            .map(|t| t.to_ascii_lowercase())
            .collect();
        for c in &mut candidates {
            let summary_lc = c.capsule.summary.to_ascii_lowercase();
            if !tags_lc.is_empty() && tags_lc.iter().any(|t| summary_lc.contains(t.as_str())) {
                c.capsule.score *= 1.4;
            }
            if !effective_prefer_roles.is_empty()
                && effective_prefer_roles.iter().any(|r| {
                    // For memory capsules: check the real sub-kind embedded in the
                    // summary prefix ("scope:kind - text") via capsule_matches_kind.
                    // This makes task-kind prefer_role hints work for memory capsules
                    // whose outer `kind` field is always the generic "memory" string.
                    // For non-memory capsules: fall back to the original substring
                    // check on the outer `kind` field (preserves v0.6 behaviour for
                    // caller-supplied prefer_roles like "semantic_operator").
                    if c.capsule.kind == "memory" {
                        capsule_matches_kind(&c.capsule, r.as_str())
                    } else {
                        c.capsule.kind.contains(r.as_str())
                    }
                })
            {
                c.capsule.score *= 1.3;
            }
        }
    }

    // v2.7: newer-wins supersession penalty. The workflow benchmark measured
    // that a cited incumbent buries its own replacement: the usefulness boost
    // feeds the relevance axis, freshness cannot distinguish memories written
    // minutes apart (30-day half-life), and nothing at ranking time knows two
    // candidates conflict. When two memory candidates are near-duplicates by
    // embedding cosine, the OLDER one is penalized so the newer statement of
    // the same topic wins the ordering regardless of its sibling's citations.
    // Inert on lean builds (no embeddings) and for genuinely distinct memories.
    apply_supersession_penalty(&mut candidates);

    // D1e-2: absolute semantic relevance floor. On embeddings builds
    // (query_embedding is Some), drop candidates whose cosine to the
    // query is strictly below min_semantic_score. This ensures a
    // genuinely-irrelevant corpus hits the zero-capsule skipped path
    // rather than surfacing its "best of a bad lot". Inert on lean
    // builds (query_embedding is None) or when floor is 0.0.
    //
    // Applied BEFORE the candidate→capsule conversion so irrelevant
    // rows don't consume budget or affect normalization.
    //
    // Only applied to memory candidates (those with cosine populated);
    // repo_file and manifest candidates have cosine=None and are
    // always passed through — they're matched by FTS which is already
    // a signal of relevance.
    if query_embedding.is_some() && request.min_semantic_score > 0.0 {
        candidates.retain(|c| {
            // Keep non-memory candidates (no cosine) and memory
            // candidates that cleared the floor.
            match c.cosine {
                Some(cos) => cos >= request.min_semantic_score,
                None => true,
            }
        });
    }

    // D1e-1: candidate-stage embedding-MMR. On embeddings builds,
    // apply MMR over the ranked Vec<Candidate> using cosine similarity
    // between candidate embeddings as the redundancy measure. This
    // collapses true semantic near-duplicates ("prefer rg over grep"
    // and "use ripgrep") that Jaccard-of-tokens would miss.
    //
    // When EITHER candidate lacks an embedding (repo-file, manifest,
    // or a cross-model memory row), falls back to Jaccard similarity
    // of summary tokens — the same measure the existing capsule-stage
    // MMR uses. This preserves lean parity exactly.
    //
    // Sort by score descending first so the greedy MMR seeds on the
    // top-scoring candidate (same as the capsule-stage MMR).
    candidates.sort_by(|a, b| {
        b.capsule
            .score
            .partial_cmp(&a.capsule.score)
            .unwrap_or(Ordering::Equal)
            .then_with(|| {
                b.capsule
                    .freshness
                    .partial_cmp(&a.capsule.freshness)
                    .unwrap_or(Ordering::Equal)
            })
            // Deterministic tiebreak on the STABLE handle (memory:<id> /
            // file:<path>) — capsule.id is a fresh random ULID per retrieval,
            // so tiebreaking on it would make retrieval non-reproducible on
            // score+freshness ties.
            .then_with(|| a.capsule.expansion_handle.cmp(&b.capsule.expansion_handle))
    });

    // Run embedding-MMR on embeddings builds; lean builds skip directly
    // to the capsule-stage Jaccard MMR below.
    let embedding_mmr_ran = query_embedding.is_some() && !candidates.is_empty();
    let candidates = if embedding_mmr_ran {
        apply_candidate_mmr_diversity(candidates, 0.7)
    } else {
        candidates
    };

    // v2.6: keep each memory's creation time keyed by its stable handle before
    // the candidates are consumed. Only built when the question is actually
    // about order — on every other query it would be a map nobody reads.
    let created_at_by_handle: std::collections::HashMap<String, String> =
        if crate::ordering::is_ordering_query(&request.query) {
            candidates
                .iter()
                .filter_map(|c| {
                    c.created_at
                        .clone()
                        .map(|ts| (c.capsule.expansion_handle.clone(), ts))
                })
                .collect()
        } else {
            std::collections::HashMap::new()
        };

    // v2.7: best absolute evidence over the surviving memory candidates —
    // COSINE ONLY. Lexical relevance lives on a different scale (token
    // overlap, ~0.2-0.6 for good matches) and comparing it against a
    // cosine-calibrated floor silently killed every lexical-only retrieval
    // (lean builds, cross-model rows). When no candidate carries a cosine the
    // gate has no verdict: -1.0 = "unmeasured", and both the hard gate below
    // and the band arbitration treat it as exempt.
    let top_abs_evidence = candidates
        .iter()
        .filter(|c| c.capsule.kind == "memory")
        .filter_map(|c| c.cosine)
        .fold(f32::NAN, f32::max);
    let top_abs_evidence = if top_abs_evidence.is_nan() {
        -1.0
    } else {
        top_abs_evidence
    };
    // Repo-file/manifest capsules suppress the evidence gate: an FTS hit on
    // real repo content is its own evidence the bundle is useful.
    let memory_only = candidates.iter().all(|c| c.capsule.kind == "memory");

    let mut capsules = candidates
        .into_iter()
        .map(|candidate| candidate.capsule)
        .collect::<Vec<_>>();

    // After embedding-MMR the candidate list is already in MMR order.
    // On lean builds (no embedding-MMR) we still need to sort by score.
    if !embedding_mmr_ran {
        capsules.sort_by(|left, right| {
            right
                .score
                .partial_cmp(&left.score)
                .unwrap_or(Ordering::Equal)
                .then_with(|| {
                    right
                        .freshness
                        .partial_cmp(&left.freshness)
                        .unwrap_or(Ordering::Equal)
                })
                // Stable handle tiebreak (capsule.id is random per retrieval).
                .then_with(|| left.expansion_handle.cmp(&right.expansion_handle))
        });
    }

    // v0.6: confidence-aware skip — if the top score is below the caller's
    // threshold, return an empty bundle immediately. Zero tokens injected.
    //
    // v2.7: joined by the absolute abstention gate. `top_score` is normalized
    // (the best candidate always carries relevance 1.0), so `min_score` ranks
    // but cannot abstain; `abstain_evidence` compares the best RAW cosine /
    // relevance against an absolute floor, so a corpus with nothing genuinely
    // relevant stays silent instead of shipping its best-of-a-bad-lot.
    let top_score = capsules.first().map(|c| c.score).unwrap_or(0.0);
    let composite_skip = request.min_score > 0.0 && top_score < request.min_score;
    // The hard floor sits one band-width BELOW the configured threshold: the
    // [threshold - width, threshold) band is not decided here but by
    // [`rerank_and_arbitrate`] at the call sites that own a cross-encoder —
    // raw bi-encoder cosine under-scores paraphrased matches, and the band is
    // exactly where those live. Callers without a reranker fail the band
    // closed, which reproduces the plain hard-gate behavior.
    let evidence_skip = request.abstain_evidence > 0.0
        && memory_only
        && top_abs_evidence >= 0.0
        && top_abs_evidence < (request.abstain_evidence - abstain_band_width()).max(0.0);
    if composite_skip || evidence_skip {
        return Ok(ContextBundle {
            stage: request.stage,
            budget_tokens: request.budget_tokens,
            used_tokens: 0,
            capsules: Vec::new(),
            excluded: capsules,
            skipped: true,
            top_score,
            top_abs_evidence,
            // A skipped bundle covers nothing, by construction.
            evidence_coverage: 0.0,
            uncovered_terms: Vec::new(),
            // Nothing was rendered, so nothing was rendered in time order.
            chronological: false,
            known_fact_conflicts: vec![],
        });
    }

    // MP-17 #13: capsule-stage Jaccard MMR — safety net / lean path.
    // On embeddings builds the candidate-stage embedding-MMR already
    // collapsed semantic near-duplicates; this pass is largely a no-op
    // (same-kind Jaccard score will be low for already-deduped summaries)
    // but provides a final guard against any remaining token-level
    // duplicates (e.g. repo files with heavily overlapping snippets).
    // On lean builds this is the sole diversity mechanism (unchanged).
    let capsules = apply_mmr_diversity(capsules, 0.7);

    let capsule_budget = request.budget_tokens / 2;
    let mut used_tokens = 0u32;
    let mut included = Vec::new();
    let mut excluded = Vec::new();

    for capsule in capsules {
        // v0.6: max_capsules cap (0 = disabled)
        if request.max_capsules > 0 && included.len() >= request.max_capsules {
            excluded.push(capsule);
            continue;
        }
        if (request.defer_fact_budget && request.max_capsules > 0)
            || used_tokens.saturating_add(capsule.token_estimate) <= capsule_budget
        {
            used_tokens = used_tokens.saturating_add(capsule.token_estimate);
            included.push(capsule);
        } else {
            excluded.push(capsule);
        }
    }

    let (coverage, uncovered_terms) = evidence_coverage(conn, &request.query, &included);

    // v2.6: presentation only, and last — the budget has already decided which
    // capsules ship, so re-rendering can neither admit one it rejected nor drop
    // one it chose. Coverage is measured before the date prefixes are added so
    // the score describes the memories, not their timestamps.
    //
    // `used_tokens` is recomputed because the prefixes are real tokens.
    let chronological = !created_at_by_handle.is_empty();
    let included = if chronological {
        let dated = crate::ordering::render_chronologically(included, &created_at_by_handle);
        used_tokens = dated.iter().map(|c| c.token_estimate).sum();
        dated
    } else {
        included
    };

    Ok(ContextBundle {
        stage: request.stage,
        budget_tokens: request.budget_tokens,
        used_tokens,
        capsules: included,
        excluded,
        skipped: false,
        top_score,
        top_abs_evidence,
        evidence_coverage: coverage,
        uncovered_terms,
        chronological,
        known_fact_conflicts: vec![],
    })
}

/// History/lineage path: search memories including expired ones (valid_to in the past).
///
/// This is the companion to `retrieve_context` for cases where you WANT to see
/// superseded, expired, or historically-valid memories — e.g. `kimetsu brain memory list`,
/// blame attribution, and lineage inspection.  The default retrieval path
/// (`retrieve_context` / `memory_candidates`) always excludes expired memories.
///
/// Returns the most recent `limit` active memories (invalidated_at IS NULL,
/// superseded_by IS NULL) including those whose `valid_to` has passed.
/// Superseded and invalidated rows are excluded (those are never valid for injection;
/// the `blame` path has its own direct SQL for those).
pub fn search_memories_including_expired(
    conn: &Connection,
    limit: u32,
) -> KimetsuResult<Vec<ContextCapsule>> {
    let mut stmt = conn.prepare_cached(
        "
        SELECT memory_id, scope, kind, text, confidence, created_at,
               use_count, usefulness_score, valid_from, valid_to
        FROM memories
        WHERE invalidated_at IS NULL
          AND superseded_by IS NULL
        ORDER BY created_at DESC
        LIMIT ?1
        ",
    )?;
    let rows = stmt.query_map(params![limit], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, f32>(4)?,
            row.get::<_, String>(5)?,
            row.get::<_, i64>(6)?,
            row.get::<_, f64>(7)?,
            row.get::<_, Option<String>>(8)?,
            row.get::<_, Option<String>>(9)?,
        ))
    })?;
    let now_utc = OffsetDateTime::now_utc();
    let mut capsules = Vec::new();
    for row in rows {
        let (
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            _use_count,
            _usefulness,
            _valid_from,
            valid_to,
        ) = row?;
        let freshness = freshness(&created_at);
        let scope_weight = scope_weight(&scope);
        // Annotate expired memories so callers can identify them in history output.
        let suffix = if let Some(ref vt) = valid_to {
            if OffsetDateTime::parse(vt, &time::format_description::well_known::Rfc3339)
                .is_ok_and(|end| end <= now_utc)
            {
                format!(" [expired valid_to={vt}]")
            } else {
                format!(" [valid_to={vt}]")
            }
        } else {
            String::new()
        };
        let revision = crate::projector::claim_revision_at(conn, &memory_id, None)?;
        let facts = crate::fact_store::load(conn, &memory_id, &revision)?;
        let claim_revision = Some(revision);
        capsules.push(ContextCapsule {
            id: new_id().to_string(),
            kind: "memory".to_string(),
            summary: format!("{scope}:{kind} - {text}{suffix}"),
            token_estimate: estimate_tokens(&text) + 8,
            expansion_handle: format!("memory:{memory_id}"),
            provenance: vec![ProvenanceRef {
                source: "Memory".to_string(),
                id: memory_id,
                excerpt: Some(excerpt(&text)),
            }],
            confidence,
            freshness,
            relevance: 0.0,
            scope_weight,
            score: 0.0,
            superseded_hint: false,
            rerank_policy_tier: 0,
            claim_revision,
            facts,
            rerank_usefulness: None,
            rerank_trust: None,
        });
    }
    Ok(capsules)
}

pub fn search_repo_files(
    conn: &Connection,
    repo_root: &str,
    query: &str,
    limit: u32,
) -> KimetsuResult<Vec<ContextCapsule>> {
    let candidates = repo_file_candidates(conn, repo_root, query, limit)?;
    let mut capsules = candidates
        .into_iter()
        .map(|mut candidate| {
            candidate.capsule.relevance = candidate.raw_relevance;
            candidate.capsule.score = candidate.raw_relevance;
            candidate.capsule
        })
        .collect::<Vec<_>>();
    capsules.sort_by(|left, right| {
        right
            .score
            .partial_cmp(&left.score)
            .unwrap_or(Ordering::Equal)
            .then_with(|| left.expansion_handle.cmp(&right.expansion_handle))
    });
    Ok(capsules)
}

// -----------------------------------------------------------------------
// ANN candidate generation via the usearch HNSW index — embeddings only.
// (The old brute-force `vec0` index code was removed in T3c; usearch now
// supersedes it entirely. See `crate::ann`.)
// -----------------------------------------------------------------------

/// Top-K ANN candidates from the usearch HNSW index.
///
/// Returns memory rows fetched from `memories` (same columns as
/// `latest_memory_candidates`) built into `Candidate`s via
/// `memory_row_to_candidate`. Callers union this with the FTS set and dedup.
#[cfg(feature = "embeddings")]
fn memory_ann_candidates(
    conn: &Connection,
    qe: &QueryEmbedding,
    k: u32,
    query_tokens: &[String],
    half_life_days: f32,
    include_facts: bool,
) -> KimetsuResult<Vec<Candidate>> {
    // Tier-3: ANN candidate generation via the usearch HNSW index.
    let handle = crate::ann::handle_for_query(conn, qe.vector.len(), &qe.model_id)?;
    let hits = handle
        .read()
        .unwrap_or_else(|p| p.into_inner())
        .search(&qe.vector, k as usize)?;
    // Map rowids back to memory_ids (active-only is enforced by the index, but
    // we still join `memories` below for the full row + the embedding_model
    // residual filter, so collect rowids here).
    let knn_rowids: Vec<i64> = hits.into_iter().map(|(rowid, _dist)| rowid).collect();
    if knn_rowids.is_empty() {
        return Ok(Vec::new());
    }

    // Fetch full memory rows for those rowids (same projection as latest_memory_candidates).
    let placeholders: String = knn_rowids
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 1))
        .collect::<Vec<_>>()
        .join(", ");
    let sql = format!(
        "SELECT memory_id, scope, kind, text, confidence, created_at,
                use_count, usefulness_score, embedding, embedding_model,
                last_useful_at, provenance_snapshot_json
         FROM   memories
         WHERE  invalidated_at IS NULL
           AND  superseded_by IS NULL
           AND  (valid_from IS NULL OR julianday(valid_from) <= julianday('now'))
          AND (valid_to IS NULL OR julianday(valid_to) > julianday('now'))
           AND  embedding_model = ?{model_param}
           AND  rowid IN ({placeholders})",
        model_param = knn_rowids.len() + 1
    );
    let mut stmt = conn.prepare(&sql)?;
    let mut params_vec: Vec<&dyn rusqlite::ToSql> = knn_rowids
        .iter()
        .map(|n| n as &dyn rusqlite::ToSql)
        .collect();
    params_vec.push(&qe.model_id);
    let rows_iter = stmt.query_map(params_vec.as_slice(), |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, f32>(4)?,
            row.get::<_, String>(5)?,
            row.get::<_, i64>(6)?,
            row.get::<_, f64>(7)?,
            row.get::<_, Option<Vec<u8>>>(8)?,
            row.get::<_, Option<String>>(9)?,
            row.get::<_, Option<String>>(10)?,
            row.get::<_, Option<String>>(11)?,
        ))
    })?;

    let mut candidates = Vec::new();
    for row in rows_iter {
        let (
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            use_count,
            usefulness_score,
            embedding,
            embedding_model,
            last_useful_at,
            provenance_snapshot,
        ) = row?;
        let (cosine, row_vec) =
            compute_cosine_and_vec(Some(qe), embedding.as_deref(), embedding_model.as_deref());
        let claim_revision = crate::projector::claim_revision_at(conn, &memory_id, None)?;
        if let Some(mut candidate) = memory_row_to_candidate(
            query_tokens,
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            use_count,
            usefulness_score,
            last_useful_at,
            provenance_snapshot,
            half_life_days,
            None, // no raw FTS relevance override — cosine drives ranking
            cosine,
            row_vec,
        ) {
            candidate.capsule.claim_revision = Some(claim_revision);
            hydrate_fact_evidence(conn, &mut candidate, include_facts)?;
            candidates.push(candidate);
        }
    }
    Ok(candidates)
}

/// Attach evidence only after row eligibility, while the text SELECT holds its snapshot.
pub(crate) fn hydrate_fact_evidence(
    conn: &Connection,
    candidate: &mut Candidate,
    include_facts: bool,
) -> KimetsuResult<()> {
    if include_facts {
        if let (Some(id), Some(revision)) = (
            candidate.capsule.expansion_handle.strip_prefix("memory:"),
            candidate.capsule.claim_revision.as_deref(),
        ) {
            candidate.capsule.facts = crate::fact_store::load(conn, id, revision)?;
        }
    }
    Ok(())
}

/// S5.1: the flat memory candidate function exposed as `pub(crate)` so
/// [`crate::backend::FlatBackend`] can delegate to it without copying logic.
///
/// Runs the FTS + usearch-ANN (embeddings) or FTS + recency (lean) candidate
/// pipeline — identical behaviour to pre-S5.1.
pub(crate) fn memory_candidates_flat(
    conn: &Connection,
    query: &str,
    query_embedding: Option<&QueryEmbedding>,
    half_life_days: f32,
    fusion: crate::fusion::Fusion,
    include_facts: bool,
) -> KimetsuResult<Vec<Candidate>> {
    memory_candidates(
        conn,
        query,
        query_embedding,
        half_life_days,
        fusion,
        include_facts,
    )
}

/// Build the flat candidate pool, merging the lexical and semantic rankings
/// with `fusion`.
///
/// The two sources — FTS5 and the ANN index — are independent rankings over the
/// same corpus, and how they are merged is a real ranking decision rather than
/// plumbing. See [`crate::fusion`].
fn memory_candidates(
    conn: &Connection,
    query: &str,
    query_embedding: Option<&QueryEmbedding>,
    half_life_days: f32,
    // Read only on the embeddings build: the lean path has a single ranking,
    // so there is nothing to fuse and any rule is the identity.
    #[cfg_attr(not(feature = "embeddings"), allow(unused_variables))] fusion: crate::fusion::Fusion,
    include_facts: bool,
) -> KimetsuResult<Vec<Candidate>> {
    let query_tokens = query_tokens(query);

    // D1c: on embeddings builds with a real query vector, run BOTH FTS and
    // ANN and fuse the two rankings. This replaces the recency-bounded
    // latest_memory_candidates fallback as the semantic-recall source when
    // embeddings are active.
    #[cfg(feature = "embeddings")]
    if let Some(qe) = query_embedding {
        // FTS candidates (may be empty if no lexical matches).
        let fts_candidates = if let Some(fts_query) = fts_query(query) {
            memory_fts_candidates(
                conn,
                &query_tokens,
                &fts_query,
                80,
                Some(qe),
                half_life_days,
                include_facts,
            )?
        } else {
            Vec::new()
        };

        // ANN candidates — top-80 nearest neighbours from the usearch index.
        let ann_candidates =
            memory_ann_candidates(conn, qe, 80, &query_tokens, half_life_days, include_facts)?;

        // Both sources return best-first, which is what rank-based fusion needs.
        return Ok(crate::fusion::fuse(
            fusion,
            vec![fts_candidates, ann_candidates],
        ));
    }

    // Lean (NoopEmbedder) path: unchanged — FTS then recency fallback.
    if let Some(fts_query) = fts_query(query) {
        let candidates = memory_fts_candidates(
            conn,
            &query_tokens,
            &fts_query,
            80,
            query_embedding,
            half_life_days,
            include_facts,
        )?;
        if !candidates.is_empty() {
            return Ok(candidates);
        }
    }

    latest_memory_candidates(
        conn,
        &query_tokens,
        200,
        query_embedding,
        half_life_days,
        include_facts,
    )
}

fn latest_memory_candidates(
    conn: &Connection,
    query_tokens: &[String],
    limit: u32,
    query_embedding: Option<&QueryEmbedding>,
    half_life_days: f32,
    include_facts: bool,
) -> KimetsuResult<Vec<Candidate>> {
    // MP-4d: exclude invalidated memories from retrieval. The row stays in
    // brain.db so `memory list` and replay can still see the history; only
    // the broker filters it out.
    //
    // v0.4.2: SELECT now also pulls the optional embedding + model id
    // so we can blend a cosine score with the lexical match.
    //
    // v0.5.1: SELECT also pulls `last_useful_at` so the broker can
    // apply the half-life decay term (memories that helped recently
    // outvote memories that haven't been confirmed useful in months).
    let mut stmt = conn.prepare_cached(
        "
        SELECT memory_id, scope, kind, text, confidence, created_at,
               use_count, usefulness_score, embedding, embedding_model,
               last_useful_at, provenance_snapshot_json
        FROM memories
        WHERE invalidated_at IS NULL
          AND superseded_by IS NULL
          AND (valid_from IS NULL OR julianday(valid_from) <= julianday('now'))
          AND (valid_to IS NULL OR julianday(valid_to) > julianday('now'))
        ORDER BY created_at DESC
        LIMIT ?1
        ",
    )?;

    let rows = stmt.query_map(params![limit], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, f32>(4)?,
            row.get::<_, String>(5)?,
            row.get::<_, i64>(6)?,
            row.get::<_, f64>(7)?,
            row.get::<_, Option<Vec<u8>>>(8)?,
            row.get::<_, Option<String>>(9)?,
            row.get::<_, Option<String>>(10)?,
            row.get::<_, Option<String>>(11)?,
        ))
    })?;

    let mut candidates = Vec::new();
    for row in rows {
        let (
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            use_count,
            usefulness_score,
            embedding,
            embedding_model,
            last_useful_at,
            provenance_snapshot,
        ) = row?;
        let (cosine, row_vec) = compute_cosine_and_vec(
            query_embedding,
            embedding.as_deref(),
            embedding_model.as_deref(),
        );
        let claim_revision = crate::projector::claim_revision_at(conn, &memory_id, None)?;
        if let Some(mut candidate) = memory_row_to_candidate(
            query_tokens,
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            use_count,
            usefulness_score,
            last_useful_at,
            provenance_snapshot,
            half_life_days,
            None,
            cosine,
            row_vec,
        ) {
            candidate.capsule.claim_revision = Some(claim_revision);
            hydrate_fact_evidence(conn, &mut candidate, include_facts)?;
            candidates.push(candidate);
        }
    }
    Ok(candidates)
}

fn memory_fts_candidates(
    conn: &Connection,
    query_tokens: &[String],
    fts_query: &str,
    limit: u32,
    query_embedding: Option<&QueryEmbedding>,
    half_life_days: f32,
    include_facts: bool,
) -> KimetsuResult<Vec<Candidate>> {
    let mut stmt = conn.prepare_cached(
        "
        SELECT m.memory_id, m.scope, m.kind, m.text, m.confidence, m.created_at,
               m.use_count, m.usefulness_score, bm25(memories_fts) AS rank,
               m.embedding, m.embedding_model, m.last_useful_at,
               m.provenance_snapshot_json
        FROM memories_fts
        JOIN memories m
          ON m.memory_id = memories_fts.memory_id
        WHERE m.invalidated_at IS NULL
          AND m.superseded_by IS NULL
          AND (m.valid_from IS NULL OR julianday(m.valid_from) <= julianday('now'))
          AND (m.valid_to IS NULL OR julianday(m.valid_to) > julianday('now'))
          AND memories_fts MATCH ?1
        ORDER BY rank
        LIMIT ?2
        ",
    )?;

    let rows = stmt.query_map(params![fts_query, limit], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, f32>(4)?,
            row.get::<_, String>(5)?,
            row.get::<_, i64>(6)?,
            row.get::<_, f64>(7)?,
            row.get::<_, f64>(8)?,
            row.get::<_, Option<Vec<u8>>>(9)?,
            row.get::<_, Option<String>>(10)?,
            row.get::<_, Option<String>>(11)?,
            row.get::<_, Option<String>>(12)?,
        ))
    })?;

    let mut candidates = Vec::new();
    for row in rows {
        let (
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            use_count,
            usefulness_score,
            rank,
            embedding,
            embedding_model,
            last_useful_at,
            provenance_snapshot,
        ) = row?;
        let fts_relevance = (-rank as f32).max(0.0);
        let (cosine, row_vec) = compute_cosine_and_vec(
            query_embedding,
            embedding.as_deref(),
            embedding_model.as_deref(),
        );
        let claim_revision = crate::projector::claim_revision_at(conn, &memory_id, None)?;
        if let Some(mut candidate) = memory_row_to_candidate(
            query_tokens,
            memory_id,
            scope,
            kind,
            text,
            confidence,
            created_at,
            use_count,
            usefulness_score,
            last_useful_at,
            provenance_snapshot,
            half_life_days,
            Some(fts_relevance),
            cosine,
            row_vec,
        ) {
            candidate.capsule.claim_revision = Some(claim_revision);
            hydrate_fact_evidence(conn, &mut candidate, include_facts)?;
            candidates.push(candidate);
        }
    }
    Ok(candidates)
}

/// v0.4.2 / D1e: cosine helper — returns both the cosine score and the
/// decoded row embedding vector for a memory row. Used by all three
/// memory-candidate retrieval paths (FTS, ANN, latest-recency) to
/// populate `Candidate.cosine` and `Candidate.embedding` for the
/// candidate-stage embedding-MMR pass.
///
/// Returns `(None, None)` when:
///   * `query_embedding` is None (NoopEmbedder / lean build)
///   * The row has no embedding bytes
///   * The row's `embedding_model` doesn't match the active query's
///     model id (cross-model mismatch — vectors are incomparable)
///
/// Cross-model rows are intentionally NOT blended: a row embedded
/// with `stub-d8` and a query embedded with `bge-small-en-v1.5`
/// produce meaningless dot products. Falling back to FTS for those
/// rows keeps hybrid retrieval safe across schema upgrades and
/// `kimetsu brain reindex` migrations (v0.4.3).
///
/// D1e: variant that returns both the cosine score and the decoded row
/// embedding vector. Used by callsites that need to store the vector
/// on the `Candidate` for the candidate-stage embedding-MMR pass.
/// When the row is cross-model or has no embedding, both fields are
/// `None` — identical semantics to [`compute_cosine`].
fn compute_cosine_and_vec(
    query_embedding: Option<&QueryEmbedding>,
    row_bytes: Option<&[u8]>,
    row_model: Option<&str>,
) -> (Option<f32>, Option<Vec<f32>>) {
    let q = match query_embedding {
        Some(q) => q,
        None => return (None, None),
    };
    let bytes = match row_bytes {
        Some(b) => b,
        None => return (None, None),
    };
    let model = match row_model {
        Some(m) => m,
        None => return (None, None),
    };
    if model != q.model_id {
        return (None, None);
    }
    let row_vec = match decode_embedding(bytes, Some(q.vector.len())) {
        Ok(v) => v,
        Err(_) => return (None, None),
    };
    let score = cosine_similarity(&q.vector, &row_vec);
    (Some(score), Some(row_vec))
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn memory_row_to_candidate(
    query_tokens: &[String],
    memory_id: String,
    scope: String,
    kind: String,
    text: String,
    confidence: f32,
    created_at: String,
    use_count: i64,
    usefulness_score: f64,
    last_useful_at: Option<String>,
    // v2.6: the memory's stored provenance snapshot, classified into a trust
    // multiplier. See `crate::trust`.
    provenance_snapshot: Option<String>,
    half_life_days: f32,
    raw_relevance_override: Option<f32>,
    cosine_score: Option<f32>,
    // D1e: decoded embedding vector for this row (same model as the
    // active query embedder). None for cross-model rows, rows without
    // embeddings, or lean builds. Stored on Candidate for the
    // candidate-stage embedding-MMR pass.
    row_embedding: Option<Vec<f32>>,
) -> Option<Candidate> {
    let lexical = lexical_relevance(query_tokens, &format!("{kind} {text}"));
    let lexical_term = raw_relevance_override.unwrap_or(lexical).max(lexical);

    // v0.4.2: hybrid blend.
    //   final = (1 - α) * lexical + α * normalized_cosine
    // where normalized_cosine maps [-1, 1] -> [0, 1] so it composes
    // with the lexical relevance scale.
    //
    // When cosine_score is None (NoopEmbedder, NULL row embedding,
    // cross-model mismatch), the cosine term drops out and the
    // candidate scores lexical-only — exact v0.4.1 behavior. The
    // caller's gate `raw_relevance <= 0.0 && !query_tokens.is_empty()`
    // still works because in the no-cosine path `raw_relevance ==
    // lexical_term`.
    let raw_relevance = match cosine_score {
        Some(c) => {
            let normalized_cos = ((c + 1.0) * 0.5).clamp(0.0, 1.0);
            (1.0 - DEFAULT_HYBRID_ALPHA) * lexical_term + DEFAULT_HYBRID_ALPHA * normalized_cos
        }
        None => lexical_term,
    };

    // Drop the row when neither lexical nor cosine had any signal —
    // an empty query OR a candidate that didn't match any of the
    // search terms. The cosine-only path is still allowed through
    // (raw_relevance > 0) for semantic-only matches against rows
    // whose words don't textually overlap the query.
    if raw_relevance <= 0.0 && !query_tokens.is_empty() {
        return None;
    }

    let freshness = freshness(&created_at);
    let scope_weight = scope_weight(&scope);
    // v0.5.1: usefulness multiplier with half-life decay applied to
    // the *deviation from neutral*. A 6-month-old memory that scored
    // 1.5 (max boost) decays toward 1.0 (neutral) — NOT toward 0,
    // because losing confidence in old signal shouldn't penalize a
    // memory below a brand-new memory with zero history.
    let raw_multiplier = usefulness_multiplier(usefulness_score as f32, use_count as u32);
    let decay = usefulness_decay(last_useful_at.as_deref(), &created_at, half_life_days);
    let multiplier = 1.0 + (raw_multiplier - 1.0) * decay;
    let biased_relevance = apply_usefulness_boost(raw_relevance, multiplier);
    // Retain the sign for older serialized consumers. New capsules carry the full multiplier.
    let rerank_policy_tier = if multiplier > 1.0 + f32::EPSILON {
        1
    } else if multiplier < 1.0 - f32::EPSILON {
        -1
    } else {
        0
    };
    // Reliance and outcome association do not verify a memory or erase origin.
    let provenance =
        crate::trust::Provenance::from_snapshot(provenance_snapshot.as_deref().unwrap_or("{}"));
    let trusted_relevance =
        biased_relevance * crate::trust::trust_multiplier(provenance, last_useful_at.is_some());

    Some(Candidate {
        raw_relevance: trusted_relevance,
        embedding: row_embedding,
        cosine: cosine_score,
        created_at: Some(created_at),
        capsule: ContextCapsule {
            id: new_id().to_string(),
            kind: "memory".to_string(),
            summary: format!("{scope}:{kind} - {text}"),
            token_estimate: estimate_tokens(&text) + 8,
            expansion_handle: format!("memory:{memory_id}"),
            provenance: vec![ProvenanceRef {
                source: "Memory".to_string(),
                id: memory_id,
                excerpt: Some(excerpt(&text)),
            }],
            confidence,
            freshness,
            relevance: 0.0,
            scope_weight,
            score: 0.0,
            superseded_hint: false,
            rerank_policy_tier,
            claim_revision: None,
            facts: vec![],
            rerank_usefulness: Some(multiplier),
            rerank_trust: Some(crate::trust::trust_multiplier(
                provenance,
                last_useful_at.is_some(),
            )),
        },
    })
}

/// v0.5.1: half-life decay factor applied to the *deviation from
/// neutral* of [`usefulness_multiplier`]. Returns a value in `[0.0,
/// 1.0]` where 1.0 = "use full envelope" (memory was confirmed useful
/// recently) and 0.0 = "treat as neutral" (memory's confirmation is
/// ancient).
///
/// Reference timestamp:
///   * `last_useful_at` (set by the projector when a cited memory's
///     run ended in run.finished) if present
///   * fallback to `created_at` so a brand-new memory that's never
///     been cited yet decays from its birthday — same shape, but
///     starts fresh.
///
/// Math:
///   decay = exp(-ln(2) * age_days / half_life_days)
/// so at age == half_life the contribution is halved, at 2*half_life
/// it's quartered, etc.
///
/// Safety rails:
///   * `half_life_days <= 0` disables decay (returns 1.0) so an
///     operator can opt out via project.toml.
///   * Unparseable RFC3339 timestamps return 1.0 — fail-open so a
///     corrupted row doesn't get silently demoted out of retrieval.
pub(crate) fn usefulness_decay(
    last_useful_at: Option<&str>,
    created_at: &str,
    half_life_days: f32,
) -> f32 {
    if half_life_days <= 0.0 {
        return 1.0;
    }
    let reference = last_useful_at.unwrap_or(created_at);
    let Ok(reference_ts) =
        OffsetDateTime::parse(reference, &time::format_description::well_known::Rfc3339)
    else {
        return 1.0;
    };
    let age = OffsetDateTime::now_utc() - reference_ts;
    let age_days = (age.whole_seconds().max(0) as f32) / 86_400.0;
    let exponent = -std::f32::consts::LN_2 * age_days / half_life_days;
    exponent.exp().clamp(0.0, 1.0)
}

// v2.5.1: the boost cap and multiplier envelope live in crate::scoring (the
// one-page home of every learning-loop constant).
pub(crate) use crate::scoring::USEFULNESS_BOOST_CAP;

/// Apply the usefulness multiplier to a relevance score with the boost gain
/// capped at [`USEFULNESS_BOOST_CAP`] (see there for why).
pub(crate) fn apply_usefulness_boost(raw_relevance: f32, multiplier: f32) -> f32 {
    if multiplier <= 1.0 {
        return raw_relevance * multiplier;
    }
    (raw_relevance * multiplier).min(raw_relevance + USEFULNESS_BOOST_CAP)
}

/// MP-4b multiplier in [0.5, 1.5] derived from a memory's outcome history.
/// `use_count < 3` is treated as small-sample and yields 1.0 (neutral) so a
/// brand-new memory has a fair chance to demonstrate value before being
/// boosted or penalized.
pub(crate) fn usefulness_multiplier(usefulness_score: f32, use_count: u32) -> f32 {
    // MP-17e: soften the hard sample-size threshold via Bayesian smoothing.
    //
    // Old behaviour: hard cutoff at use_count < 3 returned neutral 1.0,
    // then full envelope kicked in. That meant a memory with 2 uses (both
    // helpful) was treated identically to a memory with 0 uses, which
    // wasted early signal. New behaviour: linearly blend toward the
    // full multiplier as use_count climbs to FULL_CONFIDENCE_USES.
    use crate::scoring::{FULL_CONFIDENCE_USES, MULTIPLIER_MAX, MULTIPLIER_MIN};
    if use_count == 0 {
        return 1.0;
    }
    let ratio = usefulness_score / use_count as f32; // in -1.0..1.0 typically
    let normalized = ((ratio + 1.0) / 2.0).clamp(0.0, 1.0); // map to 0..1
    let full_multiplier = MULTIPLIER_MIN + normalized * (MULTIPLIER_MAX - MULTIPLIER_MIN);
    let confidence = (use_count as f32 / FULL_CONFIDENCE_USES as f32).min(1.0);
    1.0 * (1.0 - confidence) + full_multiplier * confidence
}

fn repo_file_candidates(
    conn: &Connection,
    repo_root: &str,
    query: &str,
    limit: u32,
) -> KimetsuResult<Vec<Candidate>> {
    let Some(fts_query) = fts_query(query) else {
        return Ok(Vec::new());
    };

    let mut stmt = conn.prepare_cached(
        "
        SELECT path, snippet, language_guess, bm25(repo_files_fts) AS rank
        FROM repo_files_fts
        WHERE repo_root = ?1 AND repo_files_fts MATCH ?2
        ORDER BY rank
        LIMIT ?3
        ",
    )?;

    let rows = stmt.query_map(params![repo_root, fts_query, limit], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, f64>(3)?,
        ))
    })?;

    let mut candidates = Vec::new();
    for row in rows {
        let (path, snippet, language, rank) = row?;
        let raw_relevance = (-rank as f32).max(0.0);
        let summary = format!("{path} ({language}) - {}", excerpt(&snippet));
        let token_estimate = estimate_tokens(&summary) + 8;
        candidates.push(Candidate {
            raw_relevance,
            embedding: None,
            cosine: None,
            // A repo file has no position in the memory timeline.
            created_at: None,
            capsule: ContextCapsule {
                id: new_id().to_string(),
                kind: "repo_file".to_string(),
                summary,
                token_estimate,
                expansion_handle: format!("file:{path}"),
                provenance: vec![ProvenanceRef {
                    source: "RepoFile".to_string(),
                    id: path.clone(),
                    excerpt: Some(excerpt(&snippet)),
                }],
                confidence: 0.9,
                freshness: 1.0,
                relevance: 0.0,
                scope_weight: 0.9,
                score: 0.0,
                superseded_hint: false,
                rerank_policy_tier: 0,
                claim_revision: None,
                facts: vec![],
                rerank_usefulness: None,
                rerank_trust: None,
            },
        });
    }
    Ok(candidates)
}

fn manifest_candidates(
    conn: &Connection,
    repo_root: &str,
    query: &str,
) -> KimetsuResult<Vec<Candidate>> {
    if let Some(fts_query) = fts_query(query) {
        let candidates = manifest_fts_candidates(conn, repo_root, &fts_query, 30)?;
        if !candidates.is_empty() {
            return Ok(candidates);
        }
    }

    let query_tokens = query_tokens(query);
    let mut stmt = conn.prepare_cached(
        "
        SELECT manifest_path, manifest_kind, parsed_summary_json
        FROM repo_manifests
        WHERE repo_root = ?1
        ORDER BY manifest_path
        ",
    )?;

    let rows = stmt.query_map(params![repo_root], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
        ))
    })?;

    let mut candidates = Vec::new();
    for row in rows {
        let (path, kind, summary_json) = row?;
        let raw_relevance =
            lexical_relevance(&query_tokens, &format!("{path} {kind} {summary_json}"));
        if raw_relevance <= 0.0 && !query_tokens.is_empty() {
            continue;
        }
        let summary = format!("{path} manifest ({kind})");
        let token_estimate = estimate_tokens(&summary) + 8;
        candidates.push(Candidate {
            raw_relevance,
            embedding: None,
            cosine: None,
            // A repo file has no position in the memory timeline.
            created_at: None,
            capsule: ContextCapsule {
                id: new_id().to_string(),
                kind: "repo_manifest".to_string(),
                summary,
                token_estimate,
                expansion_handle: format!("file:{path}"),
                provenance: vec![ProvenanceRef {
                    source: "Manifest".to_string(),
                    id: path,
                    excerpt: Some(excerpt(&summary_json)),
                }],
                confidence: 0.95,
                freshness: 1.0,
                relevance: 0.0,
                scope_weight: 0.9,
                score: 0.0,
                superseded_hint: false,
                rerank_policy_tier: 0,
                claim_revision: None,
                facts: vec![],
                rerank_usefulness: None,
                rerank_trust: None,
            },
        });
    }
    Ok(candidates)
}

fn manifest_fts_candidates(
    conn: &Connection,
    repo_root: &str,
    fts_query: &str,
    limit: u32,
) -> KimetsuResult<Vec<Candidate>> {
    let mut stmt = conn.prepare_cached(
        "
        SELECT manifest_path, manifest_kind, parsed_summary_json,
               bm25(repo_manifests_fts) AS rank
        FROM repo_manifests_fts
        WHERE repo_root = ?1 AND repo_manifests_fts MATCH ?2
        ORDER BY rank
        LIMIT ?3
        ",
    )?;

    let rows = stmt.query_map(params![repo_root, fts_query, limit], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, f64>(3)?,
        ))
    })?;

    let mut candidates = Vec::new();
    for row in rows {
        let (path, kind, summary_json, rank) = row?;
        let raw_relevance = (-rank as f32).max(0.0);
        let summary = format!("{path} manifest ({kind})");
        let token_estimate = estimate_tokens(&summary) + 8;
        candidates.push(Candidate {
            raw_relevance,
            embedding: None,
            cosine: None,
            // A repo file has no position in the memory timeline.
            created_at: None,
            capsule: ContextCapsule {
                id: new_id().to_string(),
                kind: "repo_manifest".to_string(),
                summary,
                token_estimate,
                expansion_handle: format!("file:{path}"),
                provenance: vec![ProvenanceRef {
                    source: "Manifest".to_string(),
                    id: path,
                    excerpt: Some(excerpt(&summary_json)),
                }],
                confidence: 0.95,
                freshness: 1.0,
                relevance: 0.0,
                scope_weight: 0.9,
                score: 0.0,
                superseded_hint: false,
                rerank_policy_tier: 0,
                claim_revision: None,
                facts: vec![],
                rerank_usefulness: None,
                rerank_trust: None,
            },
        });
    }
    Ok(candidates)
}

/// v2.6: how `raw_relevance` becomes the `relevance` term of the composite
/// score.
///
/// ## Per-kind (the rule through v2.5)
///
/// Each `kind` is normalized against the best `raw_relevance` *of that kind*.
/// The consequence is that the top memory and the top repo_file both score
/// `relevance = 1.0` no matter how good either actually is: on a query where
/// memory has the answer and no file is relevant, the best of the irrelevant
/// files is still promoted to a perfect relevance and competes for budget on
/// the strength of the other three score terms alone.
///
/// That is the distortion the lexical and semantic *floors* exist to
/// compensate for — they prune the weak candidate before normalization can
/// flatter it. A floor is a blunt instrument for this: it is a fixed
/// threshold standing in for a comparison the normalizer could just make.
///
/// ## Global
///
/// One max over all candidates, so `relevance` means the same thing across
/// kinds and a candidate that is merely the best of a bad kind keeps a low
/// relevance. Nothing else in the pipeline changes.
///
/// ## Which one runs
///
/// Selectable, defaulting to `per_kind`. Global normalization is the more
/// principled rule and it is *still* not the default here, for the same
/// reason RRF is not: the house rule is that a ranking change ships with a
/// measurement on a real corpus, and an argument from first principles is not
/// one. `[broker] normalization` and the per-request override are how a
/// corpus gets to settle it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Normalization {
    /// Normalize within each capsule kind. Kimetsu's behaviour through v2.5.
    #[default]
    PerKind,
    /// Normalize against a single max over every candidate.
    Global,
}

impl Normalization {
    /// Parse from config. Unknown values fall back to the default, matching
    /// how `[broker] fusion` treats an unrecognized rule — a typo in a config
    /// file must not silently change ranking.
    pub fn from_config(value: &str) -> Self {
        match value.trim().to_ascii_lowercase().as_str() {
            "global" => Self::Global,
            _ => Self::PerKind,
        }
    }
}

fn normalize_and_score(
    candidates: &mut [Candidate],
    weights: StageWeights,
    normalization: Normalization,
) {
    // The per-kind rule keys on the capsule kind; the global rule uses one
    // bucket for everything. Sharing the map keeps a single scoring loop.
    let mut max_by_kind = HashMap::<String, f32>::new();
    let bucket = |candidate: &Candidate| match normalization {
        Normalization::PerKind => candidate.capsule.kind.clone(),
        Normalization::Global => String::new(),
    };
    for candidate in candidates.iter() {
        max_by_kind
            .entry(bucket(candidate))
            .and_modify(|max| *max = (*max).max(candidate.raw_relevance))
            .or_insert(candidate.raw_relevance);
    }

    for candidate in candidates {
        let max = max_by_kind.get(&bucket(candidate)).copied().unwrap_or(0.0);
        let relevance = if max <= f32::EPSILON {
            if candidate.raw_relevance > 0.0 {
                1.0
            } else {
                0.0
            }
        } else {
            (candidate.raw_relevance / max).clamp(0.0, 1.0)
        };
        candidate.capsule.relevance = relevance;
        candidate.capsule.score = weights.relevance * relevance
            + weights.confidence * candidate.capsule.confidence
            + weights.freshness * candidate.capsule.freshness
            + weights.scope * candidate.capsule.scope_weight;
    }
}

/// v2.7: two memory candidates whose embeddings agree at least this much are
/// treated as statements of the same topic for the newer-wins rule. High on
/// purpose — complementary-but-distinct lessons on one subject must not
/// penalize each other; only near-restatements qualify.
pub(crate) const SUPERSESSION_MIN_COSINE: f32 = 0.85;

/// Explicit correction language supplies extra evidence that two moderately
/// similar memories are successive versions of one fact. The 0.82 floor admits
/// the measured "no longer uses replica-1" update pair (cosine 0.837) without
/// broadening the rule for ordinary memories, which still require 0.85.
pub(crate) const SUPERSESSION_CUE_MIN_COSINE: f32 = 0.82;

/// A correction can also identify a rewritten update whose embedding moved
/// substantially because the replacement contains new implementation detail.
/// Require both several shared content tokens and dense overlap with the
/// smaller text; the cue alone is never sufficient.
pub(crate) const SUPERSESSION_CUE_MIN_SHARED_TOKENS: usize = 3;
pub(crate) const SUPERSESSION_CUE_MIN_LEXICAL_OVERLAP: f32 = 0.35;

/// v2.7: score multiplier applied (once) to the older member of a
/// near-duplicate pair. Sized from the workflow benchmark's measured failure:
/// a cited incumbent's usefulness boost gives it a ~1.08× composite advantage
/// over its fresher replacement, so 0.80 flips the ordering with margin while
/// leaving genuinely-unrelated rankings untouched.
pub(crate) const SUPERSESSION_PENALTY: f32 = 0.80;

/// v2.7: minimum age gap for the newer-wins rule. Supersession implies
/// temporal SUCCESSION — a near-duplicate written milliseconds apart is one
/// authoring event (a batch ingest, two variants of one lesson), not an
/// update, and penalizing the "older" of the pair broke the importance
/// dimension's cited-must-outrank assertion (92.1% → 81.6% on the
/// comprehensive A/B). One second cleanly separates same-batch co-writes
/// (Δ≈ms) from genuine cross-task updates (Δ≥ seconds); explicit correction
/// language provides the narrow exception for ordered batch imports.
pub(crate) const SUPERSESSION_MIN_AGE_GAP_SECS: f64 = 1.0;

/// Text can establish succession even when storage timestamps cannot. This is
/// intentionally a narrow phrase list: it only applies to near-duplicate
/// memory pairs, and only when exactly one side carries an explicit correction
/// cue. Generic recency words such as "new" are excluded because they appear
/// in ordinary co-written lessons too often.
fn has_explicit_supersession_signal(text: &str) -> bool {
    // Normalize punctuation to word boundaries before matching. Correction
    // language commonly appears parenthesized ("(switched from tabs)"); a
    // literal-space matcher misses it even though the words are unambiguous.
    // Keeping outer spaces prevents the single-word cues from matching inside
    // unrelated words (for example `now` inside `known`).
    let words = text
        .to_ascii_lowercase()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' })
        .collect::<String>();
    let text = format!(
        " {} ",
        words.split_whitespace().collect::<Vec<_>>().join(" ")
    );
    [
        " now ",
        " no longer ",
        " renamed from ",
        " switched from ",
        " as of ",
        " currently ",
        " after the ",
        " supersedes ",
        " replaced by ",
        " silently breaks ",
    ]
    .iter()
    .any(|signal| text.contains(signal))
}

fn has_supersession_lexical_identity(a: &str, b: &str) -> bool {
    let a = content_tokens(a);
    let b = content_tokens(b);
    let smaller = a.len().min(b.len());
    if smaller == 0 {
        return false;
    }
    let shared = a.iter().filter(|token| b.contains(token)).count();
    shared >= SUPERSESSION_CUE_MIN_SHARED_TOKENS
        && shared as f32 / smaller as f32 >= SUPERSESSION_CUE_MIN_LEXICAL_OVERLAP
}

/// v2.7: newer-wins supersession pass. Strong embedding near-duplicates
/// qualify directly; moderately similar or rewritten pairs must also carry
/// exactly one explicit correction cue and enough lexical identity. For
/// lexical-only rewrites, the replacement must be at least as relevant to the
/// current query so historical questions can still retrieve the old fact.
/// The OLDER candidate is multiplied by `SUPERSESSION_PENALTY` at most once,
/// however many newer siblings it has. Runs after normalization and boosts so
/// the penalty is the last word: a heavily-cited incumbent cannot out-boost
/// its own replacement.
///
/// Requires both embeddings and both parseable `created_at` timestamps; pairs
/// missing either are left alone (lean builds are unaffected end to end).
pub(crate) fn apply_supersession_penalty(candidates: &mut [Candidate]) {
    let parsed: Vec<Option<OffsetDateTime>> = candidates
        .iter()
        .map(|c| {
            if c.capsule.kind != "memory" || c.embedding.is_none() {
                return None;
            }
            c.created_at.as_deref().and_then(|ts| {
                OffsetDateTime::parse(ts, &time::format_description::well_known::Rfc3339).ok()
            })
        })
        .collect();

    let mut penalized = vec![false; candidates.len()];
    for i in 0..candidates.len() {
        let Some(ti) = parsed[i] else { continue };
        for j in (i + 1)..candidates.len() {
            let Some(tj) = parsed[j] else { continue };
            let (Some(ei), Some(ej)) = (&candidates[i].embedding, &candidates[j].embedding) else {
                continue;
            };
            let signals = (
                has_explicit_supersession_signal(&candidates[i].capsule.summary),
                has_explicit_supersession_signal(&candidates[j].capsule.summary),
            );
            let exactly_one_signal = signals.0 ^ signals.1;
            let similarity = crate::embeddings::cosine_similarity(ei, ej);
            let cue_related = exactly_one_signal
                && (similarity >= SUPERSESSION_CUE_MIN_COSINE
                    || has_supersession_lexical_identity(
                        &candidates[i].capsule.summary,
                        &candidates[j].capsule.summary,
                    ));
            if similarity < SUPERSESSION_MIN_COSINE && !cue_related {
                continue;
            }
            // Sub-second gaps (incl. identical timestamps) are normally one
            // authoring event, not a supersession. A single explicit
            // correction cue can still establish direction for batch imports;
            // if both or neither carry one, there is no defensible winner.
            let gap = (ti - tj).abs();
            let subsecond = (gap.whole_milliseconds().unsigned_abs() as f64)
                < SUPERSESSION_MIN_AGE_GAP_SECS * 1000.0;
            let older = if subsecond {
                match signals {
                    (true, false) => j,
                    (false, true) => i,
                    _ => continue,
                }
            } else {
                match ti.cmp(&tj) {
                    Ordering::Less => i,
                    Ordering::Greater => j,
                    Ordering::Equal => continue,
                }
            };
            if similarity < SUPERSESSION_CUE_MIN_COSINE {
                // Lexical-only rewrites below the cue-qualified cosine floor
                // can be related facts rather than mutually exclusive
                // restatements. Apply newer-wins only when the replacement is
                // at least as relevant to THIS query. This preserves historical
                // questions such as "which embedder reached MRR 1.0?" while
                // still resolving "what is preferred now?" to the newer
                // recommendation. Cue-marked pairs at 0.82+ are close enough
                // to use the ordinary newer-wins policy directly.
                let replacement = if older == i { j } else { i };
                let replacement_has_signal = if replacement == i {
                    signals.0
                } else {
                    signals.1
                };
                let query_favors_replacement =
                    match (candidates[replacement].cosine, candidates[older].cosine) {
                        (Some(replacement_cosine), Some(older_cosine)) => {
                            replacement_cosine >= older_cosine
                        }
                        _ => false,
                    };
                if !replacement_has_signal || !query_favors_replacement {
                    continue;
                }
            }
            if !penalized[older] {
                penalized[older] = true;
                candidates[older].capsule.score *= SUPERSESSION_PENALTY;
                // Mark it so post-retrieval reranking can reapply the penalty
                // on the cross-encoder's score domain.
                candidates[older].capsule.superseded_hint = true;
            }
        }
    }
}

fn weights_for_stage(weights: &BrokerWeights, stage: &str) -> StageWeights {
    match stage {
        "localization" => weights.localization.clone(),
        "patch_plan" => weights.patch_plan.clone(),
        "verification" => weights.verification.clone(),
        "review" => weights.review.clone(),
        _ => None,
    }
    .unwrap_or(StageWeights {
        relevance: weights.relevance,
        confidence: weights.confidence,
        freshness: weights.freshness,
        scope: weights.scope,
    })
}

fn scope_weight(scope: &str) -> f32 {
    match scope.parse::<MemoryScope>() {
        Ok(MemoryScope::Run) => 1.0,
        Ok(MemoryScope::Repo) => 0.9,
        Ok(MemoryScope::Project) => 0.7,
        Ok(MemoryScope::GlobalUser) => 0.5,
        Err(_) => 0.3,
    }
}

fn freshness(created_at: &str) -> f32 {
    let Ok(created_at) =
        OffsetDateTime::parse(created_at, &time::format_description::well_known::Rfc3339)
    else {
        return 0.5;
    };
    let age = OffsetDateTime::now_utc() - created_at;
    let age_days = age.whole_seconds().max(0) as f32 / 86_400.0;
    (-std::f32::consts::LN_2 * age_days / 30.0)
        .exp()
        .clamp(0.0, 1.0)
}

/// v1.0.0: a memory whose cosine to the query clears this bar is kept by
/// the lexical floor even when it shares few query words — a genuine
/// semantic match shouldn't be pruned for lexical thinness. Inert on the
/// FTS-only hook path (cosine is always `None` there).
const SEMANTIC_KEEP_COSINE: f32 = 0.20;

/// v1.0.0: generic English function words carry no topical signal, so they
/// are stripped before the IDF-weighted lexical floor. Kept deliberately
/// small — only true stopwords. Content words like "repo" or "idea" are NOT
/// here; their commonness is handled by IDF, not a hand-maintained list.
const STOPWORDS: &[&str] = &[
    "the", "and", "for", "are", "but", "not", "you", "your", "with", "this", "that", "these",
    "those", "from", "into", "about", "what", "whats", "which", "who", "whom", "how", "why",
    "when", "where", "can", "could", "would", "should", "will", "shall", "does", "did", "was",
    "were", "been", "being", "have", "has", "had", "its", "it", "is", "as", "at", "by", "of", "to",
    "in", "on", "or", "an", "be", "do", "me", "my", "we", "us", "our", "im", "ive", "let", "lets",
    "please", "tell", "give", "show", "want", "need", "get", "got", "use", "using", "there",
    "their", "they", "them", "then", "than", "some", "any", "all", "more", "most", "such", "via",
    "per",
    // v2.6: the function words this list had always meant to cover. The
    // comment in `content_tokens` cited "during" as the reason stemming runs
    // after the stopword check, and "during" was not actually in the list —
    // harmless while these tokens only nudged a floor, but v2.6 shows uncovered
    // terms to the user by name, and "nothing above covers during" is noise.
    // These also reconcile this list with `graph::STOPWORDS`, which had a
    // different set; two disagreeing stopword lists in one codebase is its own
    // small defect.
    "during", "while", "until", "unless", "before", "after", "again", "against", "above", "below",
    "between", "through", "under", "over", "because", "also", "just", "only", "very", "much",
    "many", "each", "both", "same", "other", "another", "always", "never", "still", "even", "ever",
    "every", "first", "found", "thing", "things", "value", "default", "if", "so", "up", "out",
    "off", "down", "no", "yes",
];

/// v1.0.0: tokenize a query into deduped CONTENT tokens — the same word
/// split as [`query_tokens`] but with stopwords removed and WITHOUT the
/// `CLASS_HINTS` tool-name expansions (those are a retrieval *boost*, not
/// part of the user's topical intent). Used only by the lexical floor.
fn content_tokens(query: &str) -> Vec<String> {
    let mut seen = std::collections::HashSet::new();
    query
        .split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
        .map(str::trim)
        .filter(|part| part.len() >= 2)
        .map(str::to_ascii_lowercase)
        .filter(|t| !STOPWORDS.contains(&t.as_str()))
        // Stem AFTER the stopword check ("during" must not stem to "dur"
        // and dodge the list) so inflected variants share one IDF entry.
        .map(|t| light_stem(&t).to_string())
        .filter(|t| seen.insert(t.clone()))
        .collect()
}

/// v1.0.0: discriminating weight for each content token over the
/// (non-invalidated) memory corpus, where `df` is the number of memories
/// whose text contains the token as a substring (matching
/// [`lexical_relevance`]'s substring semantics). Only tokens that actually
/// partition the corpus carry weight; the two useless extremes are zeroed:
///
///   * `df == N` — the token is in EVERY memory (the project name). `idf =
///     ln((N+1)/(N+1)) = 0` falls out of the formula naturally.
///   * `df == 0` — the token is in NO memory (an out-of-corpus word like a
///     generic English verb). It can't distinguish one memory from another,
///     so it's forced to 0. Leaving it at its (maximal) raw IDF would let a
///     single generic query word sink every candidate's coverage below the
///     floor — the on-topic memory that matches the *rare, in-corpus* word
///     would be wrongly pruned.
///
/// Everything in between gets `idf = ln((N+1)/(df+1))` — rarer ⇒ larger.
/// Best-effort: a query/count failure yields 0 for that token (fail-open).
fn corpus_token_idf(conn: &Connection, tokens: &[String]) -> KimetsuResult<HashMap<String, f32>> {
    token_idf(conn, tokens, true)
}

/// Prefix MATCH uses the same FTS tokenizer as candidate retrieval. Each matched
/// memory counts once even when its text repeats a token. N and df both refer to
/// non-invalidated indexed documents, including historical/superseded documents.
/// One indexed posting-list lookup per unique token replaces per-term text scans.
fn token_idf(
    conn: &Connection,
    tokens: &[String],
    zero_absent: bool,
) -> KimetsuResult<HashMap<String, f32>> {
    let n: i64 = conn.query_row(
        "SELECT COUNT(*) FROM memories_fts JOIN memories m USING(memory_id) WHERE m.invalidated_at IS NULL",
        [], |r| r.get(0))?;
    let mut idf = HashMap::new();
    if n == 0 {
        return Ok(idf);
    }
    let mut stmt = conn.prepare_cached(
        "SELECT COUNT(DISTINCT m.memory_id) FROM memories_fts JOIN memories m USING(memory_id)
         WHERE memories_fts MATCH ?1 AND m.invalidated_at IS NULL",
    )?;
    for token in tokens {
        if idf.contains_key(token) {
            continue;
        }
        let pattern = format!("text : \"{}\"*", token.replace('"', "\"\""));
        let df: i64 = stmt.query_row(params![pattern], |r| r.get(0))?;
        let weight = if zero_absent && df == 0 {
            0.0
        } else {
            (((n + 1) as f32) / ((df + 1) as f32)).ln().max(0.0)
        };
        idf.insert(token.clone(), weight);
    }
    Ok(idf)
}

/// v1.0.0: the IDF-weighted fraction of the query's discriminating power that
/// `summary` lexically covers, in `[0,1]`. Tokens present in the haystack
/// contribute their IDF weight to the numerator; all tokens contribute to the
/// denominator. A summary that matches only the query's low-IDF (common)
/// words scores near 0; one that matches the rare, topical words scores near
/// 1. Returns 0 when the total weight is ~0 (all tokens ubiquitous).
fn weighted_coverage(content: &[String], idf: &HashMap<String, f32>, summary: &str) -> f32 {
    let haystack = summary.to_ascii_lowercase();
    let mut total = 0.0f32;
    let mut hit = 0.0f32;
    for token in content {
        let weight = idf.get(token).copied().unwrap_or(0.0);
        total += weight;
        if weight > 0.0 && haystack.contains(token.as_str()) {
            hit += weight;
        }
    }
    if total <= f32::EPSILON {
        0.0
    } else {
        (hit / total).clamp(0.0, 1.0)
    }
}

/// v1.0.0: light query-side stemming — strip the common English inflection
/// suffixes so "benchmarked"/"benchmarking" reduce to "benchmark". Because
/// downstream matching uses substring lexical hints and FTS-prefix document
/// frequencies (`fts_query` also appends `*`), the
/// stem matches every variant in the corpus while the inflected form matches
/// none of them — an unstemmed "benchmarked" gets df=0, loses all IDF
/// weight, and the relevance floor goes blind on the query's one
/// discriminating word. Haystacks stay raw; only query tokens are stemmed.
/// Conservative: a suffix is stripped only when ≥4 chars remain, and only
/// one suffix is stripped.
///
/// v2.6: plus the English y→ies rule, which the suffix list alone gets wrong in
/// both directions. `"retries"` strips `es` to `retri`; `"retry"` matches no
/// suffix and stays `retry`; neither is a prefix of the other, so a query
/// asking about `retry` treats a corpus that says `retries` as not mentioning
/// it at all. BrainBench's sycophancy track found this by flagging a gap on a
/// question the memories plainly answered — the same defect silently costs the
/// lexical floor its IDF weight on any `-y` word (`query`, `policy`, `memory`,
/// `binary`), which is a large share of the vocabulary this corpus is made of.
///
/// Stripping a trailing `y`/`i` after a consonant collapses both forms onto the
/// shared prefix (`retry`, `retries` → `retr`), which is what substring and
/// FTS-prefix matching need. Only after a consonant, so `day`/`key` keep their
/// vowel-`y`, and only with ≥4 chars remaining, so short words are left alone.
fn light_stem(token: &str) -> &str {
    let mut stem = token;
    for suffix in ["ing", "ed", "es", "s"] {
        if let Some(stripped) = token.strip_suffix(suffix)
            && stripped.len() >= 4
        {
            stem = stripped;
            break;
        }
    }
    if stem.len() >= 5
        && let Some(trimmed) = stem.strip_suffix('y').or_else(|| stem.strip_suffix('i'))
        && trimmed
            .chars()
            .next_back()
            .is_some_and(|c| !matches!(c, 'a' | 'e' | 'i' | 'o' | 'u'))
    {
        return trimmed;
    }
    stem
}

fn query_tokens(query: &str) -> Vec<String> {
    let mut tokens: Vec<String> = query
        .split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
        .map(str::trim)
        .filter(|part| part.len() >= 2)
        .map(str::to_ascii_lowercase)
        .map(|t| light_stem(&t).to_string())
        .collect();
    // MP-17 #11: task-class routing — augment the query with tool-aware
    // tokens so MP-17b's tool-proficiency capsules surface higher when
    // the task description matches a known class. Cheap keyword fan-out;
    // the underlying lexical_relevance counts substring matches so the
    // augmented tokens only matter when a capsule's text actually mentions
    // them (i.e. the new MP-17b capsules light up, not generic text).
    let lower = query.to_ascii_lowercase();
    for (triggers, expansions) in CLASS_HINTS.iter() {
        if triggers.iter().any(|t| lower.contains(t)) {
            tokens.extend(expansions.iter().map(|e| e.to_string()));
        }
    }
    tokens
}

// MP-17 #11: (trigger keywords, expansion tokens) pairs.
//
// When the user task mentions a trigger, we add the expansions to the
// query token set. Capsules whose text mentions the same expansions
// then score higher on lexical_relevance. The expansions are kimetsu
// tool / concept names so MP-17b capsules (which document those tools)
// surface preferentially.
const CLASS_HINTS: &[(&[&str], &[&str])] = &[
    (
        &[
            "build",
            "compile",
            "make",
            "cargo",
            "cmake",
            "configure",
            "install",
            "train",
            "benchmark",
            "test suite",
            "ray trace",
            "render",
        ],
        &[
            "shell_background",
            "shell_status",
            "shell_output",
            "shell_stop",
            "long_running",
        ],
    ),
    (
        &[
            "edit", "modify", "change", "fix", "update", "patch", "refactor", "rename",
        ],
        &["edit_file", "apply_patch", "old_string", "new_string"],
    ),
    (
        &[
            "read", "inspect", "review", "analyze", "examine", "view", "show",
        ],
        &["read_file", "offset", "limit", "multi_read"],
    ),
    (
        &["find", "locate", "search", "look up", "discover", "list"],
        &["glob", "search_files", "list_files"],
    ),
    (
        &["plan", "step", "checklist", "todo", "task list", "phase"],
        &["plan", "todos"],
    ),
    (
        &[
            "verify",
            "check",
            "ensure",
            "validate",
            "pass test",
            "verifier",
        ],
        &["finish", "verifier", "verification"],
    ),
    (
        &[
            "image",
            "png",
            "jpeg",
            "jpg",
            "pdf",
            "diagram",
            "screenshot",
        ],
        &["view_image", "base64", "sha256"],
    ),
    (&["delete", "remove", "rm "], &["delete_file", "recursive"]),
    (&["rename", "move file", "mv "], &["move_file"]),
];

/// v0.8: does a capsule satisfy a requested (memory) kind? Repo/manifest
/// capsules match only by their literal `kind`; memory capsules
/// (`kind == "memory"`) match against the real kind embedded in their
/// `"scope:kind - text"` summary prefix.
fn capsule_matches_kind(capsule: &ContextCapsule, wanted: &str) -> bool {
    if capsule.kind == wanted {
        return true;
    }
    if capsule.kind == "memory"
        && let Some((prefix, _)) = capsule.summary.split_once(" - ")
        && let Some((_scope, mkind)) = prefix.split_once(':')
    {
        return mkind == wanted;
    }
    false
}

pub(crate) fn fts_query(query: &str) -> Option<String> {
    let tokens = query_tokens(query);
    if tokens.is_empty() {
        return None;
    }
    Some(
        tokens
            .into_iter()
            .take(12)
            .map(|token| format!("{token}*"))
            .collect::<Vec<_>>()
            .join(" OR "),
    )
}

/// D1e: candidate-stage MMR using embedding cosine similarity as the
/// redundancy measure, with Jaccard-of-summary-tokens as the fallback
/// when either candidate lacks an embedding vector.
///
/// Called BEFORE the candidate→capsule conversion so the `Candidate`
/// embedding fields are still accessible. Input must already be sorted
/// by descending score (the pipeline sorts before calling this).
///
/// Redundancy measure:
///   * Both candidates have embeddings of the same model → cosine(a, b).
///     cosine ∈ [-1, 1]; we use it directly as the overlap penalty.
///     Two paraphrases ("prefer rg" / "use ripgrep") will typically
///     share high cosine (≥0.85) and collapse to one slot.
///   * Either candidate lacks an embedding → Jaccard of summary-token
///     sets, scaled by 0.5 for cross-kind pairs (mirrors the existing
///     capsule-stage logic).
///
/// Cross-kind pairs are penalized at half the same-kind rate for both
/// measures (consistent with the capsule-stage Jaccard MMR).
fn apply_candidate_mmr_diversity(mut sorted: Vec<Candidate>, lambda: f32) -> Vec<Candidate> {
    if sorted.len() <= 1 {
        return sorted;
    }
    // Pre-tokenize summaries for the Jaccard fallback.
    let summaries: Vec<std::collections::HashSet<String>> = sorted
        .iter()
        .map(|c| summary_token_set(&c.capsule.summary))
        .collect();

    let mut picked_indices: Vec<usize> = Vec::with_capacity(sorted.len());
    let mut remaining: Vec<usize> = (0..sorted.len()).collect();

    // Seed with the highest-scoring candidate.
    picked_indices.push(remaining.remove(0));

    while !remaining.is_empty() {
        let mut best_idx_in_remaining = 0;
        let mut best_score = f32::MIN;

        for (i, &cand) in remaining.iter().enumerate() {
            let mut max_overlap = 0.0f32;
            for &p in &picked_indices {
                // Compute redundancy between candidate `cand` and
                // already-picked `p`.
                let same_kind = sorted[cand].capsule.kind == sorted[p].capsule.kind;
                let raw_overlap = candidate_pair_overlap(
                    &sorted[cand],
                    &sorted[p],
                    &summaries[cand],
                    &summaries[p],
                );
                let overlap = if same_kind {
                    raw_overlap
                } else {
                    raw_overlap * 0.5
                };
                if overlap > max_overlap {
                    max_overlap = overlap;
                }
            }
            let mmr = lambda * sorted[cand].capsule.score - (1.0 - lambda) * max_overlap;
            if mmr > best_score {
                best_score = mmr;
                best_idx_in_remaining = i;
            }
        }
        picked_indices.push(remaining.remove(best_idx_in_remaining));
    }

    // Reconstruct in picked order.
    let mut taken: Vec<Option<Candidate>> = sorted.drain(..).map(Some).collect();
    let mut out = Vec::with_capacity(taken.len());
    for idx in picked_indices {
        if let Some(c) = taken[idx].take() {
            out.push(c);
        }
    }
    out
}

/// D1e: overlap between two candidates for MMR.
///
/// * Both have embeddings → cosine similarity (clamped to [0,1] to
///   treat anti-correlated vectors as non-redundant, not negatively
///   redundant).
/// * Either lacks an embedding → Jaccard of summary-token sets.
fn candidate_pair_overlap(
    a: &Candidate,
    b: &Candidate,
    tokens_a: &std::collections::HashSet<String>,
    tokens_b: &std::collections::HashSet<String>,
) -> f32 {
    if let (Some(va), Some(vb)) = (a.embedding.as_deref(), b.embedding.as_deref()) {
        // Cosine in [-1,1]; clamp to [0,1] so negative correlation
        // (very different content) contributes 0 overlap rather than
        // a negative penalty (which would spuriously boost unrelated
        // content over moderately-related content).
        cosine_similarity(va, vb).max(0.0)
    } else {
        jaccard(tokens_a, tokens_b)
    }
}

/// MP-17 #13: greedy MMR (Maximal Marginal Relevance) re-ranking.
///
/// Given capsules already sorted by relevance score, walk the list and
/// at each step pick the next capsule that maximizes
/// `lambda * score - (1 - lambda) * max_overlap_with_already_picked`.
///
/// Overlap = Jaccard similarity of the lowercased token sets of the
/// `summary` field. Capsules from different kinds (memory / repo_file /
/// manifest) get a 0.5 similarity floor so redundancy is only penalized
/// within-kind (a memory and a repo_file aren't really redundant even
/// if they share words).
fn apply_mmr_diversity(mut sorted: Vec<ContextCapsule>, lambda: f32) -> Vec<ContextCapsule> {
    if sorted.len() <= 1 {
        return sorted;
    }
    // Pre-tokenize summaries for cheap Jaccard.
    let summaries: Vec<std::collections::HashSet<String>> = sorted
        .iter()
        .map(|c| summary_token_set(&c.summary))
        .collect();
    let mut picked_indices: Vec<usize> = Vec::with_capacity(sorted.len());
    let mut remaining: Vec<usize> = (0..sorted.len()).collect();

    // Always seed with the top-scoring capsule.
    picked_indices.push(remaining.remove(0));

    while !remaining.is_empty() {
        let mut best_idx_in_remaining = 0;
        let mut best_score = f32::MIN;
        for (i, &cand) in remaining.iter().enumerate() {
            let mut max_overlap = 0.0f32;
            for &p in &picked_indices {
                let raw = jaccard(&summaries[cand], &summaries[p]);
                let overlap = if sorted[cand].kind == sorted[p].kind {
                    raw
                } else {
                    // cross-kind: scale down so we don't over-penalize a memory
                    // that happens to share words with a repo file.
                    raw * 0.5
                };
                if overlap > max_overlap {
                    max_overlap = overlap;
                }
            }
            let mmr = lambda * sorted[cand].score - (1.0 - lambda) * max_overlap;
            if mmr > best_score {
                best_score = mmr;
                best_idx_in_remaining = i;
            }
        }
        picked_indices.push(remaining.remove(best_idx_in_remaining));
    }
    // Reorder `sorted` to match picked_indices.
    let mut out = Vec::with_capacity(sorted.len());
    // We need to drain in picked_indices order; do it by taking with mem::replace.
    let mut taken: Vec<Option<ContextCapsule>> = sorted.drain(..).map(Some).collect();
    for idx in picked_indices {
        if let Some(c) = taken[idx].take() {
            out.push(c);
        }
    }
    out
}

fn summary_token_set(s: &str) -> std::collections::HashSet<String> {
    s.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
        .filter(|t| t.len() >= 3)
        .map(str::to_ascii_lowercase)
        .collect()
}

fn jaccard(a: &std::collections::HashSet<String>, b: &std::collections::HashSet<String>) -> f32 {
    if a.is_empty() && b.is_empty() {
        return 0.0;
    }
    let intersection = a.intersection(b).count();
    let union = a.union(b).count();
    intersection as f32 / union.max(1) as f32
}

fn lexical_relevance(tokens: &[String], haystack: &str) -> f32 {
    if tokens.is_empty() {
        return 0.0;
    }
    let haystack = haystack.to_ascii_lowercase();
    let matches = tokens
        .iter()
        .filter(|token| haystack.contains(token.as_str()))
        .count();
    matches as f32 / tokens.len() as f32
}

pub fn estimate_tokens(text: &str) -> u32 {
    ((text.split_whitespace().count() as f32) * 1.33).ceil() as u32
}

// -----------------------------------------------------------------------
// v1.5 (Story 2.1): render-time capsule compression
// -----------------------------------------------------------------------

/// Render-time compression: strips the `[tags: ...]` prefix and the trailing
/// `(context: ...)` suffix, then caps at the first `max_sentences` sentences.
///
/// **Architectural invariant**: this function is called ONLY at render time —
/// after retrieval and reranking. Ranking inputs, stored `summary` text, and
/// the eval/bench retrieval paths are never affected. The full text stays
/// available via `expansion_handle`.
///
/// Sentence splitting uses `". "` / `".\n"` boundaries (simple, reliable,
/// UTF-8-safe). Common abbreviation edge cases are deliberately NOT handled —
/// the savings far outweigh an occasional mid-abbreviation split.
///
/// The `scope:kind - ` prefix that memory summaries carry (e.g.
/// `"project:fact - Some lesson here."`) is preserved: compression applies
/// only to the text *after* the ` - ` separator.
///
/// Fallback: never returns an empty string — when trimming would leave nothing,
/// the original input is returned unchanged.
pub fn compress_for_render(summary: &str, max_sentences: usize) -> String {
    if max_sentences == 0 {
        return summary.to_string();
    }

    // ── 1. Strip [tags: ...] prefix (if present) ─────────────────────────
    let text = if let Some(rest) = summary.strip_prefix('[') {
        // Find the closing ']' followed by optional whitespace
        if let Some(idx) = rest.find(']') {
            rest[idx + 1..].trim_start()
        } else {
            summary
        }
    } else {
        summary
    };

    // ── 2. Strip (context: ...) suffix (if present) ──────────────────────
    let text = if let Some(idx) = text.rfind('(') {
        let candidate = text[..idx].trim_end();
        // Only strip if the parenthetical looks like a trailing annotation
        // (contains a ':' inside), to avoid stripping content parentheses.
        let inner = &text[idx + 1..];
        if inner.contains(':') && inner.trim_end().ends_with(')') {
            candidate
        } else {
            text
        }
    } else {
        text
    };

    // ── 3. Detect and preserve "scope:kind - " prefix ────────────────────
    let (scope_prefix, body) = if let Some(dash_pos) = text.find(" - ") {
        let prefix_candidate = &text[..dash_pos];
        // Must look like "word:word" (no spaces in the prefix part)
        if !prefix_candidate.contains(' ') && prefix_candidate.contains(':') {
            let body_start = dash_pos + 3; // len(" - ")
            (&text[..body_start], &text[body_start..])
        } else {
            ("", text)
        }
    } else {
        ("", text)
    };

    // ── 4. Cap at max_sentences on the body ──────────────────────────────
    let compressed_body = cap_sentences(body, max_sentences);

    // ── 5. Reassemble; fallback to original if result would be empty ─────
    let result = if scope_prefix.is_empty() {
        compressed_body.to_string()
    } else {
        format!("{scope_prefix}{compressed_body}")
    };

    if result.trim().is_empty() {
        summary.to_string()
    } else {
        result
    }
}

/// Return the first `n` sentences from `text`, where sentences end at
/// `". "` or `".\n"` boundaries. The terminal period is included in the
/// returned slice. If fewer than `n` sentences exist the full text is returned.
fn cap_sentences(text: &str, n: usize) -> &str {
    let bytes = text.as_bytes();
    let len = bytes.len();
    let mut count = 0;
    let mut i = 0;
    while i < len {
        // Look for ". " or ".\n" — a period followed by whitespace.
        if bytes[i] == b'.' {
            let next = i + 1;
            if next < len && (bytes[next] == b' ' || bytes[next] == b'\n') {
                count += 1;
                if count >= n {
                    // Include the period, trim trailing whitespace on the slice.
                    return text[..=i].trim_end();
                }
            }
        }
        i += 1;
    }
    // Fewer than n sentences — return the whole text.
    text.trim_end()
}

fn excerpt(text: &str) -> String {
    let value = one_line(text);
    value.chars().take(256).collect()
}

fn one_line(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

// -----------------------------------------------------------------------
// F2: capsule resolver — expand a headline handle to its full text.
// -----------------------------------------------------------------------

/// Maximum bytes returned when resolving a `file:` handle. Keeps large
/// source files from flooding the context window on a single expand call.
const FILE_EXPAND_CAP_BYTES: usize = 2048;

/// F2: resolve an expansion handle to its full text content.
///
/// Handles:
/// - `memory:<id>` → `SELECT text FROM memories WHERE memory_id = ?`
/// - `file:<path>` → read `repo_root/<path>`, capped at [`FILE_EXPAND_CAP_BYTES`]
/// - `run:<id>`    → deferred; returns a descriptive error
/// - anything else → returns a descriptive error
///
/// This is the resolver that the `expand_capsule` agent tool delegates to.
/// All errors are user-visible (returned to the agent as a tool-result
/// error string) and never crash the dispatch loop.
pub fn resolve_capsule(
    conn: &Connection,
    repo_root: &std::path::Path,
    handle: &str,
) -> kimetsu_core::KimetsuResult<String> {
    if let Some(memory_id) = handle.strip_prefix("memory:") {
        // SELECT the raw text from the memories table.
        let mut stmt = conn.prepare_cached(
            "SELECT text FROM memories WHERE memory_id = ? AND invalidated_at IS NULL",
        )?;
        let text: Option<String> = stmt
            .query_row(rusqlite::params![memory_id], |row| row.get(0))
            .optional()?;
        match text {
            Some(t) => Ok(t),
            None => {
                Err(format!("expand_capsule: no active memory found for handle `{handle}`").into())
            }
        }
    } else if let Some(rel_path) = handle.strip_prefix("file:") {
        // Sanitize: reject absolute paths (drive-letter or Unix-root) and
        // `..` traversal. On Windows, POSIX-style `/foo` paths are not
        // considered absolute by `is_absolute()` (no drive prefix), so we
        // also reject paths with a RootDir component.
        let path = std::path::Path::new(rel_path);
        if path.is_absolute() {
            return Err(format!(
                "expand_capsule: `{handle}` is an absolute path — only repo-relative paths are supported"
            )
            .into());
        }
        for component in path.components() {
            match component {
                std::path::Component::ParentDir => {
                    return Err(format!(
                        "expand_capsule: `{handle}` contains `..` traversal — rejected"
                    )
                    .into());
                }
                std::path::Component::RootDir | std::path::Component::Prefix(_) => {
                    return Err(format!(
                        "expand_capsule: `{handle}` is an absolute path — only repo-relative paths are supported"
                    )
                    .into());
                }
                _ => {}
            }
        }
        let full_path = repo_root.join(path);
        let bytes = std::fs::read(&full_path)
            .map_err(|e| format!("expand_capsule: could not read `{rel_path}`: {e}"))?;
        // Bound the returned slice so huge files don't blow the context window.
        let bounded = if bytes.len() > FILE_EXPAND_CAP_BYTES {
            let mut end = FILE_EXPAND_CAP_BYTES;
            // Snap back to a UTF-8 boundary so we don't slice mid-codepoint.
            while end > 0 && (bytes[end] & 0xC0) == 0x80 {
                end -= 1;
            }
            let s = String::from_utf8_lossy(&bytes[..end]);
            format!(
                "{s}\n[... truncated at {FILE_EXPAND_CAP_BYTES} bytes; call expand_capsule again with a line range if needed]"
            )
        } else {
            String::from_utf8_lossy(&bytes).into_owned()
        };
        Ok(bounded)
    } else if handle.starts_with("run:") {
        Err(format!(
            "expand_capsule: `run:` handle expansion is not yet supported (handle: `{handle}`)"
        )
        .into())
    } else {
        Err(format!(
            "expand_capsule: unrecognised handle format `{handle}`; \
             expected `memory:<id>`, `file:<path>`, or `run:<id>`"
        )
        .into())
    }
}

// ── v1.0.0: cross-encoder reranking ──────────────────────────────────────

/// v1.0.0: final-stage cross-encoder rerank over already-retrieved capsules.
/// Reranks by `summary`, overwrites `score` with the sigmoid-normalized
/// rerank score, sorts descending, drops capsules below `floor`, truncates
/// to `cap` (0 = no cap). Fail-open: on a rerank error the input ordering
/// is returned unchanged (truncated to `cap`) — a broken reranker must
/// never lose retrieval entirely.
/// v2.7: width of the evidence band below `abstain_evidence` in which the
/// cross-encoder arbitrates instead of the raw cosine. Below
/// `abstain_evidence - ABSTAIN_BAND_WIDTH` the retrieval hard-abstains.
pub const ABSTAIN_BAND_WIDTH: f32 = 0.10;

fn abstain_band_width() -> f32 {
    std::env::var("KIMETSU_ABSTAIN_BAND_WIDTH")
        .ok()
        .and_then(|v| v.parse::<f32>().ok())
        .unwrap_or(ABSTAIN_BAND_WIDTH)
        .clamp(0.0, 1.0)
}

/// v2.7: default cross-encoder score a band bundle must reach to be injected.
/// Swept on the workflow benchmark (ms-marco-tinybert, n=150/floor): recall
/// was FLAT from 0.3 through 0.95 (useful-hit 0.80 → 0.79) while
/// false-injection fell monotonically (0.32 → 0.24) — genuinely relevant band
/// bundles saturate the tinybert sigmoid, junk does not. 0.9 takes most of
/// that precision and leaves margin for cross-encoders whose scores don't
/// saturate as hard. Overridable via `KIMETSU_ABSTAIN_RERANK_FLOOR`.
pub const ABSTAIN_RERANK_FLOOR: f32 = 0.9;

fn abstain_rerank_floor() -> f32 {
    std::env::var("KIMETSU_ABSTAIN_RERANK_FLOOR")
        .ok()
        .and_then(|v| v.parse::<f32>().ok())
        .unwrap_or(ABSTAIN_RERANK_FLOOR)
}

/// v2.7: post-retrieval reranking + evidence-band arbitration, shared by every
/// call site that owns a cross-encoder (CLI `brain context`, MCP server, embed
/// daemon).
///
/// The retrieval pipeline hard-abstains below `abstain_evidence -`
/// [`ABSTAIN_BAND_WIDTH`] and returns bundles above it. This helper decides
/// the band in between: the cross-encoder rescoring recognizes paraphrased
/// matches that raw bi-encoder cosine under-scores, so a band bundle whose
/// best rerank score clears [`ABSTAIN_RERANK_FLOOR`] is injected and one that
/// doesn't is converted to a skipped (zero-token) bundle. Out-of-band bundles
/// are reranked for ordering but never converted.
///
/// With no reranker available the band FAILS CLOSED (skipped) — equivalent to
/// the plain hard gate at `abstain_evidence` — so a lean build is never
/// noisier than the gate promises. Bundles containing non-memory capsules are
/// never converted (repo evidence stands on its own), and `abstain_evidence
/// <= 0` disables arbitration entirely.
pub fn rerank_and_arbitrate(
    query: &str,
    mut bundle: ContextBundle,
    reranker: Option<&dyn crate::embeddings::Reranker>,
    abstain_evidence: f32,
    rerank_floor: f32,
    rerank_cap: usize,
) -> ContextBundle {
    if bundle.skipped || bundle.capsules.is_empty() {
        return bundle;
    }
    let memory_only = bundle.capsules.iter().all(|c| c.kind == "memory");
    // top_abs_evidence < 0.0 means "no cosine evidence exists" (lean builds,
    // cross-model rows) — the band is a cosine construct, so it is exempt.
    let in_band = abstain_evidence > 0.0
        && memory_only
        && bundle.top_abs_evidence >= 0.0
        && bundle.top_abs_evidence < abstain_evidence;

    let to_skipped = |mut bundle: ContextBundle| -> ContextBundle {
        let rejected = std::mem::take(&mut bundle.capsules);
        bundle.excluded.extend(rejected);
        bundle.skipped = true;
        bundle.used_tokens = 0;
        bundle.evidence_coverage = 0.0;
        bundle.uncovered_terms = Vec::new();
        bundle.chronological = false;
        bundle
    };

    match reranker {
        Some(rr) => {
            let reranked = rerank_capsules_with_diagnostics(
                query,
                std::mem::take(&mut bundle.capsules),
                rr,
                rerank_floor,
                rerank_cap,
            );
            // Admission is calibrated on the RAW cross-encoder score, before
            // ranking policy is applied. Otherwise usefulness or supersession
            // could silently alter abstention behavior.
            let best_raw_rerank = reranked.best_raw_score.unwrap_or(0.0);
            bundle.capsules = reranked.capsules;
            bundle.used_tokens = bundle.capsules.iter().map(|c| c.token_estimate).sum();
            if in_band && best_raw_rerank < abstain_rerank_floor() {
                to_skipped(bundle)
            } else {
                bundle
            }
        }
        // No arbiter: the band fails closed, matching the hard gate.
        None if in_band => to_skipped(bundle),
        None => bundle,
    }
}

pub fn rerank_capsules(
    query: &str,
    capsules: Vec<ContextCapsule>,
    reranker: &dyn crate::embeddings::Reranker,
    floor: f32,
    cap: usize,
) -> Vec<ContextCapsule> {
    rerank_capsules_with_diagnostics(query, capsules, reranker, floor, cap).capsules
}

struct RerankOutcome {
    capsules: Vec<ContextCapsule>,
    /// Best raw cross-encoder score among capsules that survived the ranking
    /// floor.
    /// `None` means the reranker did not produce a usable verdict.
    best_raw_score: Option<f32>,
}

fn effective_rerank_policy_tier(capsule: &ContextCapsule) -> i8 {
    // A superseded memory must not retain a historic citation advantage over
    // its replacement. Its explicit post-rerank penalty carries that policy.
    if capsule.superseded_hint {
        0
    } else {
        capsule.rerank_policy_tier
    }
}

fn rerank_capsules_with_diagnostics(
    query: &str,
    capsules: Vec<ContextCapsule>,
    reranker: &dyn crate::embeddings::Reranker,
    floor: f32,
    cap: usize,
) -> RerankOutcome {
    if capsules.is_empty() {
        return RerankOutcome {
            capsules,
            best_raw_score: None,
        };
    }

    // Rerank on the FULL summary. Truncating to a snippet was tried for
    // latency and measurably cratered quality on the eval fixture
    // (recall@4 0.83 → 0.66, below even FTS) — the cross-encoder needs the
    // whole lesson to judge relevance. Reranking is therefore a
    // quality-over-latency opt-in, not part of the hook's 300ms budget.
    let docs: Vec<&str> = capsules.iter().map(|c| c.summary.as_str()).collect();
    let scores = match reranker.rerank(query, &docs) {
        // The trait contract is one score per doc in doc order; a custom
        // third-party reranker that returns a short vec would otherwise
        // silently drop the unscored tail via the zip below — treat a
        // length mismatch as an error and fail open instead.
        Ok(s) if s.len() == docs.len() => s,
        _ => {
            // Fail-open: preserve input order, just apply cap.
            let mut out = capsules;
            if cap > 0 && out.len() > cap {
                out.truncate(cap);
            }
            return RerankOutcome {
                capsules: out,
                best_raw_score: None,
            };
        }
    };

    // Apply bounded usefulness, then trust and supersession; admission uses raw scores.
    let mut ranked: Vec<(ContextCapsule, f32)> = capsules
        .into_iter()
        .zip(scores)
        .map(|(mut c, s)| {
            let multiplier = if c.superseded_hint {
                1.0
            } else {
                c.rerank_usefulness
                    .unwrap_or(1.0 + 0.5 * effective_rerank_policy_tier(&c) as f32)
            };
            c.score = apply_usefulness_boost(s, multiplier.clamp(0.5, 1.5))
                * c.rerank_trust.unwrap_or(1.0).clamp(0.0, 1.0);
            if c.superseded_hint {
                c.score *= SUPERSESSION_PENALTY;
            }
            (c, s)
        })
        .collect();

    ranked.sort_by(|a, b| b.0.score.total_cmp(&a.0.score));

    // This is the ordinary per-capsule retention floor. The separate
    // evidence-band decision reads `best_raw_score` before the supersession
    // policy is reapplied, because its 0.9 threshold was calibrated on the
    // cross-encoder's sigmoid scale.
    ranked.retain(|(_, raw_score)| *raw_score >= floor);

    // Admission evidence is independent of policy ordering and output cap.
    // A high-confidence neutral capsule displaced by a cited one still proves
    // that the in-band bundle has relevant evidence.
    let best_raw_score = ranked
        .iter()
        .map(|(_, raw_score)| *raw_score)
        .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

    if cap > 0 && ranked.len() > cap {
        ranked.truncate(cap);
    }

    RerankOutcome {
        capsules: ranked.into_iter().map(|(c, _)| c).collect(),
        best_raw_score,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn capsule(kind: &str, summary: &str) -> ContextCapsule {
        ContextCapsule {
            id: "c".into(),
            kind: kind.into(),
            summary: summary.into(),
            token_estimate: 1,
            expansion_handle: "memory:x".into(),
            provenance: vec![],
            confidence: 1.0,
            freshness: 1.0,
            relevance: 1.0,
            scope_weight: 1.0,
            score: 1.0,
            superseded_hint: false,
            rerank_policy_tier: 0,
            claim_revision: None,
            facts: vec![],
            rerank_usefulness: None,
            rerank_trust: None,
        }
    }

    /// Create a unique temp directory under the system temp path.
    /// Named by `tag` so test failures are diagnosable.
    fn make_test_dir(tag: &str) -> std::path::PathBuf {
        use std::time::{SystemTime, UNIX_EPOCH};
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.subsec_nanos())
            .unwrap_or(0);
        let dir = std::env::temp_dir().join(format!("kbrain_test_{tag}_{ts}"));
        std::fs::create_dir_all(&dir).expect("create test dir");
        dir
    }

    #[test]
    fn capsule_matches_kind_reads_memory_summary_prefix() {
        // Memory capsule: real kind lives in the "scope:kind - text" prefix.
        let mem = capsule("memory", "project:failure_pattern - linker not found");
        assert!(capsule_matches_kind(&mem, "failure_pattern"));
        assert!(!capsule_matches_kind(&mem, "command"));
        // Non-memory capsules match only by literal kind, never via prefix.
        let repo = capsule("repo_file", "src/lib.rs:command - run build");
        assert!(capsule_matches_kind(&repo, "repo_file"));
        assert!(!capsule_matches_kind(&repo, "command"));
    }

    /// MP-17e: zero-use rows are neutral (no data); use_count >= 1 starts
    /// blending toward the full multiplier (Bayesian smoothing).
    #[test]
    fn usefulness_multiplier_neutral_at_zero_uses() {
        // use_count = 0 is the only strictly-neutral case.
        assert!((usefulness_multiplier(0.0, 0) - 1.0).abs() < f32::EPSILON);
        assert!((usefulness_multiplier(5.0, 0) - 1.0).abs() < f32::EPSILON);
        assert!((usefulness_multiplier(-5.0, 0) - 1.0).abs() < f32::EPSILON);
    }

    /// MP-17e: between use_count 1..3 the multiplier blends linearly from
    /// neutral (1.0) toward the full envelope. A use_count of 2 with a
    /// perfect ratio lands at 2/3 of the way to the max boost.
    #[test]
    fn usefulness_multiplier_blends_smoothly_in_transition() {
        // use_count = 1, ratio = 1.0 -> confidence 1/3, blend toward 1.5
        // expected = 1.0 * 2/3 + 1.5 * 1/3 = 1.1667
        let one_use = usefulness_multiplier(1.0, 1);
        assert!((one_use - 1.166_666_6).abs() < 1e-4, "got {one_use}");
        // use_count = 2, ratio = 1.0 -> confidence 2/3, blend toward 1.5
        // expected = 1.0 * 1/3 + 1.5 * 2/3 = 1.3333
        let two_uses = usefulness_multiplier(2.0, 2);
        assert!((two_uses - 1.333_333_4).abs() < 1e-4, "got {two_uses}");
        // use_count = 2 with ratio = -1.0 should pull toward the penalty side.
        let two_uses_bad = usefulness_multiplier(-2.0, 2);
        // expected = 1.0 * 1/3 + 0.5 * 2/3 = 0.6667
        assert!(
            (two_uses_bad - 0.666_666_7).abs() < 1e-4,
            "got {two_uses_bad}"
        );
    }

    /// MP-4b: at use_count >= 3 the multiplier maps ratio in [-1, 1] linearly
    /// onto [MULTIPLIER_MIN, MULTIPLIER_MAX] = [0.5, 1.5]. A neutral memory
    /// (ratio = 0) gets a 1.0 multiplier.
    #[test]
    fn usefulness_multiplier_maps_ratio_onto_envelope() {
        // ratio = 1.0 -> 1.5 (max boost)
        assert!((usefulness_multiplier(5.0, 5) - 1.5).abs() < f32::EPSILON);
        // ratio = -1.0 -> 0.5 (max penalty)
        assert!((usefulness_multiplier(-5.0, 5) - 0.5).abs() < f32::EPSILON);
        // ratio = 0.0 -> 1.0 (neutral)
        let mid = usefulness_multiplier(0.0, 6);
        assert!((mid - 1.0).abs() < f32::EPSILON, "got {mid}");
        // ratio = 0.5 -> 1.25 (mid boost)
        let high = usefulness_multiplier(2.0, 4);
        assert!((high - 1.25).abs() < f32::EPSILON, "got {high}");
        // ratio = -0.5 -> 0.75 (mid penalty)
        let low = usefulness_multiplier(-2.0, 4);
        assert!((low - 0.75).abs() < f32::EPSILON, "got {low}");
    }

    /// MP-4b: the multiplier is bounded so even a runaway score cannot
    /// dominate the budget; a single memory with usefulness_score >> use_count
    /// is clamped at the upper envelope.
    #[test]
    fn usefulness_multiplier_clamps_to_envelope() {
        // ratio > 1.0 is clamped to 1.0 -> 1.5
        assert!((usefulness_multiplier(100.0, 5) - 1.5).abs() < f32::EPSILON);
        // ratio < -1.0 is clamped to -1.0 -> 0.5
        assert!((usefulness_multiplier(-100.0, 5) - 0.5).abs() < f32::EPSILON);
    }

    // ----- v2.5.1: citation-boost saturation (LoCoMo k=5 collapse fix) -----

    /// The boost's absolute gain is capped: a max-boosted (1.5x) weakly
    /// relevant memory must NOT outrank a strongly relevant uncited one.
    /// This is the exact inversion observed in the LoCoMo learning run
    /// (junk at raw 0.39 x 1.5 = 0.58 beat a true match at 0.53).
    #[test]
    fn boost_gain_is_capped_so_cited_junk_cannot_beat_relevant_uncited() {
        let junk = apply_usefulness_boost(0.39, 1.5);
        let true_match = apply_usefulness_boost(0.53, 1.0);
        assert!(
            junk < true_match,
            "capped boost must preserve relevance order: junk {junk} vs match {true_match}"
        );
        // gain never exceeds the cap
        assert!(junk <= 0.39 + USEFULNESS_BOOST_CAP + f32::EPSILON);
    }

    /// Within a relevance band the boost still reorders: a proven memory at
    /// slightly lower relevance may overtake a neutral near-equal. This is
    /// the behaviour that produced the +4.6 holdout gain and must survive.
    #[test]
    fn boost_still_reorders_within_a_relevance_band() {
        let proven = apply_usefulness_boost(0.85, 1.5);
        let neutral = apply_usefulness_boost(0.90, 1.0);
        assert!(
            proven > neutral,
            "capped boost must still reorder near-equals: proven {proven} vs neutral {neutral}"
        );
    }

    /// Penalties stay multiplicative: suppressing net-negative memories
    /// below their raw relevance is desirable and unbounded-downward is safe
    /// (floor 0.5x from the multiplier envelope).
    #[test]
    fn penalty_side_remains_multiplicative() {
        let penalized = apply_usefulness_boost(0.8, 0.5);
        assert!((penalized - 0.4).abs() < 1e-6);
    }

    // ----- MP-17 #11: task-class query expansion -----

    #[test]
    fn query_tokens_expands_build_class() {
        let toks = query_tokens("Build the project from source");
        assert!(toks.iter().any(|t| t == "build"));
        // class-aware expansion adds tool tokens:
        assert!(toks.iter().any(|t| t == "shell_background"));
        assert!(toks.iter().any(|t| t == "long_running"));
    }

    #[test]
    fn query_tokens_expands_edit_class() {
        let toks = query_tokens("Modify the config to fix the bug");
        assert!(toks.iter().any(|t| t == "edit_file"));
        assert!(toks.iter().any(|t| t == "apply_patch"));
    }

    #[test]
    fn query_tokens_expands_search_class() {
        let toks = query_tokens("Find all references to the symbol");
        assert!(toks.iter().any(|t| t == "glob"));
        assert!(toks.iter().any(|t| t == "search_files"));
    }

    #[test]
    fn query_tokens_no_expansion_on_unrelated_query() {
        let toks = query_tokens("hello world testing nothing");
        // Only the "test" trigger fires here -> verification expansion.
        assert!(toks.iter().any(|t| t == "hello"));
        // The base tokens are present regardless.
        assert!(toks.iter().any(|t| t == "world"));
    }

    // ----- MP-17 #13: MMR diversity helpers -----

    #[test]
    fn jaccard_is_zero_for_disjoint_sets() {
        let a: std::collections::HashSet<String> =
            ["foo", "bar"].iter().map(|s| s.to_string()).collect();
        let b: std::collections::HashSet<String> =
            ["baz", "qux"].iter().map(|s| s.to_string()).collect();
        assert!((jaccard(&a, &b) - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn jaccard_is_one_for_identical_sets() {
        let a: std::collections::HashSet<String> =
            ["foo", "bar"].iter().map(|s| s.to_string()).collect();
        let b = a.clone();
        assert!((jaccard(&a, &b) - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn jaccard_partial_overlap() {
        let a: std::collections::HashSet<String> = ["foo", "bar", "baz"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let b: std::collections::HashSet<String> =
            ["bar", "qux"].iter().map(|s| s.to_string()).collect();
        // intersection = {bar} = 1, union = {foo,bar,baz,qux} = 4
        assert!((jaccard(&a, &b) - 0.25).abs() < f32::EPSILON);
    }

    #[test]
    fn summary_token_set_lowercases_and_filters_short() {
        let set = summary_token_set("Build the Foo-bar project");
        assert!(set.contains("build"));
        assert!(set.contains("foo"));
        assert!(set.contains("bar"));
        assert!(set.contains("project"));
        // "the" is len=3, included; "a" or "i" would be excluded.
        assert!(set.contains("the"));
    }

    // ----- v0.4.2: hybrid retrieval end-to-end -----

    /// Helper: open an in-memory brain.db, initialize schema, insert
    /// a memory row (post-projector shape) plus its embedding +
    /// embedding_model and the matching FTS entry.
    fn insert_memory_with_embedding(
        conn: &rusqlite::Connection,
        memory_id: &str,
        text: &str,
        embedder: &dyn embeddings::Embedder,
    ) {
        let normalized = kimetsu_core::memory::normalize_memory_text(text);
        conn.execute(
            "
            INSERT INTO memories (
                memory_id, scope, kind, text, normalized_text, confidence,
                source_event_id, provenance_snapshot_json, created_at,
                use_count, usefulness_score, embedding, embedding_model
            )
            VALUES (?1, 'global_user', 'fact', ?2, ?3, 1.0, NULL, '{}',
                    '2026-05-01T00:00:00Z', 0, 0.0, ?4, ?5)
            ",
            rusqlite::params![
                memory_id,
                text,
                normalized,
                embeddings::encode_embedding(&embedder.embed(text).expect("embed test row")),
                embedder.model_id(),
            ],
        )
        .expect("insert memory");
        conn.execute(
            "INSERT INTO memories_fts (memory_id, text, kind, scope) VALUES (?1, ?2, 'fact', 'global_user')",
            rusqlite::params![memory_id, text],
        )
        .expect("insert fts row");
    }

    /// v0.4.2: the cosine blend changes retrieval ranking when two
    /// memories tie lexically but differ semantically (via the stub
    /// embedder's hashed-bucket vectors).
    ///
    /// Setup: two memories, neither containing the query's literal
    /// words. With pure FTS, neither matches and we fall back to
    /// latest-memory ranking. With the stub embedder enabled, the
    /// memory that's "semantically closer" to the query (shares
    /// hash buckets) outranks the other.
    #[test]
    fn hybrid_retrieval_uses_cosine_score_to_rerank() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let stub = embeddings::StubEmbedder::new();

        insert_memory_with_embedding(&conn, "m_rg", "use ripgrep for code search", &stub);
        insert_memory_with_embedding(
            &conn,
            "m_unrelated",
            "cookie recipe with chocolate chips",
            &stub,
        );

        // Query shares words with m_rg but not m_unrelated. FTS will
        // already prefer m_rg here; we use that as the baseline.
        let weights = kimetsu_core::config::BrokerWeights::default();
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "ripgrep search".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &stub,
        )
        .expect("retrieve");

        let memory_handles: Vec<_> = bundle
            .capsules
            .iter()
            .filter(|c| c.expansion_handle.starts_with("memory:"))
            .collect();
        assert!(
            !memory_handles.is_empty(),
            "at least one memory should surface"
        );
        // The semantically-relevant memory must rank first.
        assert_eq!(
            memory_handles[0].expansion_handle,
            "memory:m_rg",
            "ripgrep memory should outrank the cookie recipe; ranked: {:?}",
            memory_handles
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );
    }

    /// v2.7: the absolute abstention gate. `top_abs_evidence` carries the best
    /// raw cosine; a floor above it skips the bundle entirely, a floor below
    /// it (or 0.0) lets the bundle through. Self-calibrating: the test reads
    /// the achieved evidence first rather than hard-coding a stub cosine.
    #[test]
    fn abstain_evidence_gate_skips_on_weak_absolute_evidence() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let stub = embeddings::StubEmbedder::new();
        insert_memory_with_embedding(&conn, "m_rg", "use ripgrep for code search", &stub);

        let weights = kimetsu_core::config::BrokerWeights::default();
        let retrieve = |abstain: f32| {
            retrieve_context_with_embedder(
                &conn,
                "/fake-repo",
                &weights,
                ContextRequest {
                    stage: "localization".to_string(),
                    query: "ripgrep search".to_string(),
                    budget_tokens: 4000,
                    abstain_evidence: abstain,
                    ..Default::default()
                },
                &[],
                &stub,
            )
            .expect("retrieve")
        };

        let open = retrieve(0.0);
        assert!(!open.skipped, "gate off must not skip");
        assert!(
            open.top_abs_evidence > 0.0,
            "a matching memory must report positive absolute evidence"
        );

        // The retrieval-internal gate hard-abstains one band-width below the
        // configured floor (the band itself is decided by the caller's
        // cross-encoder via rerank_and_arbitrate).
        let above = retrieve(open.top_abs_evidence + ABSTAIN_BAND_WIDTH + 0.05);
        assert!(
            above.skipped,
            "a floor a full band above the best evidence must hard-abstain (evidence {})",
            open.top_abs_evidence
        );
        assert!(above.capsules.is_empty(), "skipped bundle injects nothing");

        // In the band: retrieval itself does NOT skip — the arbiter decides.
        let in_band = retrieve(open.top_abs_evidence + 0.05);
        assert!(
            !in_band.skipped,
            "an in-band bundle passes through for arbitration"
        );

        let below = retrieve((open.top_abs_evidence - 0.05).max(0.01));
        assert!(!below.skipped, "a floor below the best evidence passes");
        assert!(!below.capsules.is_empty());
    }

    /// v0.4.2: when a row's stored `embedding_model` doesn't match
    /// the active query embedder's id, the row's cosine contribution
    /// is skipped — falling back to FTS-only for that row. Critical
    /// for safety across `kimetsu brain reindex` migrations (v0.4.3)
    /// where some rows might be embedded with the new model and some
    /// with the old.
    #[test]
    fn hybrid_retrieval_skips_cosine_on_model_id_mismatch() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let stub = embeddings::StubEmbedder::new();
        insert_memory_with_embedding(&conn, "m_xref", "use ripgrep for code search", &stub);

        // Stomp the row's embedding_model with a synthetic id that
        // doesn't match the active embedder. Simulates a `kimetsu
        // brain reindex` mid-migration where some rows are on the
        // new model and some on the old.
        conn.execute(
            "UPDATE memories SET embedding_model = 'bge-small-en-v1.5' WHERE memory_id = 'm_xref'",
            [],
        )
        .expect("force model_id mismatch");

        // Query through the stub embedder. Its model_id is "stub-d8";
        // the row's is "bge-small-en-v1.5". The cosine path MUST be
        // skipped for this row; FTS still surfaces it on the lexical
        // match because retrieval doesn't crash on cross-model rows.
        let weights = kimetsu_core::config::BrokerWeights::default();
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "ripgrep search".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &stub,
        )
        .expect("retrieve");

        assert!(
            bundle
                .capsules
                .iter()
                .any(|c| c.expansion_handle == "memory:m_xref"),
            "cross-model row should still match lexically (cosine skipped, FTS works)"
        );
    }

    // ----- v0.5.1: usefulness decay -----

    /// v0.5.1: `half_life_days <= 0` is the operator opt-out hatch.
    /// Decay must short-circuit to 1.0 so the usefulness multiplier
    /// is unmodified — exact pre-v0.5.1 behavior for projects that
    /// set `decay_half_life_days = 0` in project.toml.
    #[test]
    fn usefulness_decay_disabled_when_half_life_is_zero_or_negative() {
        // Even a 5-year-old reference returns 1.0 with decay disabled.
        let ancient = "2021-01-01T00:00:00Z";
        assert!((usefulness_decay(Some(ancient), ancient, 0.0) - 1.0).abs() < f32::EPSILON);
        assert!((usefulness_decay(Some(ancient), ancient, -1.0) - 1.0).abs() < f32::EPSILON);
    }

    /// v0.5.1: unparseable timestamps return 1.0 (fail-open). A
    /// corrupted row shouldn't get silently dropped out of retrieval
    /// just because its `last_useful_at` got mangled.
    #[test]
    fn usefulness_decay_returns_one_on_unparseable_timestamps() {
        assert!(
            (usefulness_decay(Some("not-a-date"), "also-not", 30.0) - 1.0).abs() < f32::EPSILON
        );
    }

    /// v0.5.1: a memory whose reference timestamp is "now" (no age)
    /// decays by zero — full contribution.
    #[test]
    fn usefulness_decay_full_at_zero_age() {
        // Use a timestamp from the future so age clamps to 0.
        let future = "2099-01-01T00:00:00Z";
        let d = usefulness_decay(Some(future), future, 30.0);
        assert!((d - 1.0).abs() < f32::EPSILON, "got {d}");
    }

    /// v0.5.1: at age == half_life, decay = 0.5; at age = 2 * half_life,
    /// decay = 0.25. Computed by setting `last_useful_at` to (now - days)
    /// using OffsetDateTime arithmetic — the only way to get a stable
    /// "now-relative" timestamp without freezing the clock.
    #[test]
    fn usefulness_decay_follows_half_life_curve() {
        let half_life = 10.0_f32;
        let now = OffsetDateTime::now_utc();
        let fmt = &time::format_description::well_known::Rfc3339;

        // age = half_life -> decay ~= 0.5
        let one_half_life_ago = (now - time::Duration::seconds((half_life * 86_400.0) as i64))
            .format(fmt)
            .expect("format");
        let d1 = usefulness_decay(Some(&one_half_life_ago), &one_half_life_ago, half_life);
        assert!(
            (d1 - 0.5).abs() < 0.01,
            "expected ~0.5 at one half-life, got {d1}"
        );

        // age = 2 * half_life -> decay ~= 0.25
        let two_half_lives_ago = (now
            - time::Duration::seconds((2.0 * half_life * 86_400.0) as i64))
        .format(fmt)
        .expect("format");
        let d2 = usefulness_decay(Some(&two_half_lives_ago), &two_half_lives_ago, half_life);
        assert!(
            (d2 - 0.25).abs() < 0.01,
            "expected ~0.25 at two half-lives, got {d2}"
        );
    }

    /// v0.5.1: when `last_useful_at` is None the function falls back to
    /// `created_at`. A 1-day-old never-cited memory should still get
    /// nearly-full decay (close to 1.0) for a 30-day half-life.
    #[test]
    fn usefulness_decay_falls_back_to_created_at_when_last_useful_is_none() {
        let now = OffsetDateTime::now_utc();
        let fmt = &time::format_description::well_known::Rfc3339;
        let one_day_ago = (now - time::Duration::seconds(86_400))
            .format(fmt)
            .expect("format");
        let d = usefulness_decay(None, &one_day_ago, 30.0);
        // exp(-ln(2) / 30) ≈ 0.977
        assert!(
            (d - 0.977).abs() < 0.01,
            "expected ~0.977 for 1-day-old created_at under 30d half-life, got {d}"
        );
    }

    /// v0.5.1: end-to-end retrieval test. Two memories with identical
    /// lexical match, identical use_count, identical (max) usefulness
    /// score — one cited yesterday, one cited a year ago. Decay must
    /// rank the recent one first.
    #[test]
    fn aged_cited_memory_ranks_below_recently_cited_memory() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        let now = OffsetDateTime::now_utc();
        let fmt = &time::format_description::well_known::Rfc3339;
        let one_day_ago = (now - time::Duration::seconds(86_400))
            .format(fmt)
            .expect("format");
        let one_year_ago = (now - time::Duration::seconds(365 * 86_400))
            .format(fmt)
            .expect("format");

        // Both memories say "use ripgrep for code search", both have
        // use_count = 5, usefulness_score = 5 (max boost → 1.5
        // multiplier). The only difference is `last_useful_at`.
        for (mid, last_useful) in [("m_recent", &one_day_ago), ("m_aged", &one_year_ago)] {
            let text = "use ripgrep for code search";
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "
                INSERT INTO memories (
                    memory_id, scope, kind, text, normalized_text, confidence,
                    source_event_id, provenance_snapshot_json, created_at,
                    use_count, usefulness_score, last_useful_at
                )
                VALUES (?1, 'global_user', 'fact', ?2, ?3, 1.0, NULL, '{}',
                        '2024-01-01T00:00:00Z', 5, 5.0, ?4)
                ",
                rusqlite::params![mid, text, normalized, last_useful],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'fact', 'global_user')",
                rusqlite::params![mid, text],
            )
            .expect("insert fts");
        }

        // Default broker weights → 30-day half-life. 1 year ≈ 12 half-lives.
        let weights = kimetsu_core::config::BrokerWeights::default();
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "ripgrep search".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve");

        let mem_order: Vec<&str> = bundle
            .capsules
            .iter()
            .filter_map(|c| c.expansion_handle.strip_prefix("memory:"))
            .collect();
        assert_eq!(
            mem_order.first().copied(),
            Some("m_recent"),
            "recently-cited memory must rank first under decay; got order {mem_order:?}"
        );
    }

    /// v0.5.1: with decay disabled (half_life = 0) the aged + recent
    /// memories tie and the deterministic tiebreaker (id) decides —
    /// proves the ranking flip in the previous test is *caused* by
    /// decay, not by some unrelated side effect of the timestamp.
    #[test]
    fn aged_cited_memory_does_not_decay_when_half_life_is_zero() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        let now = OffsetDateTime::now_utc();
        let fmt = &time::format_description::well_known::Rfc3339;
        let one_day_ago = (now - time::Duration::seconds(86_400))
            .format(fmt)
            .expect("format");
        let one_year_ago = (now - time::Duration::seconds(365 * 86_400))
            .format(fmt)
            .expect("format");

        for (mid, last_useful) in [("m_recent", &one_day_ago), ("m_aged", &one_year_ago)] {
            let text = "use ripgrep for code search";
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "
                INSERT INTO memories (
                    memory_id, scope, kind, text, normalized_text, confidence,
                    source_event_id, provenance_snapshot_json, created_at,
                    use_count, usefulness_score, last_useful_at
                )
                VALUES (?1, 'global_user', 'fact', ?2, ?3, 1.0, NULL, '{}',
                        '2024-01-01T00:00:00Z', 5, 5.0, ?4)
                ",
                rusqlite::params![mid, text, normalized, last_useful],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'fact', 'global_user')",
                rusqlite::params![mid, text],
            )
            .expect("insert fts");
        }

        // Disable decay via broker config.
        let weights = kimetsu_core::config::BrokerWeights {
            decay_half_life_days: 0.0,
            ..Default::default()
        };

        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "ripgrep search".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve");

        // Both memories should surface. With decay disabled, their
        // scores are identical (same multiplier, same lexical match,
        // same freshness band since both created_at are equal). The
        // sort tiebreaker falls back to id, so m_aged < m_recent
        // alphabetically.
        let scores: Vec<(String, f32)> = bundle
            .capsules
            .iter()
            .filter_map(|c| {
                c.expansion_handle
                    .strip_prefix("memory:")
                    .map(|id| (id.to_string(), c.score))
            })
            .collect();
        assert_eq!(scores.len(), 2, "both memories should surface");
        let recent_score = scores
            .iter()
            .find(|(id, _)| id == "m_recent")
            .map(|(_, s)| *s)
            .expect("m_recent present");
        let aged_score = scores
            .iter()
            .find(|(id, _)| id == "m_aged")
            .map(|(_, s)| *s)
            .expect("m_aged present");
        // With decay off, the two multipliers are equal → scores match.
        assert!(
            (recent_score - aged_score).abs() < 1e-4,
            "with decay disabled the two memories should tie on score: recent={recent_score} aged={aged_score}"
        );
    }

    /// v0.4.2: with [`NoopEmbedder`] the retrieval path is identical
    /// to v0.4.1 — no cosine term contributes, stored embeddings (if
    /// any) are ignored. Regression guard so the default build
    /// behaves identically to pre-v0.4.2.
    #[test]
    fn hybrid_retrieval_with_noop_embedder_is_lexical_only() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let stub = embeddings::StubEmbedder::new();
        // Two memories, both with non-null embeddings.
        insert_memory_with_embedding(&conn, "m_a", "use ripgrep", &stub);
        insert_memory_with_embedding(&conn, "m_b", "use ripgrep too", &stub);

        // Query through the Noop default. QueryEmbedding will be
        // None → no cosine blend → exact FTS ranking.
        let weights = kimetsu_core::config::BrokerWeights::default();
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "ripgrep".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve");

        let count = bundle
            .capsules
            .iter()
            .filter(|c| c.expansion_handle.starts_with("memory:"))
            .count();
        assert_eq!(count, 2, "both memories should surface via FTS");
    }

    // ---------------------------------------------------------------
    // D1d tests: ANN index correctness, rebuild on model change, dedup
    // ---------------------------------------------------------------

    /// D1d test 1: ANN finds a semantic match that FTS misses.
    ///
    /// Strategy: use a manually-crafted ("oracle") embedder that returns a
    /// FIXED known vector for any input, paired with a direct-SQL memory
    /// insertion that stores the SAME vector for the "semantic" memory and a
    /// DIFFERENT vector for the "lexical decoy". The query text and memory
    /// texts deliberately share NO words, so FTS returns nothing. ANN
    /// surfaces the semantically-near memory via the usearch index.
    ///
    /// Concretely:
    ///   - query text = "phosphorescent bioluminescent organism" (no overlap
    ///     with any memory text)
    ///   - m_semantic text = "cookie recipe chocolate" — completely different
    ///     words, but we MANUALLY store the same vector as the query embedding.
    ///   - m_decoy text = "git rebase squash commits" — different text,
    ///     orthogonal vector.
    ///
    /// The "oracle" embedder always returns [1,0,0,0,0,0,0,0] for any text.
    /// We store [1,0,0,0,0,0,0,0] for m_semantic and [0,1,0,0,0,0,0,0] for
    /// m_decoy. Cosine("oracle query", m_semantic) = 1.0; cosine(query,
    /// m_decoy) = 0.0. FTS finds nothing (no shared tokens). ANN finds
    /// m_semantic as the nearest neighbour.
    #[cfg(feature = "embeddings")]
    #[test]
    fn ann_finds_semantic_match_fts_misses() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        // Oracle embedder: always returns the same unit vector regardless of text.
        // This lets us control cosine similarity independently of word overlap.
        struct OracleEmbedder;
        impl embeddings::Embedder for OracleEmbedder {
            fn embed(&self, _text: &str) -> Result<Vec<f32>, embeddings::EmbedderError> {
                // [1,0,0,0,0,0,0,0] — unit vector along dim-0
                Ok(vec![1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
            }
            fn model_id(&self) -> &str {
                "oracle-d8"
            }
            fn dim(&self) -> usize {
                8
            }
        }

        let model_id = "oracle-d8";

        // m_semantic: text shares NO tokens with the query, but stored
        // embedding is [1,0,...,0] — cosine with the oracle query vector = 1.0.
        let sem_vec = embeddings::encode_embedding(&[1.0f32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
        let sem_text = "cookie recipe chocolate";
        let sem_norm = kimetsu_core::memory::normalize_memory_text(sem_text);
        conn.execute(
            "INSERT INTO memories (
                 memory_id, scope, kind, text, normalized_text, confidence,
                 source_event_id, provenance_snapshot_json, created_at,
                 use_count, usefulness_score, embedding, embedding_model
             )
             VALUES ('m_semantic', 'global_user', 'fact', ?1, ?2, 1.0, NULL, '{}',
                     '2026-01-01T00:00:00Z', 0, 0.0, ?3, ?4)",
            rusqlite::params![sem_text, sem_norm, sem_vec, model_id],
        )
        .expect("insert m_semantic");
        conn.execute(
            "INSERT INTO memories_fts (memory_id, text, kind, scope)
             VALUES ('m_semantic', ?1, 'fact', 'global_user')",
            rusqlite::params![sem_text],
        )
        .expect("insert m_semantic fts");

        // m_decoy: different text, orthogonal vector [0,1,0,...,0].
        let decoy_vec = embeddings::encode_embedding(&[0.0f32, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
        let decoy_text = "git rebase squash commits";
        let decoy_norm = kimetsu_core::memory::normalize_memory_text(decoy_text);
        conn.execute(
            "INSERT INTO memories (
                 memory_id, scope, kind, text, normalized_text, confidence,
                 source_event_id, provenance_snapshot_json, created_at,
                 use_count, usefulness_score, embedding, embedding_model
             )
             VALUES ('m_decoy', 'global_user', 'fact', ?1, ?2, 1.0, NULL, '{}',
                     '2026-01-01T00:00:00Z', 0, 0.0, ?3, ?4)",
            rusqlite::params![decoy_text, decoy_norm, decoy_vec, model_id],
        )
        .expect("insert m_decoy");
        conn.execute(
            "INSERT INTO memories_fts (memory_id, text, kind, scope)
             VALUES ('m_decoy', ?1, 'fact', 'global_user')",
            rusqlite::params![decoy_text],
        )
        .expect("insert m_decoy fts");

        // Sanity: FTS must find nothing for the query tokens.
        let fts_hits: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM memories_fts \
                 WHERE memories_fts MATCH 'phosphorescent bioluminescent'",
                [],
                |r| r.get(0),
            )
            .unwrap_or(0);
        assert_eq!(
            fts_hits, 0,
            "sanity: query tokens must not appear in any memory text"
        );

        // Retrieve via oracle embedder.
        // query = "phosphorescent bioluminescent organism" has no lexical
        // overlap with either memory. ANN must surface m_semantic (cosine=1).
        let weights = kimetsu_core::config::BrokerWeights::default();
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "phosphorescent bioluminescent organism".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &OracleEmbedder,
        )
        .expect("retrieve");

        let handles: Vec<&str> = bundle
            .capsules
            .iter()
            .filter_map(|c| c.expansion_handle.strip_prefix("memory:"))
            .collect();

        assert!(
            handles.contains(&"m_semantic"),
            "ANN must surface m_semantic (cosine=1 with oracle query) even though \
             FTS found nothing; got handles: {handles:?}"
        );
    }

    /// D1d test 3: a memory matched by both FTS and ANN appears exactly once.
    #[cfg(feature = "embeddings")]
    #[test]
    fn dedup_memory_matched_by_fts_and_ann_appears_once() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        let stub = embeddings::StubEmbedder::new();

        // This memory contains "ripgrep" (lexical) AND has a stub embedding
        // derived from its text, so the query "ripgrep" matches it both via
        // FTS and via ANN (same words → same stub bucket vector).
        insert_memory_with_embedding(&conn, "m_both", "use ripgrep for fast search", &stub);

        let weights = kimetsu_core::config::BrokerWeights::default();
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "ripgrep".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &stub,
        )
        .expect("retrieve");

        let count = bundle
            .capsules
            .iter()
            .filter(|c| c.expansion_handle == "memory:m_both")
            .count();
        assert_eq!(
            count,
            1,
            "m_both (matched by both FTS and ANN) must appear exactly once; \
             bundle: {:?}",
            bundle
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );
    }

    // ---------------------------------------------------------------
    // D1e tests: embedding-MMR deduplication + semantic relevance floor
    // ---------------------------------------------------------------

    /// D1e-a (embeddings-gated): two paraphrased memories that share an
    /// almost-identical embedding vector (cosine = 1.0, so embedding-MMR
    /// sees them as maximally redundant) but have LOW Jaccard overlap on
    /// their summary tokens (different words, so the Jaccard-only capsule-
    /// stage MMR would NOT penalize the second one and both survive the
    /// budget with max_capsules=2).
    ///
    /// Key mechanic: embedding-MMR assigns the second near-duplicate a very
    /// negative MMR score (lambda * score - (1-lambda) * 1.0 < 0 when score
    /// is small). It therefore ends up LAST in the reordered candidate list.
    /// When max_capsules=1 it is excluded. With Jaccard-only (NoopEmbedder),
    /// the second paraphrase has low Jaccard overlap → survives when
    /// max_capsules=2.
    ///
    /// Expected result:
    ///   * OracleEmbedder + max_capsules=1: ONE paraphrase (embedding-MMR
    ///     collapsed the redundant one).
    ///   * NoopEmbedder + max_capsules=2: BOTH paraphrases survive (Jaccard
    ///     does not see them as redundant — different tokens).
    #[cfg(feature = "embeddings")]
    #[test]
    fn embedding_mmr_collapses_paraphrases_but_jaccard_does_not() {
        // OracleEmbedder: always returns [1,0,0,…] (dim=8).
        // cosine(any two texts) = 1.0 → maximal redundancy in embedding space.
        struct OracleEmbedder;
        impl embeddings::Embedder for OracleEmbedder {
            fn embed(&self, _text: &str) -> Result<Vec<f32>, embeddings::EmbedderError> {
                let mut v = vec![0.0f32; 8];
                v[0] = 1.0;
                Ok(v)
            }
            fn model_id(&self) -> &str {
                "oracle-d8"
            }
            fn dim(&self) -> usize {
                8
            }
        }

        // Setup: two memories with DIFFERENT words (low Jaccard) but
        // SAME oracle embedding (cosine = 1.0).
        let oracle = OracleEmbedder;
        let weights = kimetsu_core::config::BrokerWeights::default();

        // "prefer ripgrep" vs "rg is the fastest" — entirely different tokens.
        // Summary token-set overlap ≈ 0 ⟹ Jaccard ≈ 0.
        let m_rg1_text = "prefer ripgrep for searching source code";
        let m_rg2_text = "rg is the fastest way to locate patterns";

        // --- Embedding-MMR path (OracleEmbedder), max_capsules=1 ---
        // Under embedding-MMR: second paraphrase gets MMR score
        //   0.7 * score - 0.3 * 1.0  (overlap = cosine = 1.0)
        // For any small normalised score, this is negative → it is assigned
        // last in the MMR reordering. max_capsules=1 → only 1 included.
        let conn = rusqlite::Connection::open_in_memory().expect("in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        insert_memory_with_embedding(&conn, "m_rg1", m_rg1_text, &oracle);
        insert_memory_with_embedding(&conn, "m_rg2", m_rg2_text, &oracle);

        let bundle_embedding = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                // Query that matches both via FTS so they survive pre-MMR scoring.
                query: "search source patterns".to_string(),
                budget_tokens: 20_000,
                max_capsules: 1, // tight cap: only 1 slot available
                ..Default::default()
            },
            &[],
            &oracle,
        )
        .expect("retrieve with oracle embedder");

        // Under embedding-MMR, the second paraphrase (cosine=1.0 with first)
        // is reranked last and excluded by max_capsules=1.
        let emb_in_capsules = bundle_embedding
            .capsules
            .iter()
            .filter(|c| {
                c.expansion_handle == "memory:m_rg1" || c.expansion_handle == "memory:m_rg2"
            })
            .count();
        assert_eq!(
            emb_in_capsules,
            1,
            "embedding-MMR must collapse cosine=1.0 paraphrases: with max_capsules=1 \
             only ONE should be included; capsule handles: {:?}; excluded: {:?}",
            bundle_embedding
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>(),
            bundle_embedding
                .excluded
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );

        // At least one is in excluded (the redundant near-duplicate).
        let emb_in_excluded = bundle_embedding
            .excluded
            .iter()
            .filter(|c| {
                c.expansion_handle == "memory:m_rg1" || c.expansion_handle == "memory:m_rg2"
            })
            .count();
        assert_eq!(
            emb_in_excluded,
            1,
            "the second near-duplicate must be in excluded under embedding-MMR; \
             excluded handles: {:?}",
            bundle_embedding
                .excluded
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );

        // --- Lean/Jaccard-only path (NoopEmbedder), max_capsules=2 ---
        // With Jaccard-only: summary tokens of m_rg1 and m_rg2 have ≈0
        // overlap (different words) → low redundancy penalty → BOTH score
        // high under MMR → both survive with max_capsules=2.
        let conn2 = rusqlite::Connection::open_in_memory().expect("in-memory 2");
        crate::schema::initialize(&conn2).expect("init schema 2");
        insert_memory_with_embedding(&conn2, "m_rg1", m_rg1_text, &oracle);
        insert_memory_with_embedding(&conn2, "m_rg2", m_rg2_text, &oracle);

        let bundle_lean = retrieve_context_with_embedder(
            &conn2,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "search source patterns".to_string(),
                budget_tokens: 20_000,
                max_capsules: 2, // room for both
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve with NoopEmbedder");

        let lean_in_capsules = bundle_lean
            .capsules
            .iter()
            .filter(|c| {
                c.expansion_handle == "memory:m_rg1" || c.expansion_handle == "memory:m_rg2"
            })
            .count();
        assert_eq!(
            lean_in_capsules,
            2,
            "Jaccard-only path must NOT collapse the two paraphrases (different words, \
             low token overlap → both survive MMR with max_capsules=2); capsule handles: {:?}",
            bundle_lean
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );
    }

    // ── v1.0.0: lexical relevance floor (A+B+C) ──────────────────────────

    #[test]
    fn content_tokens_strips_stopwords_keeps_topical_words() {
        let got = content_tokens("Tell me about kimetsu, what's the idea of the repo");
        // Stopwords (tell, me, about, what, the, of) dropped; "s" too short.
        // Topical words kept; deduped (no second "the").
        assert_eq!(got, vec!["kimetsu", "idea", "repo"]);
    }

    #[test]
    fn light_stem_strips_one_inflection_suffix() {
        assert_eq!(light_stem("benchmarked"), "benchmark");
        assert_eq!(light_stem("benchmarking"), "benchmark");
        assert_eq!(light_stem("repos"), "repo");
        // Too short after stripping → untouched.
        assert_eq!(light_stem("does"), "does");
        assert_eq!(light_stem("toml"), "toml");
    }

    /// Real-world regression: "Can you find out how kimetsu is benchmarked?"
    /// surfaced off-topic memories because the inflected "benchmarked"
    /// matched nothing (FTS prefix `benchmarked*` and IDF `%benchmarked%`
    /// both miss "benchmark"), zeroing the query's only discriminating
    /// token. With query-side stemming the benchmark memory surfaces and
    /// the off-topic ones stay below the floor.
    #[test]
    fn stemmed_query_matches_inflected_corpus_through_floor() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let insert = |id: &str, text: &str| {
            let norm = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score, embedding, embedding_model
                 )
                 VALUES (?1, 'global_user', 'fact', ?2, ?3, 0.9, NULL, '{}',
                         '2026-06-01T00:00:00Z', 0, 0.0, NULL, NULL)",
                rusqlite::params![id, text, norm],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'fact', 'global_user')",
                rusqlite::params![id, text],
            )
            .expect("insert fts");
        };
        insert(
            "m_bench",
            "kimetsu benchmark runs go through the kbench binary and the Terminal-Bench driver",
        );
        insert(
            "m_doctor",
            "kimetsu doctor version-skew check parses process start times on Windows via CIM",
        );
        insert(
            "m_gc",
            "kimetsu runs auto-GC on run creation; keep the env guard at the trigger site",
        );

        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &kimetsu_core::config::BrokerWeights::default(),
            ContextRequest {
                stage: "localization".to_string(),
                query: "Can you find out how kimetsu is benchmarked?".to_string(),
                budget_tokens: 2000,
                max_capsules: 2,
                min_lexical_coverage: 0.5,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve");
        let handles: Vec<_> = bundle
            .capsules
            .iter()
            .map(|c| c.expansion_handle.as_str())
            .collect();
        assert!(
            handles.contains(&"memory:m_bench"),
            "stemmed 'benchmarked' must surface the benchmark memory; got {handles:?}"
        );
        assert!(
            !handles.contains(&"memory:m_doctor") && !handles.contains(&"memory:m_gc"),
            "off-topic memories sharing only 'kimetsu' must stay below the floor; got {handles:?}"
        );
    }

    #[test]
    fn weighted_coverage_ignores_zero_idf_tokens() {
        // "kimetsu" is corpus-ubiquitous (idf 0); "idea" is rare (high idf);
        // "repo" is mid. A summary that matches only the project name + a
        // mid-idf word covers a minority of the discriminating weight.
        let content = vec![
            "kimetsu".to_string(),
            "idea".to_string(),
            "repo".to_string(),
        ];
        let mut idf = HashMap::new();
        idf.insert("kimetsu".to_string(), 0.0);
        idf.insert("idea".to_string(), 1.386);
        idf.insert("repo".to_string(), 0.693);

        // Matches kimetsu + repo, NOT idea → 0.693 / (1.386+0.693) ≈ 0.333.
        let cov = weighted_coverage(
            &content,
            &idf,
            "global:fact - the git repo and kimetsu brain",
        );
        assert!((cov - 0.333).abs() < 0.01, "got {cov}");

        // Matches the rare topical word → high coverage.
        let cov_topical =
            weighted_coverage(&content, &idf, "global:fact - the core idea of kimetsu");
        assert!(cov_topical > 0.6, "got {cov_topical}");
    }

    /// The reported regression, reproduced end-to-end on the FTS-only path:
    /// a corpus of unrelated debugging war-stories that all happen to contain
    /// the project name "kimetsu", queried with a broad conceptual prompt.
    ///
    /// * floor disabled (min_lexical_coverage = 0.0) → all the noise surfaces
    ///   (pre-fix behaviour: incidental "kimetsu" overlap is enough).
    /// * floor enabled (0.5) → the memories whose ONLY match is the corpus-
    ///   ubiquitous project name (m2, m3) are dropped. m1 also contains the
    ///   real word "repo", so it's a genuine (if weak) lexical match and
    ///   survives — eliminating that kind of keyword-overlap-but-off-topic
    ///   hit needs the semantic path, not lexical filtering. The win here is
    ///   killing the pure-project-name matches, which were the bulk of the
    ///   injected noise.
    #[test]
    fn lexical_floor_drops_offtopic_memories_sharing_project_name() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        let insert = |id: &str, text: &str| {
            let norm = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score, embedding, embedding_model
                 )
                 VALUES (?1, 'global_user', 'fact', ?2, ?3, 0.9, NULL, '{}',
                         '2026-06-01T00:00:00Z', 0, 0.0, NULL, NULL)",
                rusqlite::params![id, text, norm],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'fact', 'global_user')",
                rusqlite::params![id, text],
            )
            .expect("insert fts");
        };

        // All three contain "kimetsu"; none contain "idea". Only m1 contains
        // "repo" (as in "git repo") — mirrors the real war-stories.
        insert(
            "m1",
            "When implementing a setup command that calls init_project, tests must call \
             git_init_boundary before setup_cmd so ProjectPaths discover resolves to the temp \
             dir instead of climbing to the real parent git repo including the user brain at kimetsu",
        );
        insert(
            "m2",
            "A member crate with default embeddings silently turned embeddings on for the entire \
             cargo test workspace build graph because cargo unifies features; kimetsu-chat \
             retrieval tests failed",
        );
        insert(
            "m3",
            "In toml 0.9 use toml from_str to parse a TOML document into a Value not str parse; \
             implementing config get and set in kimetsu-cli",
        );

        let query = "Tell me about kimetsu, what's the idea of the repo".to_string();
        let weights = kimetsu_core::config::BrokerWeights::default();
        let handles = |bundle: &ContextBundle| {
            bundle
                .capsules
                .iter()
                .map(|c| c.expansion_handle.clone())
                .collect::<Vec<_>>()
        };

        // Floor disabled: every off-topic memory surfaces (pre-fix behaviour).
        let no_floor = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: query.clone(),
                budget_tokens: 2000,
                max_capsules: 8,
                min_lexical_coverage: 0.0,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve without floor");
        let before = handles(&no_floor);
        assert!(
            before.contains(&"memory:m2".to_string()) && before.contains(&"memory:m3".to_string()),
            "sanity: without the floor the pure-project-name memories should surface; got {before:?}"
        );

        // Floor enabled: the pure-project-name matches (m2, m3) are dropped.
        let floored = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query,
                budget_tokens: 2000,
                max_capsules: 8,
                min_lexical_coverage: 0.5,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve with floor");
        let after = handles(&floored);
        assert!(
            !after.contains(&"memory:m2".to_string()) && !after.contains(&"memory:m3".to_string()),
            "the lexical floor must drop memories whose only match is the corpus-ubiquitous \
             project name; surviving: {after:?}"
        );
    }

    /// A genuinely on-topic query must NOT be over-pruned: a memory that
    /// covers the query's rare, discriminating word survives the floor.
    #[test]
    fn lexical_floor_keeps_ontopic_memory() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        let insert = |id: &str, text: &str| {
            let norm = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score, embedding, embedding_model
                 )
                 VALUES (?1, 'global_user', 'fact', ?2, ?3, 0.9, NULL, '{}',
                         '2026-06-01T00:00:00Z', 0, 0.0, NULL, NULL)",
                rusqlite::params![id, text, norm],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'fact', 'global_user')",
                rusqlite::params![id, text],
            )
            .expect("insert fts");
        };

        // Two memories so "distiller" is rare (df=1) → high idf.
        insert(
            "d1",
            "The distiller runs at session end and harvests durable lessons from the transcript",
        );
        insert(
            "n1",
            "Unrelated note about git rebase and squashing commits",
        );

        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &kimetsu_core::config::BrokerWeights::default(),
            ContextRequest {
                stage: "localization".to_string(),
                query: "how does the distiller work".to_string(),
                budget_tokens: 2000,
                min_lexical_coverage: 0.5,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve");

        assert!(
            bundle
                .capsules
                .iter()
                .any(|c| c.expansion_handle == "memory:d1"),
            "on-topic memory covering the rare query word must survive the floor; got: {:?}",
            bundle
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );
    }

    /// D1e-b: absolute semantic relevance floor (min_semantic_score).
    ///
    /// * With a positive floor and a query whose embedding is orthogonal
    ///   to every memory, the result must be `skipped: true` / 0 capsules.
    /// * With the same floor and a query that IS relevant, the memory
    ///   still surfaces (signal preserved).
    /// * With floor = 0.0 (default), the off-topic query still surfaces
    ///   the "best of a bad lot" (existing pre-D1e behaviour).
    #[cfg(feature = "embeddings")]
    #[test]
    fn min_semantic_score_floor_drops_off_topic_queries() {
        // DirectionalEmbedder: returns a specific unit vector based on
        // which "topic" the text is assigned to. Allows us to place the
        // query vector and memory vectors in known relative positions.
        //
        // dim=8. Topic A = [1,0,0,0,0,0,0,0]. Topic B = [0,1,0,0,0,0,0,0].
        // cosine(A, B) = 0.0 → perfectly orthogonal (unrelated).
        // cosine(A, A) = 1.0 → identical topic.
        //
        // We embed the query on topic A, the memory on topic B.
        // Cosine(query, memory) = 0.0 < any positive floor.
        struct DirectionalEmbedder {
            // Text containing "TOPIC_A" embeds as [1,0,…]; all others as [0,1,…].
            marker: &'static str,
        }
        impl embeddings::Embedder for DirectionalEmbedder {
            fn embed(&self, text: &str) -> Result<Vec<f32>, embeddings::EmbedderError> {
                let mut v = vec![0.0f32; 8];
                if text.contains(self.marker) {
                    v[0] = 1.0;
                } else {
                    v[1] = 1.0;
                }
                Ok(v)
            }
            fn model_id(&self) -> &str {
                "directional-d8"
            }
            fn dim(&self) -> usize {
                8
            }
        }

        let emb = DirectionalEmbedder { marker: "TOPIC_A" };

        let conn = rusqlite::Connection::open_in_memory().expect("in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        // Memory is on topic B (does NOT contain "TOPIC_A").
        insert_memory_with_embedding(&conn, "m_b", "cookie recipe chocolate baking TOPIC_B", &emb);

        let weights = kimetsu_core::config::BrokerWeights::default();

        // 1. Off-topic query (TOPIC_A) with a positive floor: must be skipped.
        let bundle_off = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                // Query is on TOPIC_A (cosine with memory = 0.0).
                query: "TOPIC_A unrelated phosphorescent".to_string(),
                budget_tokens: 4000,
                min_semantic_score: 0.1, // positive floor
                ..Default::default()
            },
            &[],
            &emb,
        )
        .expect("retrieve off-topic");

        assert!(
            bundle_off.capsules.is_empty(),
            "off-topic query (cosine=0 < floor=0.1) must produce zero capsules; \
             got: {:?}",
            bundle_off
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );

        // 2. On-topic query (TOPIC_B): cosine = 1.0 ≥ floor → surfaces.
        // Insert a memory explicitly on topic B that FTS can also match.
        let conn2 = rusqlite::Connection::open_in_memory().expect("in-memory 2");
        crate::schema::initialize(&conn2).expect("init schema 2");
        insert_memory_with_embedding(
            &conn2,
            "m_b2",
            "cookie recipe chocolate TOPIC_B baking"
                .to_string()
                .as_str(),
            &emb,
        );

        let bundle_on = retrieve_context_with_embedder(
            &conn2,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                // Query is on TOPIC_B: cosine with m_b2 = 1.0 ≥ floor.
                query: "cookie chocolate TOPIC_B".to_string(),
                budget_tokens: 4000,
                min_semantic_score: 0.1,
                ..Default::default()
            },
            &[],
            &emb,
        )
        .expect("retrieve on-topic");

        assert!(
            bundle_on
                .capsules
                .iter()
                .any(|c| c.expansion_handle == "memory:m_b2"),
            "on-topic query (cosine=1.0 ≥ floor) must surface m_b2; \
             got capsules: {:?}",
            bundle_on
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );

        // 3. Off-topic query with floor=0.0 (disabled): memory still surfaces
        //    (existing pre-D1e behaviour — floor is a no-op at 0.0).
        let conn3 = rusqlite::Connection::open_in_memory().expect("in-memory 3");
        crate::schema::initialize(&conn3).expect("init schema 3");
        insert_memory_with_embedding(
            &conn3,
            "m_b3",
            "cookie chocolate TOPIC_B recipe".to_string().as_str(),
            &emb,
        );

        let bundle_noop_floor = retrieve_context_with_embedder(
            &conn3,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                // FTS: "cookie chocolate" matches m_b3.
                query: "cookie chocolate TOPIC_A".to_string(),
                budget_tokens: 4000,
                min_semantic_score: 0.0, // disabled
                ..Default::default()
            },
            &[],
            &emb,
        )
        .expect("retrieve noop floor");

        // With floor disabled, FTS match is enough — memory surfaces.
        assert!(
            bundle_noop_floor
                .capsules
                .iter()
                .any(|c| c.expansion_handle == "memory:m_b3"),
            "with floor=0.0 (disabled), off-topic-cosine memory must still surface via FTS; \
             got: {:?}",
            bundle_noop_floor
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );
    }

    // ---------------------------------------------------------------
    // D1f test: token-economy reduction proof
    // ---------------------------------------------------------------

    /// D1f: Prove that embedding-MMR + semantic floor reduces token usage
    /// while preserving signal.
    ///
    /// Setup: a corpus of 6 memories:
    ///   * 3 near-duplicate paraphrases on topic A (same OracleA vector)
    ///   * 1 genuinely relevant memory on topic A (same OracleA vector,
    ///     different words)
    ///   * 2 completely unrelated memories on topic B (OracleB vector)
    ///
    /// Query: topic A.
    ///
    /// WITHOUT D1e (NoopEmbedder + floor=0.0): all 6 memories potentially
    /// surface (no semantic dedup, no floor). With the budget large enough
    /// all 6 fit → many capsules, many tokens.
    ///
    /// WITH D1e (OracleEmbedder + positive floor):
    ///   * Floor (min_semantic_score > 0) drops the 2 topic-B memories.
    ///   * Embedding-MMR collapses the 3 near-duplicate topic-A memories
    ///     to 1 slot.
    ///   * The genuinely-relevant memory survives (it is the "seed" of MMR
    ///     or at least one slot per topic-A cluster remains).
    ///
    /// Assertion: WITH D1e → strictly fewer capsules AND the genuinely-
    /// relevant memory is still present (signal preserved, noise cut).
    #[cfg(feature = "embeddings")]
    #[test]
    fn d1f_token_economy_fewer_capsules_signal_preserved() {
        // OracleEmbedder: topic-A text gets [1,0,…]; everything else [0,1,…].
        struct OracleTopicEmbedder;
        impl embeddings::Embedder for OracleTopicEmbedder {
            fn embed(&self, text: &str) -> Result<Vec<f32>, embeddings::EmbedderError> {
                let mut v = vec![0.0f32; 8];
                if text.contains("TOPIC_A") {
                    v[0] = 1.0; // topic A
                } else {
                    v[1] = 1.0; // topic B
                }
                Ok(v)
            }
            fn model_id(&self) -> &str {
                "oracle-topic-d8"
            }
            fn dim(&self) -> usize {
                8
            }
        }

        let oracle = OracleTopicEmbedder;

        // Helper: set up the corpus on a fresh connection.
        let setup = |conn: &rusqlite::Connection| {
            // 3 near-duplicate paraphrases on topic A (same oracle vector,
            // different FTS words so they match the query but Jaccard is low).
            for (mid, text) in [
                ("m_dup1", "TOPIC_A prefer ripgrep for searching"),
                ("m_dup2", "TOPIC_A rg is the fastest searcher"),
                ("m_dup3", "TOPIC_A use rg tool to find patterns"),
                // 1 genuinely-relevant memory on topic A (the one we must keep).
                (
                    "m_relevant",
                    "TOPIC_A critical lesson about search performance",
                ),
                // 2 off-topic memories on topic B.
                ("m_noise1", "chocolate cookie baking TOPIC_B recipe"),
                ("m_noise2", "gardening tulip planting TOPIC_B spring"),
            ] {
                insert_memory_with_embedding(conn, mid, text, &oracle);
            }
        };

        let weights = kimetsu_core::config::BrokerWeights::default();

        // --- WITHOUT D1e: NoopEmbedder, floor=0.0 ---
        // FTS: "TOPIC_A" appears in m_dup1/2/3 + m_relevant; "search"
        // appears in m_dup1 and m_relevant. All 4 topic-A memories match
        // FTS. The 2 topic-B memories also have "recipe" and "spring"
        // which don't match — they may or may not appear via recency
        // fallback. Use a large budget so all matching memories fit.
        let conn_lean = rusqlite::Connection::open_in_memory().expect("in-memory lean");
        crate::schema::initialize(&conn_lean).expect("init schema lean");
        setup(&conn_lean);

        let bundle_lean = retrieve_context_with_embedder(
            &conn_lean,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "TOPIC_A search performance".to_string(),
                budget_tokens: 20_000,
                min_semantic_score: 0.0, // floor disabled
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve lean");

        let lean_count = bundle_lean
            .capsules
            .iter()
            .filter(|c| c.expansion_handle.starts_with("memory:"))
            .count();

        // --- WITH D1e: OracleEmbedder + positive floor ---
        let conn_emb = rusqlite::Connection::open_in_memory().expect("in-memory emb");
        crate::schema::initialize(&conn_emb).expect("init schema emb");
        setup(&conn_emb);

        let bundle_emb = retrieve_context_with_embedder(
            &conn_emb,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "TOPIC_A search performance".to_string(),
                budget_tokens: 20_000,
                min_semantic_score: 0.5, // positive floor: drops topic-B (cosine=0.0)
                ..Default::default()
            },
            &[],
            &oracle,
        )
        .expect("retrieve with embeddings");

        let emb_count = bundle_emb
            .capsules
            .iter()
            .filter(|c| c.expansion_handle.starts_with("memory:"))
            .count();

        // Token reduction: embedding path must produce strictly fewer capsules.
        assert!(
            emb_count < lean_count,
            "D1e must reduce capsule count: embedding path {emb_count} must be \
             < lean path {lean_count}. Embedding capsules: {:?}",
            bundle_emb
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );

        // Signal preservation: the genuinely-relevant memory must survive.
        assert!(
            bundle_emb
                .capsules
                .iter()
                .any(|c| c.expansion_handle == "memory:m_relevant"),
            "m_relevant must survive D1e selection (signal preserved); \
             embedding capsules: {:?}",
            bundle_emb
                .capsules
                .iter()
                .map(|c| &c.expansion_handle)
                .collect::<Vec<_>>()
        );

        // Token estimate: embedding path must use fewer or equal token budget.
        let lean_tokens: u32 = bundle_lean.capsules.iter().map(|c| c.token_estimate).sum();
        let emb_tokens: u32 = bundle_emb.capsules.iter().map(|c| c.token_estimate).sum();
        assert!(
            emb_tokens < lean_tokens,
            "D1e must reduce token usage: emb={emb_tokens} must be < lean={lean_tokens}"
        );
    }

    /// D1d test 4: lean-unchanged guarantee.
    ///
    /// With NoopEmbedder (query_embedding == None), memory_candidates
    /// takes the FTS-then-recency path exactly as before D1c. No vec
    /// table is touched; no panic occurs.
    #[test]
    fn lean_noop_embedder_uses_fts_then_recency_unchanged() {
        // The NoopEmbedder logic path never touches the ANN index — it must
        // work purely via FTS + recency on both lean and embeddings builds.
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        // Insert two plain memories (no embeddings).
        for (mid, text) in [
            ("m_x", "use git rebase to clean history"),
            ("m_y", "grep finds text quickly"),
        ] {
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score
                 )
                 VALUES (?1, 'global_user', 'fact', ?2, ?3, 1.0, NULL, '{}',
                         '2026-01-01T00:00:00Z', 0, 0.0)",
                rusqlite::params![mid, text, normalized],
            )
            .expect("insert");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope) VALUES (?1, ?2, 'fact', 'global_user')",
                rusqlite::params![mid, text],
            )
            .expect("insert fts");
        }

        let weights = kimetsu_core::config::BrokerWeights::default();
        // NoopEmbedder → query_embedding = None → FTS + recency path.
        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: "grep text".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve with NoopEmbedder must not panic");

        // m_y matches "grep text" lexically via FTS. m_x does not.
        let handles: Vec<&str> = bundle
            .capsules
            .iter()
            .filter_map(|c| c.expansion_handle.strip_prefix("memory:"))
            .collect();
        assert!(
            handles.contains(&"m_y"),
            "m_y must surface via FTS on lean path; got {handles:?}"
        );
        // Crucially: no panic, no ANN index access.
    }

    // ---------------------------------------------------------------
    // E3 tests: task-kind classification + adaptive retrieval routing
    // ---------------------------------------------------------------

    /// E3-1: classify_task is deterministic for each kind.
    #[test]
    fn classify_task_maps_each_kind_deterministically() {
        // Debug examples
        assert_eq!(
            classify_task("fix the panic in the parser"),
            TaskKind::Debug,
            "contains 'fix' and 'panic'"
        );
        assert_eq!(
            classify_task("there is a crash in auth when calling login"),
            TaskKind::Debug,
            "contains 'crash'"
        );
        assert_eq!(
            classify_task("debug the failing test"),
            TaskKind::Debug,
            "contains 'debug' and 'fail'"
        );

        // Investigation examples
        assert_eq!(
            classify_task("investigate why retrieval is slow"),
            TaskKind::Investigation,
            "contains 'investigate' and 'why'"
        );
        assert_eq!(
            classify_task("analyze the root cause of the latency"),
            TaskKind::Investigation,
            "contains 'analyze' and 'root cause'"
        );

        // Refactor examples
        assert_eq!(
            classify_task("refactor the auth module"),
            TaskKind::Refactor,
            "contains 'refactor'"
        );
        assert_eq!(
            classify_task("rename the config struct"),
            TaskKind::Refactor,
            "contains 'rename'"
        );
        assert_eq!(
            classify_task("simplify the retry handling logic"),
            TaskKind::Refactor,
            "contains 'simplify'"
        );

        // Docs examples
        assert_eq!(
            classify_task("document the API endpoints"),
            TaskKind::Docs,
            "contains 'document'"
        );
        assert_eq!(
            classify_task("update the readme with new instructions"),
            TaskKind::Docs,
            "contains 'readme'"
        );
        assert_eq!(
            classify_task("add a docstring to the main function"),
            TaskKind::Docs,
            "contains 'docstring'"
        );

        // Feature examples (default / fallback)
        assert_eq!(
            classify_task("add a dark mode toggle"),
            TaskKind::Feature,
            "no debug/refactor/docs/investigate keyword"
        );
        assert_eq!(
            classify_task("implement the new caching layer"),
            TaskKind::Feature,
            "no debug/refactor/docs/investigate keyword"
        );
        assert_eq!(
            classify_task("build the export pipeline"),
            TaskKind::Feature,
            "no debug/refactor/docs/investigate keyword"
        );
    }

    /// E3-1b: precedence — Debug > Investigation > Refactor > Docs > Feature.
    #[test]
    fn classify_task_respects_precedence_order() {
        // "fix" (Debug) + "refactor" (Refactor) → Debug wins
        assert_eq!(
            classify_task("fix and refactor the login module"),
            TaskKind::Debug,
            "Debug > Refactor"
        );
        // "investigate" (Investigation) + "refactor" (Refactor) → Investigation wins
        assert_eq!(
            classify_task("investigate and refactor the cache layer"),
            TaskKind::Investigation,
            "Investigation > Refactor"
        );
        // "investigate" (Investigation) + "document" (Docs) → Investigation wins
        assert_eq!(
            classify_task("investigate the docs and document the API"),
            TaskKind::Investigation,
            "Investigation > Docs"
        );
        // "refactor" (Refactor) + "docs" (Docs) → Refactor wins
        assert_eq!(
            classify_task("refactor and add docs"),
            TaskKind::Refactor,
            "Refactor > Docs"
        );
        // "fix" (Debug) + "investigate" (Investigation) → Debug wins
        assert_eq!(
            classify_task("fix the bug and investigate the regression"),
            TaskKind::Debug,
            "Debug > Investigation"
        );
    }

    /// E3-2: weight renormalization — weights_for_task_kind(w, Debug) sums
    /// to approximately the same total as the input weights.
    /// v2.6 (2b): build two candidates of different kinds where the memory is
    /// a strong match and the repo_file is a weak one.
    fn two_kinds_one_strong() -> Vec<Candidate> {
        let mk = |kind: &str, raw: f32| Candidate {
            capsule: ContextCapsule {
                id: format!("{kind}-1"),
                kind: kind.to_string(),
                summary: String::new(),
                token_estimate: 0,
                expansion_handle: String::new(),
                provenance: Vec::new(),
                confidence: 0.0,
                freshness: 0.0,
                relevance: 0.0,
                scope_weight: 0.0,
                score: 0.0,
                superseded_hint: false,
                rerank_policy_tier: 0,
                claim_revision: None,
                facts: vec![],
                rerank_usefulness: None,
                rerank_trust: None,
            },
            raw_relevance: raw,
            embedding: None,
            cosine: None,
            created_at: None,
        };
        vec![mk("memory", 0.9), mk("repo_file", 0.1)]
    }

    /// The behaviour 2b exists to describe: per-kind normalization promotes
    /// the best of an irrelevant kind to a perfect relevance.
    #[test]
    fn per_kind_normalization_flatters_the_best_of_a_weak_kind() {
        let mut candidates = two_kinds_one_strong();
        let weights = StageWeights {
            relevance: 1.0,
            confidence: 0.0,
            freshness: 0.0,
            scope: 0.0,
        };
        normalize_and_score(&mut candidates, weights, Normalization::PerKind);
        assert!((candidates[0].capsule.relevance - 1.0).abs() < 1e-6);
        assert!(
            (candidates[1].capsule.relevance - 1.0).abs() < 1e-6,
            "per-kind gives the lone weak repo_file relevance 1.0, got {}",
            candidates[1].capsule.relevance
        );
    }

    /// Global normalization keeps relevance comparable across kinds: the weak
    /// repo_file stays weak because it is measured against the same max.
    #[test]
    fn global_normalization_keeps_relevance_comparable_across_kinds() {
        let mut candidates = two_kinds_one_strong();
        let weights = StageWeights {
            relevance: 1.0,
            confidence: 0.0,
            freshness: 0.0,
            scope: 0.0,
        };
        normalize_and_score(&mut candidates, weights, Normalization::Global);
        assert!((candidates[0].capsule.relevance - 1.0).abs() < 1e-6);
        let weak = candidates[1].capsule.relevance;
        assert!(
            (weak - (0.1 / 0.9)).abs() < 1e-6,
            "global normalizes against the single max, got {weak}"
        );
        assert!(weak < candidates[0].capsule.relevance);
    }

    /// v2.7: candidate builder for the supersession tests — a memory with an
    /// embedding, a creation time, and a pre-set score.
    fn superseding_candidate(
        id: &str,
        embedding: Vec<f32>,
        created_at: &str,
        score: f32,
    ) -> Candidate {
        Candidate {
            capsule: ContextCapsule {
                id: id.to_string(),
                kind: "memory".to_string(),
                summary: id.to_string(),
                token_estimate: 0,
                expansion_handle: format!("memory:{id}"),
                provenance: Vec::new(),
                confidence: 0.0,
                freshness: 0.0,
                relevance: 0.0,
                scope_weight: 0.0,
                score,
                superseded_hint: false,
                rerank_policy_tier: 0,
                claim_revision: None,
                facts: vec![],
                rerank_usefulness: None,
                rerank_trust: None,
            },
            raw_relevance: score,
            embedding: Some(embedding),
            // Query relevance for relaxed, cue-qualified supersession tests.
            cosine: Some(score),
            created_at: Some(created_at.to_string()),
        }
    }

    /// v2.7: near-duplicate pair — the OLDER one is penalized so the newer
    /// statement of the topic outranks it even when citations boosted it.
    #[test]
    fn supersession_penalizes_the_older_near_duplicate() {
        let mut candidates = vec![
            // Old, cited, currently winning (score 0.94 > 0.87).
            superseding_candidate("old", vec![1.0, 0.0], "2026-08-01T10:00:00Z", 0.94),
            superseding_candidate("new", vec![0.99, 0.14], "2026-08-01T10:10:00Z", 0.87),
        ];
        apply_supersession_penalty(&mut candidates);
        let old_score = candidates[0].capsule.score;
        let new_score = candidates[1].capsule.score;
        assert!(
            (old_score - 0.94 * SUPERSESSION_PENALTY).abs() < 1e-6,
            "older twin must carry the penalty, got {old_score}"
        );
        assert!((new_score - 0.87).abs() < 1e-6, "newer twin untouched");
        assert!(
            new_score > old_score,
            "the update must now outrank the incumbent"
        );
    }

    /// Distinct memories (low mutual cosine) must not penalize each other,
    /// and the penalty applies at most once however many newer siblings exist.
    #[test]
    fn supersession_ignores_distinct_memories_and_applies_once() {
        let mut candidates = vec![
            superseding_candidate("old", vec![1.0, 0.0], "2026-08-01T10:00:00Z", 0.90),
            // Orthogonal embedding — different topic entirely.
            superseding_candidate("other", vec![0.0, 1.0], "2026-08-02T10:00:00Z", 0.80),
            // Two newer near-duplicates of `old`.
            superseding_candidate("new1", vec![0.99, 0.14], "2026-08-03T10:00:00Z", 0.70),
            superseding_candidate("new2", vec![0.98, 0.19], "2026-08-04T10:00:00Z", 0.60),
        ];
        apply_supersession_penalty(&mut candidates);
        assert!(
            (candidates[0].capsule.score - 0.90 * SUPERSESSION_PENALTY).abs() < 1e-6,
            "penalty applies exactly once, got {}",
            candidates[0].capsule.score
        );
        assert!(
            (candidates[1].capsule.score - 0.80).abs() < 1e-6,
            "orthogonal memory untouched"
        );
        // new1 is itself older than new2 and near-duplicate of it.
        assert!(
            (candidates[2].capsule.score - 0.70 * SUPERSESSION_PENALTY).abs() < 1e-6,
            "a middle sibling is old relative to a newer one"
        );
        assert!(
            (candidates[3].capsule.score - 0.60).abs() < 1e-6,
            "newest untouched"
        );
    }

    /// Lean builds (no embeddings) and unparseable timestamps are inert.
    #[test]
    fn supersession_is_inert_without_embeddings_or_timestamps() {
        let mut no_embedding = vec![
            Candidate {
                embedding: None,
                ..superseding_candidate("a", vec![], "2026-08-01T10:00:00Z", 0.9)
            },
            Candidate {
                embedding: None,
                ..superseding_candidate("b", vec![], "2026-08-02T10:00:00Z", 0.8)
            },
        ];
        apply_supersession_penalty(&mut no_embedding);
        assert!((no_embedding[0].capsule.score - 0.9).abs() < 1e-6);

        let mut bad_ts = vec![
            superseding_candidate("a", vec![1.0, 0.0], "not-a-date", 0.9),
            superseding_candidate("b", vec![1.0, 0.0], "2026-08-02T10:00:00Z", 0.8),
        ];
        apply_supersession_penalty(&mut bad_ts);
        assert!(
            (bad_ts[0].capsule.score - 0.9).abs() < 1e-6,
            "unparseable ts skipped"
        );
        assert!((bad_ts[1].capsule.score - 0.8).abs() < 1e-6);

        // Identical timestamps: no defensible "older", both untouched.
        let mut same_ts = vec![
            superseding_candidate("a", vec![1.0, 0.0], "2026-08-01T10:00:00Z", 0.9),
            superseding_candidate("b", vec![1.0, 0.0], "2026-08-01T10:00:00Z", 0.8),
        ];
        apply_supersession_penalty(&mut same_ts);
        assert!((same_ts[0].capsule.score - 0.9).abs() < 1e-6);
        assert!((same_ts[1].capsule.score - 0.8).abs() < 1e-6);

        // Sub-second gap: one authoring event (same batch ingest), not a
        // supersession — both untouched even though one is nominally older.
        let mut batch = vec![
            superseding_candidate("a", vec![1.0, 0.0], "2026-08-01T10:00:00.100Z", 0.9),
            superseding_candidate("b", vec![1.0, 0.0], "2026-08-01T10:00:00.900Z", 0.8),
        ];
        apply_supersession_penalty(&mut batch);
        assert!(
            (batch[0].capsule.score - 0.9).abs() < 1e-6,
            "millisecond-apart co-writes must not be penalized"
        );
        assert!((batch[1].capsule.score - 0.8).abs() < 1e-6);

        // A batch-imported correction can establish direction in its text.
        // Timestamp order is deliberately reversed here: the explicit cue,
        // not arbitrary JSONL order, identifies the replacement.
        let mut explicit_update = vec![
            superseding_candidate(
                "the project uses spaces (switched from tabs)",
                vec![1.0, 0.0],
                "2026-08-01T10:00:00.100Z",
                0.9,
            ),
            superseding_candidate(
                "the project uses tabs for indentation",
                // Cosine 0.83: below the ordinary 0.85 floor, above the
                // cue-qualified 0.82 floor.
                vec![0.83, 0.557_8],
                "2026-08-01T10:00:00.900Z",
                0.8,
            ),
        ];
        apply_supersession_penalty(&mut explicit_update);
        assert!((explicit_update[0].capsule.score - 0.9).abs() < 1e-6);
        assert!(
            (explicit_update[1].capsule.score - 0.8 * SUPERSESSION_PENALTY).abs() < 1e-6,
            "the unmarked incumbent must lose to the explicit correction"
        );
        assert!(explicit_update[1].capsule.superseded_hint);

        // Rewritten updates can move far in embedding space while retaining a
        // dense lexical identity. Correction cue + overlap recovers direction.
        let mut rewritten_update = vec![
            superseding_candidate(
                "as of v2 the preferred kimetsu embedder is jina, replacing bge",
                vec![1.0, 0.0],
                "2026-08-01T10:00:00.100Z",
                0.9,
            ),
            superseding_candidate(
                "the recommended kimetsu embedder for retrieval is bge",
                vec![0.71, 0.704_2],
                "2026-08-01T10:00:00.900Z",
                0.8,
            ),
        ];
        apply_supersession_penalty(&mut rewritten_update);
        assert!((rewritten_update[0].capsule.score - 0.9).abs() < 1e-6);
        assert!((rewritten_update[1].capsule.score - 0.8 * SUPERSESSION_PENALTY).abs() < 1e-6);

        // The same pair asked as a historical question favors the incumbent
        // by query cosine, so the relaxed relationship must not penalize it.
        let mut historical_query = vec![
            Candidate {
                cosine: Some(0.70),
                ..superseding_candidate(
                    "as of v2 the preferred kimetsu embedder is jina, replacing bge",
                    vec![1.0, 0.0],
                    "2026-08-01T10:00:00.100Z",
                    0.9,
                )
            },
            Candidate {
                cosine: Some(0.90),
                ..superseding_candidate(
                    "the recommended kimetsu embedder for retrieval is bge",
                    vec![0.71, 0.704_2],
                    "2026-08-01T10:00:00.900Z",
                    0.8,
                )
            },
        ];
        apply_supersession_penalty(&mut historical_query);
        assert!((historical_query[0].capsule.score - 0.9).abs() < 1e-6);
        assert!((historical_query[1].capsule.score - 0.8).abs() < 1e-6);

        // A cue is evidence of direction, not permission to join unrelated
        // topics: below the cue-qualified similarity floor both remain intact.
        let mut too_distant = vec![
            superseding_candidate(
                "the project now uses spaces",
                vec![1.0, 0.0],
                "2026-08-01T10:00:00.100Z",
                0.9,
            ),
            superseding_candidate(
                "database backup retention is seven days",
                vec![0.81, 0.586_4],
                "2026-08-01T10:00:00.900Z",
                0.8,
            ),
        ];
        apply_supersession_penalty(&mut too_distant);
        assert!((too_distant[0].capsule.score - 0.9).abs() < 1e-6);
        assert!((too_distant[1].capsule.score - 0.8).abs() < 1e-6);

        // Two update-like variants are ambiguous and remain untouched.
        let mut ambiguous = vec![
            superseding_candidate(
                "the setting is now cheap_model",
                vec![1.0, 0.0],
                "2026-08-01T10:00:00.100Z",
                0.9,
            ),
            superseding_candidate(
                "as of v2 the setting is cheap_model",
                vec![1.0, 0.0],
                "2026-08-01T10:00:00.900Z",
                0.8,
            ),
        ];
        apply_supersession_penalty(&mut ambiguous);
        assert!((ambiguous[0].capsule.score - 0.9).abs() < 1e-6);
        assert!((ambiguous[1].capsule.score - 0.8).abs() < 1e-6);
    }

    /// An unknown or empty value must not silently change ranking — a typo in
    /// project.toml falls back to the shipped rule.
    #[test]
    fn unknown_normalization_falls_back_to_per_kind() {
        assert_eq!(Normalization::from_config(""), Normalization::PerKind);
        assert_eq!(
            Normalization::from_config("per_kind"),
            Normalization::PerKind
        );
        assert_eq!(
            Normalization::from_config("nonsense"),
            Normalization::PerKind
        );
        assert_eq!(Normalization::from_config("global"), Normalization::Global);
        assert_eq!(
            Normalization::from_config("  GLOBAL "),
            Normalization::Global
        );
    }

    #[test]
    fn weights_for_task_kind_renormalizes_to_unit_sum() {
        let base = StageWeights {
            relevance: 0.50,
            confidence: 0.20,
            freshness: 0.20,
            scope: 0.10,
        };
        let original_sum = base.relevance + base.confidence + base.freshness + base.scope;

        for kind in [
            TaskKind::Debug,
            TaskKind::Refactor,
            TaskKind::Investigation,
            TaskKind::Docs,
        ] {
            let w = weights_for_task_kind(base.clone(), kind);
            let new_sum = w.relevance + w.confidence + w.freshness + w.scope;
            // Renormalized to 1.0; the original_sum is also 1.0 for these weights.
            assert!(
                (new_sum - original_sum).abs() < 1e-4,
                "weights_for_task_kind({kind:?}) sum {new_sum} differs from {original_sum}"
            );
        }
    }

    /// E3-2b: Feature is the neutral kind — weights unchanged.
    #[test]
    fn weights_for_task_kind_feature_is_unchanged() {
        let base = StageWeights {
            relevance: 0.40,
            confidence: 0.30,
            freshness: 0.20,
            scope: 0.10,
        };
        let w = weights_for_task_kind(base.clone(), TaskKind::Feature);
        assert!((w.relevance - base.relevance).abs() < f32::EPSILON);
        assert!((w.confidence - base.confidence).abs() < f32::EPSILON);
        assert!((w.freshness - base.freshness).abs() < f32::EPSILON);
        assert!((w.scope - base.scope).abs() < f32::EPSILON);
    }

    /// E3-2c: Debug biases toward freshness; after renorm, freshness
    /// fraction must be strictly larger than in the base weights.
    #[test]
    fn weights_for_task_kind_debug_up_freshness_fraction() {
        let base = StageWeights {
            relevance: 0.50,
            confidence: 0.20,
            freshness: 0.20,
            scope: 0.10,
        };
        let debug_w = weights_for_task_kind(base.clone(), TaskKind::Debug);
        // Freshness fraction = freshness / sum = freshness (since sum=1 after renorm).
        assert!(
            debug_w.freshness > base.freshness,
            "Debug must increase freshness fraction: {debug_w:?}"
        );
    }

    /// E3-2d: Refactor biases toward scope; after renorm, scope fraction
    /// must be strictly larger than in the base weights.
    #[test]
    fn weights_for_task_kind_refactor_up_scope_fraction() {
        let base = StageWeights {
            relevance: 0.50,
            confidence: 0.20,
            freshness: 0.20,
            scope: 0.10,
        };
        let refactor_w = weights_for_task_kind(base.clone(), TaskKind::Refactor);
        assert!(
            refactor_w.scope > base.scope,
            "Refactor must increase scope fraction: {refactor_w:?}"
        );
    }

    /// E3-3: Feature is truly neutral — retrieval with task_kind=Feature
    /// returns the same capsule set as with the default ContextRequest.
    #[test]
    fn task_kind_feature_is_retrieval_neutral() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        // Insert a few memories so retrieval has something to return.
        // DB columns: scope='project', kind=actual memory kind.
        // Broker formats summary as "{scope}:{kind} - {text}".
        for (mid, db_kind, text) in [
            ("m1", "failure_pattern", "linker not found error in build"),
            ("m2", "convention", "use snake_case for all identifiers"),
            ("m3", "fact", "the cache is invalidated on every deploy"),
        ] {
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score
                 )
                 VALUES (?1, 'project', ?2, ?3, ?4, 1.0, NULL, '{}',
                         '2026-01-01T00:00:00Z', 0, 0.0)",
                rusqlite::params![mid, db_kind, text, normalized],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, ?3, 'project')",
                rusqlite::params![mid, text, db_kind],
            )
            .expect("insert fts");
        }

        let weights = kimetsu_core::config::BrokerWeights::default();
        let query = "cache convention failure".to_string();

        // Baseline: no task_kind set (Default::default() → Feature)
        let baseline = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: query.clone(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("baseline retrieve");

        // Explicit Feature: must be identical to baseline
        let feature = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: query.clone(),
                budget_tokens: 4000,
                task_kind: TaskKind::Feature,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("feature retrieve");

        let baseline_ids: Vec<&str> = baseline
            .capsules
            .iter()
            .map(|c| c.expansion_handle.as_str())
            .collect();
        let feature_ids: Vec<&str> = feature
            .capsules
            .iter()
            .map(|c| c.expansion_handle.as_str())
            .collect();
        assert_eq!(
            baseline_ids, feature_ids,
            "task_kind=Feature must produce identical retrieval to default; \
             baseline={baseline_ids:?} feature={feature_ids:?}"
        );

        let baseline_scores: Vec<f32> = baseline.capsules.iter().map(|c| c.score).collect();
        let feature_scores: Vec<f32> = feature.capsules.iter().map(|c| c.score).collect();
        for (b, f) in baseline_scores.iter().zip(feature_scores.iter()) {
            assert!(
                (b - f).abs() < 1e-5,
                "scores must be identical: baseline={b} feature={f}"
            );
        }
    }

    /// E3-4: headline behavioral proof — Debug routes strictly more
    /// failure_pattern capsules than Docs over the same corpus + query.
    ///
    /// Setup: 4 failure_pattern memories + 4 convention/fact memories
    /// that all share a common topic keyword "auth". We cap at 4 capsules
    /// and compare how many are failure_pattern between Debug and Docs.
    ///
    /// Memory row layout: `scope='project'`, `kind='failure_pattern'` (or
    /// `'convention'`/`'fact'`). The broker formats the capsule summary as
    /// `"{scope}:{kind} - {text}"` so `capsule_matches_kind` can parse it.
    #[test]
    fn debug_surfaces_more_failure_pattern_than_docs() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");

        // Insert 4 failure_pattern memories.
        // DB columns: scope='project', kind='failure_pattern'
        // Broker formats summary as "project:failure_pattern - <text>".
        for (i, text) in [
            "auth token expired causes login failure",
            "auth service crash on null pointer",
            "auth regression after upgrade breaks sessions",
            "auth error when certificate is invalid",
        ]
        .iter()
        .enumerate()
        {
            let mid = format!("mfp{i}");
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score
                 )
                 VALUES (?1, 'project', 'failure_pattern', ?2, ?3, 1.0, NULL, '{}',
                         '2026-01-01T00:00:00Z', 0, 0.0)",
                rusqlite::params![mid, text, normalized],
            )
            .expect("insert failure_pattern");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'failure_pattern', 'project')",
                rusqlite::params![mid, text],
            )
            .expect("insert fts");
        }

        // Insert 4 convention/fact memories — also mention "auth".
        // DB columns: scope='project', kind='convention' or 'fact'.
        for (i, (db_kind, text)) in [
            ("convention", "auth module uses bearer tokens by convention"),
            ("convention", "auth scopes are documented in the API guide"),
            ("fact", "auth service runs on port 8443 in production"),
            ("fact", "auth uses JWT with RS256 signing for all tokens"),
        ]
        .iter()
        .enumerate()
        {
            let mid = format!("mconv{i}");
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "INSERT INTO memories (
                     memory_id, scope, kind, text, normalized_text, confidence,
                     source_event_id, provenance_snapshot_json, created_at,
                     use_count, usefulness_score
                 )
                 VALUES (?1, 'project', ?2, ?3, ?4, 1.0, NULL, '{}',
                         '2026-01-01T00:00:00Z', 0, 0.0)",
                rusqlite::params![mid, db_kind, text, normalized],
            )
            .expect("insert convention/fact");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, ?3, 'project')",
                rusqlite::params![mid, text, db_kind],
            )
            .expect("insert fts");
        }

        let weights = kimetsu_core::config::BrokerWeights::default();
        let query = "auth token failure".to_string();

        // Retrieve with Debug task_kind
        let debug_bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: query.clone(),
                budget_tokens: 4000,
                max_capsules: 4,
                task_kind: TaskKind::Debug,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("debug retrieve");

        // Retrieve with Docs task_kind
        let docs_bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &weights,
            ContextRequest {
                stage: "localization".to_string(),
                query: query.clone(),
                budget_tokens: 4000,
                max_capsules: 4,
                task_kind: TaskKind::Docs,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("docs retrieve");

        // Count failure_pattern capsules in each result.
        // Memory capsules have kind="memory"; the real kind is in the summary prefix.
        let count_failure_pattern = |bundle: &ContextBundle| -> usize {
            bundle
                .capsules
                .iter()
                .filter(|c| capsule_matches_kind(c, "failure_pattern"))
                .count()
        };

        let debug_fp = count_failure_pattern(&debug_bundle);
        let docs_fp = count_failure_pattern(&docs_bundle);

        assert!(
            debug_fp > docs_fp,
            "Debug must surface strictly more failure_pattern capsules than Docs: \
             debug_fp={debug_fp} docs_fp={docs_fp}\n\
             Debug capsules: {:?}\n\
             Docs capsules: {:?}",
            debug_bundle
                .capsules
                .iter()
                .map(|c| format!("{}:{}", c.kind, &c.summary[..c.summary.len().min(60)]))
                .collect::<Vec<_>>(),
            docs_bundle
                .capsules
                .iter()
                .map(|c| format!("{}:{}", c.kind, &c.summary[..c.summary.len().min(60)]))
                .collect::<Vec<_>>(),
        );
    }

    // ── F2: resolve_capsule unit tests ────────────────────────────────────

    fn init_db_with_memory(memory_id: &str, text: &str) -> rusqlite::Connection {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let normalized = kimetsu_core::memory::normalize_memory_text(text);
        conn.execute(
            "INSERT INTO memories (
                 memory_id, scope, kind, text, normalized_text, confidence,
                 source_event_id, provenance_snapshot_json, created_at,
                 use_count, usefulness_score
             )
             VALUES (?1, 'project', 'fact', ?2, ?3, 1.0, NULL, '{}',
                     '2026-01-01T00:00:00Z', 0, 0.0)",
            rusqlite::params![memory_id, text, normalized],
        )
        .expect("insert memory");
        conn
    }

    /// F2-1: memory:<id> resolves to the full memory text.
    #[test]
    fn resolve_capsule_memory_returns_full_text() {
        let conn = init_db_with_memory("test-mem-id", "Use rg over grep for speed");
        let repo_root = std::path::Path::new("/fake-repo");
        let result =
            resolve_capsule(&conn, repo_root, "memory:test-mem-id").expect("should resolve");
        assert_eq!(result, "Use rg over grep for speed");
    }

    /// F2-2: memory:<id> for a non-existent id returns Err.
    #[test]
    fn resolve_capsule_memory_missing_id_returns_err() {
        let conn = init_db_with_memory("real-id", "some text");
        let repo_root = std::path::Path::new("/fake-repo");
        let err = resolve_capsule(&conn, repo_root, "memory:nonexistent-id")
            .expect_err("should error for missing memory");
        assert!(
            err.to_string().contains("no active memory"),
            "error message should mention missing: {err}"
        );
    }

    /// F2-3: file:<path> returns a bounded slice of the file content.
    #[test]
    fn resolve_capsule_file_returns_bounded_content() {
        let dir = make_test_dir("f2_file_resolve");
        let content = "hello from the file\n";
        std::fs::write(dir.join("notes.txt"), content).expect("write");
        let result = resolve_capsule(
            // conn is unused for file: handles; pass an in-memory DB
            &rusqlite::Connection::open_in_memory().expect("open"),
            &dir,
            "file:notes.txt",
        )
        .expect("should resolve file");
        assert!(result.contains("hello from the file"));
        std::fs::remove_dir_all(&dir).ok();
    }

    /// F2-4: file:<path> for a large file is capped at FILE_EXPAND_CAP_BYTES.
    #[test]
    fn resolve_capsule_file_caps_large_file() {
        let dir = make_test_dir("f2_file_cap");
        let big = "A".repeat(FILE_EXPAND_CAP_BYTES * 3);
        std::fs::write(dir.join("big.txt"), &big).expect("write");
        let result = resolve_capsule(
            &rusqlite::Connection::open_in_memory().expect("open"),
            &dir,
            "file:big.txt",
        )
        .expect("should resolve large file");
        assert!(
            result.len() <= FILE_EXPAND_CAP_BYTES + 200,
            "result should be bounded: got {} bytes",
            result.len()
        );
        assert!(
            result.contains("truncated"),
            "truncation marker should be present"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// F2-5: unknown handle format returns Err.
    #[test]
    fn resolve_capsule_unknown_handle_returns_err() {
        let conn = rusqlite::Connection::open_in_memory().expect("open");
        let err = resolve_capsule(&conn, std::path::Path::new("/r"), "blob:abc123")
            .expect_err("should error");
        assert!(
            err.to_string().contains("unrecognised handle"),
            "got: {err}"
        );
    }

    /// F2-6: malformed handle (no colon) returns Err.
    #[test]
    fn resolve_capsule_malformed_handle_returns_err() {
        let conn = rusqlite::Connection::open_in_memory().expect("open");
        let err = resolve_capsule(&conn, std::path::Path::new("/r"), "justnocolon")
            .expect_err("should error");
        assert!(
            err.to_string().contains("unrecognised handle"),
            "got: {err}"
        );
    }

    /// F2-7: run:<id> returns the deferred-error message.
    #[test]
    fn resolve_capsule_run_handle_returns_deferred_err() {
        let conn = rusqlite::Connection::open_in_memory().expect("open");
        let err = resolve_capsule(&conn, std::path::Path::new("/r"), "run:some-run-id")
            .expect_err("run: should be deferred err");
        assert!(err.to_string().contains("not yet supported"), "got: {err}");
    }

    /// F2-8: file:<path> with absolute path is rejected.
    #[test]
    fn resolve_capsule_file_rejects_absolute_path() {
        let conn = rusqlite::Connection::open_in_memory().expect("open");
        let err = resolve_capsule(&conn, std::path::Path::new("/r"), "file:/etc/passwd")
            .expect_err("should reject absolute path");
        assert!(err.to_string().contains("absolute path"), "got: {err}");
    }

    // ── v1.0.0 rerank_capsules tests ─────────────────────────────────────────

    fn make_capsule(summary: &str, score: f32) -> ContextCapsule {
        ContextCapsule {
            id: new_id().to_string(),
            kind: "memory".to_string(),
            summary: summary.to_string(),
            token_estimate: 10,
            expansion_handle: format!("memory:{}", new_id()),
            provenance: vec![],
            confidence: 1.0,
            freshness: 1.0,
            relevance: 1.0,
            scope_weight: 1.0,
            score,
            superseded_hint: false,
            rerank_policy_tier: 0,
            claim_revision: None,
            facts: vec![],
            rerank_usefulness: None,
            rerank_trust: None,
        }
    }

    /// RR-1: capsule whose summary shares more query words ranks first and
    /// the score field is overwritten by the reranker's sigmoid-normalized score.
    #[test]
    fn rerank_capsules_reorders_by_query_overlap() {
        use crate::embeddings::StubReranker;

        // Two capsules: "rust async tokio" shares 3/3 query tokens;
        // "python django" shares 0/3.
        let query = "rust async tokio";
        let high_overlap = make_capsule("rust async tokio runtime", 0.0);
        let low_overlap = make_capsule("python django framework", 0.0);
        // Input order: low-overlap first to verify it gets pushed down.
        let capsules = vec![low_overlap.clone(), high_overlap.clone()];

        let ranked = rerank_capsules(query, capsules, &StubReranker, 0.0, 0);

        assert_eq!(ranked.len(), 2, "both capsules should survive (floor=0)");
        // The high-overlap capsule must rank first.
        assert!(
            ranked[0].summary.contains("rust"),
            "rust capsule must be first, got: {:?}",
            ranked[0].summary
        );
        // Score must be overwritten (was 0.0, now > 0.05 for the high-overlap one).
        assert!(
            ranked[0].score > 0.05,
            "score must be overwritten by reranker: {}",
            ranked[0].score
        );
        // High-overlap must score above low-overlap.
        assert!(
            ranked[0].score > ranked[1].score,
            "high overlap must score higher: {} vs {}",
            ranked[0].score,
            ranked[1].score
        );
    }

    /// RR-2: floor drops a zero-overlap capsule.
    /// StubReranker scores a zero-overlap doc at 0.05.
    /// A floor of 0.3 must drop it.
    #[test]
    fn rerank_capsules_floor_drops_zero_overlap() {
        use crate::embeddings::StubReranker;

        let query = "rust async tokio";
        let high = make_capsule("rust async tokio runtime", 0.0);
        let zero = make_capsule("completely unrelated document xyz", 0.0); // 0-overlap → 0.05

        let capsules = vec![high, zero];
        let ranked = rerank_capsules(query, capsules, &StubReranker, 0.3, 0);

        // The zero-overlap capsule (score 0.05) must be dropped by floor=0.3.
        assert_eq!(ranked.len(), 1, "zero-overlap capsule must be dropped");
        assert!(
            ranked[0].summary.contains("rust"),
            "only rust capsule should survive"
        );
    }

    /// RR-3: cap truncates the result.
    #[test]
    fn rerank_capsules_cap_truncates() {
        use crate::embeddings::StubReranker;

        let query = "alpha beta gamma";
        let capsules = vec![
            make_capsule("alpha beta gamma delta", 0.0),
            make_capsule("alpha beta", 0.0),
            make_capsule("alpha", 0.0),
            make_capsule("unrelated xyz", 0.0),
        ];

        let ranked = rerank_capsules(query, capsules, &StubReranker, 0.0, 2);
        assert_eq!(ranked.len(), 2, "cap=2 must truncate to 2 results");
        // The top-2 should be the higher-overlap ones.
        assert!(
            ranked[0].score >= ranked[1].score,
            "results must be sorted descending"
        );
    }

    #[test]
    fn hardening_usefulness_cannot_dominate_relevance() {
        let neutral = make_capsule("neutral", 0.0);
        let mut useful = make_capsule("useful", 0.0);
        useful.rerank_policy_tier = 1;
        let out = rerank_capsules(
            "q",
            vec![neutral, useful],
            &TwoScoreReranker(0.99, 0.31),
            0.30,
            0,
        );
        assert_eq!(out[0].summary, "neutral");
        assert!(out[1].score <= 0.410001);
    }

    #[test]
    fn hardening_rerank_preserves_decayed_usefulness_and_trust() {
        let neutral = make_capsule("neutral", 0.0);
        let mut stale_useful = make_capsule("stale", 0.0);
        stale_useful.rerank_policy_tier = 1;
        stale_useful.rerank_usefulness = Some(1.0001);
        let out = rerank_capsules(
            "q",
            vec![neutral.clone(), stale_useful],
            &TwoScoreReranker(0.9, 0.85),
            0.0,
            0,
        );
        assert_eq!(out[0].summary, "neutral");
        let mut imported = make_capsule("imported", 0.0);
        imported.rerank_usefulness = Some(1.5);
        imported.rerank_trust = Some(0.5);
        let out = rerank_capsules(
            "q",
            vec![neutral, imported],
            &TwoScoreReranker(0.8, 0.9),
            0.0,
            0,
        );
        assert_eq!(out[0].summary, "neutral");
        assert!((out[1].score - 0.5).abs() < 0.00001);
    }

    #[test]
    fn hardening_freshness_has_thirty_day_half_life() {
        let past = (OffsetDateTime::now_utc() - time::Duration::days(30))
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        assert!((freshness(&past) - 0.5).abs() < 0.0001);
    }

    #[test]
    fn rerank_reapplies_usefulness_but_not_to_superseded_capsules() {
        let neutral = make_capsule("neutral", 0.0);
        let mut useful = make_capsule("useful", 0.0);
        useful.rerank_policy_tier = 1;

        let out = rerank_capsules(
            "q",
            vec![neutral.clone(), useful.clone()],
            &TwoScoreReranker(0.59, 0.50),
            0.0,
            0,
        );
        assert_eq!(out[0].summary, "useful", "usefulness survives reranking");

        useful.superseded_hint = true;
        useful.rerank_policy_tier = 1;
        let out = rerank_capsules(
            "q",
            vec![neutral, useful],
            &TwoScoreReranker(0.59, 0.50),
            0.0,
            0,
        );
        assert_eq!(
            out[0].summary, "neutral",
            "superseded memories must not keep their historic usefulness boost"
        );
        assert!(
            (out[1].score - 0.40).abs() < 1e-6,
            "supersession must be reapplied to the raw rerank score"
        );
    }

    /// RR-4: fail-open — a broken reranker returns Err; input order is preserved.
    #[test]
    fn rerank_capsules_fail_open_preserves_input_order() {
        struct FailingReranker;
        impl crate::embeddings::Reranker for FailingReranker {
            fn rerank(
                &self,
                _query: &str,
                _docs: &[&str],
            ) -> Result<Vec<f32>, crate::embeddings::EmbedderError> {
                Err(crate::embeddings::EmbedderError::EmbedFailed(
                    "simulated failure".into(),
                ))
            }
            fn model_id(&self) -> &str {
                "fail-reranker"
            }
        }

        let query = "anything";
        let c1 = make_capsule("first capsule", 0.9);
        let c2 = make_capsule("second capsule", 0.5);
        let c3 = make_capsule("third capsule", 0.1);
        let capsules = vec![c1.clone(), c2.clone(), c3.clone()];

        let out = rerank_capsules(query, capsules, &FailingReranker, 0.0, 0);

        // On error: input order preserved, all 3 capsules returned.
        assert_eq!(out.len(), 3, "all capsules must be returned on error");
        assert_eq!(out[0].summary, c1.summary, "order must be preserved");
        assert_eq!(out[1].summary, c2.summary, "order must be preserved");
        assert_eq!(out[2].summary, c3.summary, "order must be preserved");
    }

    /// RR-0: empty input → empty output.
    #[test]
    fn rerank_capsules_empty_input_returns_empty() {
        use crate::embeddings::StubReranker;
        let out = rerank_capsules("query", vec![], &StubReranker, 0.0, 0);
        assert!(out.is_empty());
    }

    // ── v2.7: evidence-band arbitration ─────────────────────────────────────

    /// Reranker that returns one fixed score per doc, for band tests.
    struct FixedReranker(f32);
    impl crate::embeddings::Reranker for FixedReranker {
        fn rerank(
            &self,
            _query: &str,
            docs: &[&str],
        ) -> Result<Vec<f32>, crate::embeddings::EmbedderError> {
            Ok(vec![self.0; docs.len()])
        }
        fn model_id(&self) -> &str {
            "fixed-reranker"
        }
    }

    struct TwoScoreReranker(f32, f32);
    impl crate::embeddings::Reranker for TwoScoreReranker {
        fn rerank(
            &self,
            _query: &str,
            _docs: &[&str],
        ) -> Result<Vec<f32>, crate::embeddings::EmbedderError> {
            Ok(vec![self.0, self.1])
        }
        fn model_id(&self) -> &str {
            "two-score"
        }
    }

    fn band_bundle(top_abs_evidence: f32) -> ContextBundle {
        let mut capsule = make_capsule("a memory lesson", 0.9);
        capsule.kind = "memory".to_string();
        capsule.token_estimate = 10;
        ContextBundle {
            stage: "localization".into(),
            budget_tokens: 4000,
            used_tokens: 10,
            capsules: vec![capsule],
            excluded: vec![],
            skipped: false,
            top_score: 0.9,
            top_abs_evidence,
            evidence_coverage: 1.0,
            uncovered_terms: vec![],
            chronological: false,
            known_fact_conflicts: vec![],
        }
    }

    /// In-band + cross-encoder approves → injected (recall recovered).
    /// In-band + cross-encoder rejects → converted to a skipped bundle.
    #[test]
    fn band_arbitration_follows_the_cross_encoder() {
        let approve = FixedReranker(ABSTAIN_RERANK_FLOOR + 0.2);
        let out = rerank_and_arbitrate("q", band_bundle(0.50), Some(&approve), 0.55, 0.0, 0);
        assert!(!out.skipped, "approved band bundle must inject");
        assert_eq!(out.capsules.len(), 1);

        let reject = FixedReranker(ABSTAIN_RERANK_FLOOR - 0.2);
        let out = rerank_and_arbitrate("q", band_bundle(0.50), Some(&reject), 0.55, 0.0, 0);
        assert!(out.skipped, "rejected band bundle must convert to skipped");
        assert!(out.capsules.is_empty());
        assert_eq!(out.used_tokens, 0);
        assert_eq!(out.excluded.len(), 1, "rejected capsules land in excluded");
    }

    /// The evidence-band threshold is calibrated on raw cross-encoder scores,
    /// before the supersession policy is reapplied to ordering.
    #[test]
    fn band_arbitration_uses_raw_rerank_evidence() {
        let mut bundle = band_bundle(0.50);
        bundle.capsules[0].superseded_hint = true;
        bundle
            .capsules
            .push(make_capsule("irrelevant distractor", 1.0));

        let reranker = TwoScoreReranker(0.95, 0.0);
        let out = rerank_and_arbitrate("q", bundle, Some(&reranker), 0.55, 0.0, 0);
        assert!(!out.skipped, "raw rerank evidence above 0.9 must admit");
        assert_eq!(out.capsules[0].summary, "a memory lesson");
        assert!(
            out.capsules[0].score < ABSTAIN_RERANK_FLOOR,
            "the regression requires post-policy score below the raw-score floor"
        );
    }

    /// Admission evidence is computed before policy ordering and output cap.
    /// Bounded usefulness cannot displace clearly stronger raw evidence.
    #[test]
    fn band_arbitration_uses_raw_evidence_before_policy_cap() {
        let mut bundle = band_bundle(0.50);
        bundle.capsules[0].rerank_policy_tier = 1;
        bundle
            .capsules
            .push(make_capsule("high-confidence neutral", 1.0));

        let reranker = TwoScoreReranker(0.50, 0.95);
        let out = rerank_and_arbitrate("q", bundle, Some(&reranker), 0.55, 0.0, 1);
        assert!(!out.skipped, "raw evidence outside the cap must admit");
        assert_eq!(out.capsules.len(), 1);
        assert_eq!(out.capsules[0].summary, "high-confidence neutral");
    }

    /// Above the band the cross-encoder reorders but never converts, even
    /// when its scores are low.
    #[test]
    fn band_arbitration_never_converts_out_of_band_bundles() {
        let reject = FixedReranker(0.0);
        let out = rerank_and_arbitrate("q", band_bundle(0.70), Some(&reject), 0.55, 0.0, 0);
        assert!(
            !out.skipped,
            "evidence above the threshold is not arbitrated"
        );
        assert_eq!(out.capsules.len(), 1);
    }

    /// No reranker: the band FAILS CLOSED — equivalent to the plain hard gate.
    /// Out-of-band bundles pass through untouched.
    #[test]
    fn band_fails_closed_without_a_reranker() {
        let out = rerank_and_arbitrate("q", band_bundle(0.50), None, 0.55, 0.0, 0);
        assert!(out.skipped, "band without an arbiter must abstain");
        let out = rerank_and_arbitrate("q", band_bundle(0.70), None, 0.55, 0.0, 0);
        assert!(!out.skipped);
        // Gate disabled: nothing converts.
        let out = rerank_and_arbitrate("q", band_bundle(0.10), None, 0.0, 0.0, 0);
        assert!(!out.skipped);
    }

    /// Reranker that scores docs by position: first doc highest. Used to
    /// simulate the cross-encoder preferring the OLD twin's wording.
    struct PositionReranker;
    impl crate::embeddings::Reranker for PositionReranker {
        fn rerank(
            &self,
            _query: &str,
            docs: &[&str],
        ) -> Result<Vec<f32>, crate::embeddings::EmbedderError> {
            Ok((0..docs.len()).map(|i| 0.99 - 0.01 * i as f32).collect())
        }
        fn model_id(&self) -> &str {
            "position-reranker"
        }
    }

    /// The supersession penalty must survive reranking: the cross-encoder
    /// judges pure query relevance, so without reapplying the penalty on its
    /// scores an older twin whose wording matches the query better would be
    /// resurrected above its replacement (measured: resolution 0.58 → 0.36).
    #[test]
    fn supersession_penalty_survives_reranking() {
        let mut old = make_capsule("deploy via make deploy-staging", 0.7);
        old.superseded_hint = true; // marked by apply_supersession_penalty
        let new = make_capsule("deploy via make deploy-preview since the migration", 0.9);
        let mut bundle = band_bundle(0.70); // out of band: no conversion risk
        bundle.capsules = vec![old, new];

        // PositionReranker scores the OLD twin (first doc) highest: 0.99 vs
        // 0.98. The reapplied ×0.80 penalty must drop it below the new one.
        let out = rerank_and_arbitrate("q", bundle, Some(&PositionReranker), 0.55, 0.0, 0);
        assert!(!out.skipped);
        assert_eq!(out.capsules.len(), 2);
        assert!(
            out.capsules[0].summary.contains("deploy-preview"),
            "the replacement must outrank the penalized incumbent after reranking; got {:?}",
            out.capsules.iter().map(|c| &c.summary).collect::<Vec<_>>()
        );
        assert!(out.capsules[1].superseded_hint);
    }

    /// A bundle with a non-memory capsule is never converted: repo evidence
    /// stands on its own.
    #[test]
    fn band_spares_bundles_with_repo_evidence() {
        let mut bundle = band_bundle(0.50);
        let mut repo = make_capsule("README excerpt", 0.4);
        repo.kind = "repo_file".to_string();
        bundle.capsules.push(repo);
        let reject = FixedReranker(0.0);
        let out = rerank_and_arbitrate("q", bundle, Some(&reject), 0.55, 0.0, 0);
        assert!(!out.skipped, "repo capsules suppress band conversion");
    }

    // ── v1.5 Story 2.1: compress_for_render unit tests ──────────────────────

    /// CFR-1: short text (< 3 sentences) is returned unchanged (no truncation).
    #[test]
    fn compress_for_render_short_text_unchanged() {
        let text = "project:fact - Use cargo fmt before committing.";
        let out = compress_for_render(text, 3);
        assert_eq!(out, text, "short text must not be altered");
    }

    /// CFR-2: [tags: ...] prefix is stripped before capping.
    #[test]
    fn compress_for_render_strips_tags_prefix() {
        let text = "[tags: rust, cargo] Always run cargo clippy before submitting a PR.";
        let out = compress_for_render(text, 3);
        assert!(
            !out.starts_with('['),
            "tags prefix must be stripped, got: {out:?}"
        );
        assert!(
            out.contains("cargo clippy"),
            "body must remain, got: {out:?}"
        );
    }

    /// CFR-3: (context: ...) trailing suffix is stripped.
    #[test]
    fn compress_for_render_strips_context_suffix() {
        let text =
            "project:fact - Use cargo fmt. Always clippy clean. (context: Kimetsu brain lesson)";
        let out = compress_for_render(text, 5);
        assert!(
            !out.contains("(context:"),
            "context suffix must be stripped, got: {out:?}"
        );
        assert!(out.contains("cargo fmt"), "body must remain, got: {out:?}");
    }

    /// CFR-4: multi-sentence body is capped at max_sentences.
    #[test]
    fn compress_for_render_caps_sentences() {
        let text =
            "project:fact - First sentence. Second sentence. Third sentence. Fourth sentence.";
        let out = compress_for_render(text, 2);
        // Must contain "First" and "Second" but not "Third" or "Fourth".
        assert!(out.contains("First"), "first sentence must be present");
        assert!(out.contains("Second"), "second sentence must be present");
        assert!(
            !out.contains("Third"),
            "third sentence must be truncated, got: {out:?}"
        );
    }

    /// CFR-5: scope:kind prefix is preserved after compression.
    #[test]
    fn compress_for_render_preserves_scope_prefix() {
        let text = "global_user:convention - First rule. Second rule. Third rule. Fourth rule.";
        let out = compress_for_render(text, 2);
        assert!(
            out.starts_with("global_user:convention - "),
            "scope prefix must be preserved, got: {out:?}"
        );
        assert!(out.contains("First"), "first sentence must remain");
        assert!(!out.contains("Third"), "third sentence must be truncated");
    }

    /// CFR-6: empty string never panics and returns the original (empty) string.
    #[test]
    fn compress_for_render_empty_input_safe() {
        let out = compress_for_render("", 3);
        assert_eq!(out, "", "empty input must return empty string");
    }

    /// CFR-7: max_sentences=0 returns the original text unchanged (opt-out).
    #[test]
    fn compress_for_render_zero_max_sentences_returns_original() {
        let text = "project:fact - Some lesson that is quite long. It keeps going. And going.";
        let out = compress_for_render(text, 0);
        assert_eq!(out, text);
    }

    /// CFR-8: exotic UTF-8 (multi-byte characters) is handled safely.
    #[test]
    fn compress_for_render_utf8_safe() {
        let text = "project:fact - こんにちは世界. Hello world. Third sentence. Fourth sentence.";
        // Should not panic; body trimming is purely ASCII-safe (splitting on b'.')
        let out = compress_for_render(text, 2);
        assert!(!out.is_empty(), "UTF-8 text must not produce empty output");
        // The first Japanese sentence period is b'.', so cap at 2 means we cut after the 2nd.
        assert!(!out.contains("Third"), "third sentence must be truncated");
    }

    /// CFR-9: long memory (>60 tokens) is compressed by >=25%.
    /// Acceptance test for the Story 2.1 token-reduction gate.
    #[test]
    fn compress_for_render_long_memory_reduces_tokens_by_25_percent() {
        // Representative long memory text (8 sentences, well over 60 tokens).
        let long_summary = "project:fact - When a SQLite WAL file exists from a crashed process, \
            opening the DB causes the WAL to be replayed. The replayed WAL may contain \
            partial writes that corrupt the DB. Always check for WAL files before opening. \
            Delete the WAL only after verifying the DB is consistent. Use PRAGMA integrity_check \
            to validate after opening. If integrity_check fails, restore from backup. Never \
            truncate the WAL without replaying it first. This pattern applies to any \
            crash-recovery scenario.";

        let raw_tokens = estimate_tokens(long_summary);
        assert!(
            raw_tokens > 60,
            "test precondition: raw memory must be >60 tokens, got {raw_tokens}"
        );

        let compressed = compress_for_render(long_summary, 3);
        let compressed_tokens = estimate_tokens(&compressed);

        let reduction = 1.0 - (compressed_tokens as f64 / raw_tokens as f64);
        assert!(
            reduction >= 0.25,
            "compression must reduce tokens by >=25% on long memories; \
             raw={raw_tokens} compressed={compressed_tokens} reduction={reduction:.2}"
        );
    }
}

#[cfg(test)]
mod evidence_tests {
    use super::*;

    fn conn_with(texts: &[&str]) -> Connection {
        let conn = Connection::open_in_memory().expect("open");
        crate::schema::initialize(&conn).expect("schema");
        for (i, text) in texts.iter().enumerate() {
            conn.execute(
                "INSERT INTO memories
                 (memory_id, scope, kind, text, normalized_text, confidence,
                  provenance_snapshot_json, created_at)
                 VALUES (?1, 'project', 'fact', ?2, ?2, 0.9, '{}', '2026-01-01T00:00:00Z')",
                rusqlite::params![format!("m{i}"), text],
            )
            .expect("insert");
            conn.execute("INSERT INTO memories_fts(memory_id,text,kind,scope) VALUES (?1,?2,'fact','project')",
                params![format!("m{i}"),text]).unwrap();
        }
        conn
    }

    fn capsule(summary: &str) -> ContextCapsule {
        ContextCapsule {
            id: String::new(),
            kind: "memory".to_string(),
            summary: summary.to_string(),
            token_estimate: 10,
            expansion_handle: format!("memory:{summary}"),
            provenance: Vec::new(),
            confidence: 0.9,
            freshness: 0.5,
            relevance: 0.0,
            scope_weight: 0.9,
            score: 0.5,
            superseded_hint: false,
            rerank_policy_tier: 0,
            claim_revision: None,
            facts: vec![],
            rerank_usefulness: None,
            rerank_trust: None,
        }
    }

    fn bundle(capsules: Vec<ContextCapsule>, coverage: f32, uncovered: &[&str]) -> ContextBundle {
        ContextBundle {
            stage: "localization".to_string(),
            budget_tokens: 2000,
            used_tokens: 20,
            capsules,
            excluded: Vec::new(),
            skipped: false,
            top_score: 0.7,
            top_abs_evidence: 0.0,
            evidence_coverage: coverage,
            uncovered_terms: uncovered.iter().map(|s| s.to_string()).collect(),
            chronological: false,
            known_fact_conflicts: vec![],
        }
    }

    /// A bundle that answers the question fully must report full coverage and
    /// name nothing — a complete answer should cost zero extra tokens.
    #[test]
    fn full_coverage_names_nothing() {
        let conn = conn_with(&[
            "checkpoint the wal before copying brain.db",
            "vacuum reclaims dead pages",
        ]);
        let (coverage, uncovered) = evidence_coverage(
            &conn,
            "checkpoint wal",
            &[capsule(
                "project:fact - checkpoint the wal before copying brain.db",
            )],
        );
        assert!(coverage > 0.99, "got {coverage}");
        assert!(uncovered.is_empty(), "got {uncovered:?}");
    }

    /// The case that matters: capsules that touch part of the query. The
    /// reader must be told which part memory does not cover, rather than being
    /// left to infer it.
    #[test]
    fn partial_coverage_names_the_missing_terms() {
        let conn = conn_with(&[
            "checkpoint the wal before copying brain.db",
            "the migration runner snapshots before each step",
        ]);
        let (coverage, uncovered) = evidence_coverage(
            &conn,
            "checkpoint wal migration",
            &[capsule(
                "project:fact - checkpoint the wal before copying brain.db",
            )],
        );
        assert!(coverage < 1.0, "coverage should be partial: {coverage}");
        assert!(
            uncovered.iter().any(|t| t.starts_with("migrat")),
            "the uncovered term must be named: {uncovered:?}"
        );
    }

    /// Coverage is measured over the union of the capsules, not the best one:
    /// the question is whether the bundle answers the query.
    #[test]
    fn coverage_is_collective_not_per_capsule() {
        let conn = conn_with(&[
            "checkpoint the wal before copying brain.db",
            "the migration runner snapshots before each step",
        ]);
        let (coverage, uncovered) = evidence_coverage(
            &conn,
            "checkpoint migration",
            &[
                capsule("project:fact - checkpoint the wal before copying"),
                capsule("project:fact - the migration runner snapshots first"),
            ],
        );
        assert!(
            coverage > 0.99,
            "neither capsule covers both terms, but together they do: {coverage}"
        );
        assert!(uncovered.is_empty(), "got {uncovered:?}");
    }

    /// A query of nothing but stopwords has no content to measure. Claiming a
    /// gap there would make every vague question look like a memory failure.
    #[test]
    fn an_unmeasurable_query_does_not_claim_a_gap() {
        let conn = conn_with(&["checkpoint the wal"]);
        let (coverage, uncovered) =
            evidence_coverage(&conn, "the and of", &[capsule("project:fact - checkpoint")]);
        assert_eq!(coverage, 1.0);
        assert!(uncovered.is_empty());
    }

    /// The case that made this need its own IDF. A query term the corpus has
    /// never seen is the *strongest* evidence memory does not cover the
    /// question — but the per-memory floor's IDF zeroes exactly those, because
    /// there an out-of-corpus word would sink every candidate. Reusing it here
    /// made "checkpoint the wal during a kubernetes rollout" report full
    /// coverage on the strength of the WAL half alone.
    #[test]
    fn a_term_the_corpus_has_never_seen_counts_as_a_gap() {
        let conn = conn_with(&[
            "checkpoint the wal before copying brain.db",
            "vacuum reclaims dead pages",
        ]);
        let (coverage, uncovered) = evidence_coverage(
            &conn,
            "checkpoint the wal during a kubernetes rollout",
            &[capsule(
                "project:fact - checkpoint the wal before copying brain.db",
            )],
        );
        assert!(
            coverage <= PARTIAL_EVIDENCE_COVERAGE,
            "an unknown half of the question must read as thin, not complete: {coverage}"
        );
        assert!(
            uncovered.iter().any(|t| t.starts_with("kubernet")),
            "the unknown term must be named: {uncovered:?}"
        );
    }

    /// …and the mirror: a term in *every* memory (the project name) carries no
    /// signal either way and must not inflate coverage.
    #[test]
    fn a_ubiquitous_term_carries_no_weight() {
        let conn = conn_with(&["kimetsu checkpoint wal", "kimetsu vacuum pages"]);
        let (coverage, _) = evidence_coverage(
            &conn,
            "kimetsu vacuum",
            &[capsule("project:fact - kimetsu vacuum pages")],
        );
        assert!(coverage > 0.99, "got {coverage}");
    }

    #[test]
    fn an_empty_query_does_not_claim_a_gap() {
        let conn = conn_with(&["checkpoint the wal"]);
        assert_eq!(evidence_coverage(&conn, "", &[]).0, 1.0);
    }

    // ── The rendered notice ──────────────────────────────────────────────

    #[test]
    fn a_complete_bundle_gets_no_notice() {
        assert!(partial_evidence_notice(&bundle(vec![capsule("a")], 1.0, &[])).is_none());
        assert!(
            partial_evidence_notice(&bundle(vec![capsule("a")], 0.9, &["x"])).is_none(),
            "above the threshold is not partial"
        );
    }

    #[test]
    fn an_empty_or_skipped_bundle_gets_no_notice() {
        let mut skipped = bundle(Vec::new(), 0.0, &["x"]);
        skipped.skipped = true;
        assert!(
            partial_evidence_notice(&skipped).is_none(),
            "an empty bundle already says everything it can"
        );
        assert!(partial_evidence_notice(&bundle(Vec::new(), 0.0, &["x"])).is_none());
    }

    #[test]
    fn a_partial_bundle_names_what_is_missing_and_tells_the_reader_what_to_do() {
        let notice =
            partial_evidence_notice(&bundle(vec![capsule("a")], 0.3, &["migration", "rollback"]))
                .expect("a thin bundle must be flagged");
        assert!(notice.contains("migration"), "got: {notice}");
        assert!(notice.contains("rollback"), "got: {notice}");
        assert!(
            notice.contains("unknown"),
            "the notice must tell the reader to abstain, not just report a gap: {notice}"
        );
    }

    /// Naming twenty terms is noise.
    #[test]
    fn the_notice_caps_how_many_terms_it_names() {
        let terms: Vec<String> = (0..12).map(|i| format!("term{i}")).collect();
        let refs: Vec<&str> = terms.iter().map(String::as_str).collect();
        let notice =
            partial_evidence_notice(&bundle(vec![capsule("a")], 0.1, &refs)).expect("flagged");
        assert!(notice.contains("and 6 more"), "got: {notice}");
        assert!(!notice.contains("term9"), "got: {notice}");
    }

    // ── v2.6: light stemming ─────────────────────────────────────────────

    /// The defect BrainBench's sycophancy track surfaced: a query asking about
    /// `retry` treated a corpus saying `retries` as not mentioning it, because
    /// the two stemmed to `retry` and `retri` and neither prefixes the other.
    #[test]
    fn the_y_ies_pair_shares_a_stem() {
        for (a, b) in [
            ("retry", "retries"),
            ("query", "queries"),
            ("policy", "policies"),
            ("memory", "memories"),
            ("binary", "binaries"),
            ("registry", "registries"),
        ] {
            assert_eq!(
                light_stem(a),
                light_stem(b),
                "{a}/{b} stemmed to {:?}/{:?}",
                light_stem(a),
                light_stem(b)
            );
        }
    }

    /// Vowel-`y` is part of the word, not an inflection: `day` is not `da`.
    #[test]
    fn a_vowel_y_is_not_stripped() {
        assert_eq!(light_stem("delay"), "delay");
        assert_eq!(light_stem("gateway"), "gateway");
        // "journeys" strips the s (7 chars remain), and the y survives because
        // a vowel precedes it.
        assert_eq!(light_stem("journeys"), "journey");
    }

    /// Short words are left alone: over-stemming a four-letter token leaves a
    /// prefix that matches half the corpus.
    #[test]
    fn short_words_keep_their_ending() {
        assert_eq!(light_stem("body"), "body");
        assert_eq!(light_stem("copy"), "copy");
    }

    /// The pre-existing behaviour must be unchanged — this rule is additive.
    #[test]
    fn the_original_suffix_rules_still_hold() {
        assert_eq!(light_stem("benchmarked"), "benchmark");
        assert_eq!(light_stem("benchmarking"), "benchmark");
        assert_eq!(light_stem("migrations"), "migration");
        assert_eq!(light_stem("run"), "run");
    }

    /// End to end, which is the form the defect actually took: a bundle must
    /// not report a gap on a term the corpus inflects differently.
    #[test]
    fn an_inflected_corpus_term_counts_as_covered() {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        let text = "the ingest worker retries a failed batch three times before giving up";
        let normalized = kimetsu_core::memory::normalize_memory_text(text);
        conn.execute(
            "
            INSERT INTO memories (
                memory_id, scope, kind, text, normalized_text, confidence,
                source_event_id, provenance_snapshot_json, created_at
            )
            VALUES ('m_retry', 'project', 'fact', ?1, ?2, 1.0, NULL, '{}',
                    '2026-01-01T00:00:00Z')
            ",
            rusqlite::params![text, normalized],
        )
        .expect("insert memory");
        conn.execute(
            "INSERT INTO memories_fts (memory_id, text, kind, scope)
             VALUES ('m_retry', ?1, 'fact', 'project')",
            rusqlite::params![text],
        )
        .expect("insert fts");

        let bundle = retrieve_context_with_embedder(
            &conn,
            "/fake-repo",
            &kimetsu_core::config::BrokerWeights::default(),
            ContextRequest {
                stage: "localization".to_string(),
                query: "how many times does the ingest worker retry a failed batch".to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve");

        assert!(
            !bundle.uncovered_terms.iter().any(|t| t.starts_with("retr")),
            "`retry` must match a corpus that says `retries`; uncovered: {:?}",
            bundle.uncovered_terms
        );
    }

    // ── v2.6: event ordering (crate::ordering) ──────────────────────────

    /// Seed two memories on the same topic, written months apart, and retrieve
    /// them. The end-to-end proof that `crate::ordering` is actually reachable
    /// from the broker — the unit tests there operate on capsules the broker
    /// never handed them.
    fn ordering_conn() -> rusqlite::Connection {
        let conn = rusqlite::Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        for (mid, created, text) in [
            (
                "m_late",
                "2026-06-01T09:00:00Z",
                "switched the error type to thiserror",
            ),
            (
                "m_early",
                "2026-01-15T10:00:00Z",
                "ran the thiserror schema migration",
            ),
        ] {
            let normalized = kimetsu_core::memory::normalize_memory_text(text);
            conn.execute(
                "
                INSERT INTO memories (
                    memory_id, scope, kind, text, normalized_text, confidence,
                    source_event_id, provenance_snapshot_json, created_at
                )
                VALUES (?1, 'project', 'fact', ?2, ?3, 1.0, NULL, '{}', ?4)
                ",
                rusqlite::params![mid, text, normalized, created],
            )
            .expect("insert memory");
            conn.execute(
                "INSERT INTO memories_fts (memory_id, text, kind, scope)
                 VALUES (?1, ?2, 'fact', 'project')",
                rusqlite::params![mid, text],
            )
            .expect("insert fts");
        }
        conn
    }

    fn ordering_bundle(conn: &rusqlite::Connection, query: &str) -> ContextBundle {
        retrieve_context_with_embedder(
            conn,
            "/fake-repo",
            &kimetsu_core::config::BrokerWeights::default(),
            ContextRequest {
                stage: "localization".to_string(),
                query: query.to_string(),
                budget_tokens: 4000,
                ..Default::default()
            },
            &[],
            &embeddings::NoopEmbedder,
        )
        .expect("retrieve")
    }

    /// The fix, end to end: asked which came first, the reader is handed the
    /// memories oldest-first with the dates it needs to answer.
    #[test]
    fn an_ordering_query_returns_a_dated_chronological_bundle() {
        let conn = ordering_conn();
        let bundle = ordering_bundle(&conn, "did we run the thiserror migration before or after");

        assert!(bundle.chronological, "the query asked about order");
        let order: Vec<&str> = bundle
            .capsules
            .iter()
            .filter_map(|c| c.expansion_handle.strip_prefix("memory:"))
            .collect();
        assert_eq!(order, vec!["m_early", "m_late"], "oldest first");
        for (capsule, date) in bundle.capsules.iter().zip(["2026-01-15", "2026-06-01"]) {
            assert!(
                capsule.summary.contains(&format!("[{date}]")),
                "every capsule carries its date; got: {}",
                capsule.summary
            );
        }
    }

    /// The narrow gate is the whole reason this is safe: an ordinary question
    /// keeps relevance order and spends no tokens on dates.
    #[test]
    fn an_ordinary_query_is_untouched() {
        let conn = ordering_conn();
        let bundle = ordering_bundle(&conn, "how do we handle thiserror errors");

        assert!(!bundle.chronological);
        for capsule in &bundle.capsules {
            assert!(
                !capsule.summary.contains('['),
                "no dates on a non-ordering query; got: {}",
                capsule.summary
            );
        }
    }

    /// Presentation, not selection: reordering runs after the budget loop, so
    /// the same capsules ship either way. If this ever diverges, ordering has
    /// started changing *what* the reader sees rather than how.
    #[test]
    fn ordering_changes_the_rendering_not_the_selection() {
        let conn = ordering_conn();
        let ordered = ordering_bundle(&conn, "did we run the thiserror migration before or after");
        let plain = ordering_bundle(&conn, "did we run the thiserror migration");

        let mut got: Vec<&str> = ordered
            .capsules
            .iter()
            .map(|c| c.expansion_handle.as_str())
            .collect();
        let mut want: Vec<&str> = plain
            .capsules
            .iter()
            .map(|c| c.expansion_handle.as_str())
            .collect();
        got.sort_unstable();
        want.sort_unstable();
        assert_eq!(got, want, "same capsules, different order");
    }

    /// The dates are real tokens and the bundle's accounting has to say so,
    /// or a budgeted caller under-counts what it just injected.
    #[test]
    fn the_dates_are_counted_against_the_budget() {
        let conn = ordering_conn();
        let ordered = ordering_bundle(&conn, "did we run the thiserror migration before or after");
        let plain = ordering_bundle(&conn, "did we run the thiserror migration");
        assert!(
            ordered.used_tokens > plain.used_tokens,
            "dated: {} vs plain: {}",
            ordered.used_tokens,
            plain.used_tokens
        );
        assert_eq!(
            ordered.used_tokens,
            ordered
                .capsules
                .iter()
                .map(|c| c.token_estimate)
                .sum::<u32>(),
            "used_tokens must match what was actually rendered"
        );
    }
}

#[cfg(test)]
mod hardening_tests {
    use super::*;

    fn corpus() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        crate::schema::initialize(&conn).unwrap();
        for (id, text) in [
            ("live", "routing routing routes"),
            ("future", "routing"),
            ("expired", "routing"),
            ("offset", "routing"),
            ("other", "rerouting unrelated"),
        ] {
            conn.execute("INSERT INTO memories (memory_id,scope,kind,text,normalized_text,confidence,created_at,provenance_snapshot_json)
                VALUES (?1,'project','fact',?2,?2,1,'2020-01-01T00:00:00Z','{}')", params![id,text]).unwrap();
            conn.execute("INSERT INTO memories_fts(memory_id,text,kind,scope) VALUES (?1,?2,'fact','project')",params![id,text]).unwrap();
        }
        conn
    }

    #[test]
    fn hardening_live_lexical_and_recency_apply_both_time_bounds() {
        let conn = corpus();
        let now = OffsetDateTime::now_utc();
        let fmt = &time::format_description::well_known::Rfc3339;
        let future = (now + time::Duration::hours(1)).format(fmt).unwrap();
        let expired = (now - time::Duration::seconds(2)).format(fmt).unwrap();
        let offset = (now - time::Duration::seconds(2))
            .to_offset(time::UtcOffset::from_hms(12, 0, 0).unwrap())
            .format(fmt)
            .unwrap();
        conn.execute(
            "UPDATE memories SET valid_from=?1 WHERE memory_id='future'",
            params![future],
        )
        .unwrap();
        conn.execute(
            "UPDATE memories SET valid_to=?1 WHERE memory_id='expired'",
            params![expired],
        )
        .unwrap();
        conn.execute(
            "UPDATE memories SET valid_to=?1 WHERE memory_id='offset'",
            params![offset],
        )
        .unwrap();
        for candidates in [
            memory_fts_candidates(
                &conn,
                &["routing".into()],
                "routing*",
                80,
                None,
                30.0,
                false,
            )
            .unwrap(),
            latest_memory_candidates(&conn, &["routing".into()], 200, None, 30.0, false).unwrap(),
        ] {
            let ids: Vec<_> = candidates
                .iter()
                .map(|c| c.capsule.expansion_handle.as_str())
                .collect();
            assert!(ids.contains(&"memory:live"));
            for id in ["memory:future", "memory:expired", "memory:offset"] {
                assert!(!ids.contains(&id), "returned {id}");
            }
        }
    }

    #[test]
    fn hardening_hydration_binds_text_revision_before_later_correction() {
        let conn = corpus();
        let candidates = memory_fts_candidates(
            &conn,
            &["routing".into()],
            "routing*",
            80,
            None,
            30.0,
            false,
        )
        .unwrap();
        let capsules: Vec<_> = candidates.into_iter().map(|c| c.capsule).collect();
        assert_eq!(memory_revision_bindings(&capsules)["live"], "baseline:live");
        conn.execute("INSERT INTO memory_revisions(memory_id,event_id,text,kind,known_at,effective_at,confidence,use_count,usefulness_score)
            VALUES ('live','corrected','changed claim','fact','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z',1,0,0)",[]).unwrap();
        conn.execute(
            "UPDATE memories SET text='changed claim' WHERE memory_id='live'",
            [],
        )
        .unwrap();
        assert_eq!(
            crate::projector::claim_revision_at(&conn, "live", None).unwrap(),
            "corrected"
        );
        assert_eq!(memory_revision_bindings(&capsules)["live"], "baseline:live");
        assert!(
            capsules
                .iter()
                .find(|c| c.expansion_handle == "memory:live")
                .unwrap()
                .summary
                .contains("routing routing")
        );
    }

    #[cfg(feature = "embeddings")]
    #[test]
    fn hardening_ann_hydration_filters_time_bounds() {
        let conn = corpus();
        let blob = crate::embeddings::encode_embedding(&[1.0, 0.0]);
        conn.execute(
            "UPDATE memories SET embedding=?1,embedding_model='test'",
            params![blob],
        )
        .unwrap();
        conn.execute(
            "UPDATE memories SET valid_from='2099-01-01T00:00:00Z' WHERE memory_id='future'",
            [],
        )
        .unwrap();
        let expired = (OffsetDateTime::now_utc() - time::Duration::seconds(2))
            .to_offset(time::UtcOffset::from_hms(12, 0, 0).unwrap())
            .format(&time::format_description::well_known::Rfc3339)
            .unwrap();
        conn.execute(
            "UPDATE memories SET valid_to=?1 WHERE memory_id IN ('expired','offset')",
            params![expired],
        )
        .unwrap();
        let qe = QueryEmbedding {
            vector: vec![1.0, 0.0],
            model_id: "test".into(),
        };
        let out = memory_ann_candidates(&conn, &qe, 80, &["routing".into()], 30.0, false).unwrap();
        assert_eq!(out.len(), 2);
        for c in out {
            assert!(matches!(
                c.capsule.expansion_handle.as_str(),
                "memory:live" | "memory:other"
            ));
        }
    }

    #[test]
    fn hardening_idf_counts_prefix_documents_not_occurrences_or_substrings() {
        let conn = corpus();
        let tokens = vec!["rout".into(), "absent".into()];
        let coverage = coverage_token_idf(&conn, &tokens).unwrap();
        // Four prefix-matching documents out of five; repeated terms count once.
        assert!((coverage["rout"] - (6.0_f32 / 5.0).ln()).abs() < 0.00001);
        assert!((coverage["absent"] - 6.0_f32.ln()).abs() < 0.00001);
        assert_eq!(corpus_token_idf(&conn, &tokens).unwrap()["absent"], 0.0);
    }
}

#[cfg(test)]
mod structured_fact_hydration_tests {
    use super::*;
    use kimetsu_core::{event::Event, ids::RunId};

    #[test]
    fn lexical_and_recency_capsules_keep_their_delivered_fact_revision() {
        let c = Connection::open_in_memory().unwrap();
        crate::schema::initialize(&c).unwrap();
        crate::projector::apply_events(&c,&[Event::new(RunId::new(),"memory.accepted",serde_json::json!({
            "memory_id":"m","scope":"project","kind":"fact","text":"Orchid staging gateway port is 7319."
        }))]).unwrap();
        let mut delivered = Vec::new();
        for candidates in [
            memory_fts_candidates(&c, &["orchid".into()], "orchid*", 80, None, 30.0, true).unwrap(),
            latest_memory_candidates(&c, &["orchid".into()], 200, None, 30.0, true).unwrap(),
        ] {
            let capsule = &candidates[0].capsule;
            assert_eq!(capsule.facts.len(), 1);
            assert_eq!(capsule.facts[0].claim.value, "7319");
            assert_eq!(
                capsule.claim_revision.as_deref(),
                Some(capsule.facts[0].claim_revision.as_str())
            );
            delivered.push(capsule.clone());
        }
        crate::projector::apply_events(
            &c,
            &[Event::new(
                RunId::new(),
                "memory.corrected",
                serde_json::json!({
                    "memory_id":"m","text":"Orchid staging gateway port is 8420."
                }),
            )],
        )
        .unwrap();
        for capsule in delivered {
            assert!(capsule.summary.contains("7319"));
            assert_eq!(capsule.facts[0].claim.value, "7319");
        }
        let latest =
            latest_memory_candidates(&c, &["orchid".into()], 200, None, 30.0, true).unwrap();
        assert_eq!(latest[0].capsule.facts[0].claim.value, "8420");
    }
    #[test]
    fn legacy_wire_capsules_default_to_empty_fact_evidence() {
        let c = ContextCapsule::wire_minimal("hello".into(), "memory".into(), 1.0);
        let json = serde_json::to_value(&c).unwrap();
        assert!(json.get("facts").is_none());
        assert!(
            serde_json::from_value::<ContextCapsule>(json)
                .unwrap()
                .facts
                .is_empty()
        );
    }
}

#[cfg(test)]
mod disabled_fact_hydration_tests {
    use super::*;
    #[test]
    fn ordinary_retrieval_does_not_read_the_fact_projection() {
        let c = Connection::open_in_memory().unwrap();
        crate::schema::initialize(&c).unwrap();
        crate::projector::apply_events(
            &c,
            &[kimetsu_core::event::Event::new(
                kimetsu_core::ids::RunId::new(),
                "memory.accepted",
                serde_json::json!({"memory_id":"m","text":"Orchid gateway port is 7319."}),
            )],
        )
        .unwrap();
        c.execute_batch("DROP TABLE memory_facts").unwrap();
        for query in ["Orchid", ""] {
            let out =
                memory_candidates_flat(&c, query, None, 30.0, crate::fusion::Fusion::Linear, false)
                    .unwrap();
            assert_eq!(out.len(), 1);
            assert!(out[0].capsule.facts.is_empty());
        }
    }
}

#[cfg(test)]
mod deferred_fact_budget_tests {
    use super::*;
    #[test]
    fn initial_retrieval_budget_must_not_hide_an_eligible_conflicting_fact() {
        let c = Connection::open_in_memory().unwrap();
        crate::schema::initialize(&c).unwrap();
        for (id, value) in [("a", "7319"), ("b", "7320")] {
            let text = format!(
                "Orchid gateway port is {value}. Stable operation. Recorded settings. {}",
                "Operational notes remain available. ".repeat(350)
            );
            crate::projector::apply_events(
                &c,
                &[kimetsu_core::event::Event::new(
                    kimetsu_core::ids::RunId::new(),
                    "memory.accepted",
                    serde_json::json!({"memory_id":id,"scope":"project","kind":"fact","text":text}),
                )],
            )
            .unwrap();
        }
        let query = "What is the Orchid gateway port?";
        let policy = crate::serving::ServingPolicy {
            budget: 6000,
            cap: 1,
            explicit_fact_guard: true,
            ..Default::default()
        };
        let request = ContextRequest {
            stage: "localization".into(),
            query: query.into(),
            budget_tokens: 6000,
            ..Default::default()
        };
        let weights = BrokerWeights::default();
        let mut ordinary = request.clone();
        ordinary.max_capsules = 6;
        let ordinary = retrieve_context_with_embedder(
            &c,
            "/fake-repo",
            &weights,
            ordinary,
            &[],
            &crate::embeddings::NoopEmbedder,
        )
        .unwrap();
        assert_eq!(ordinary.capsules.len(), 1);
        assert!(ordinary.used_tokens <= 3000);
        let selected = retrieve_context_with_embedder(
            &c,
            "/fake-repo",
            &weights,
            policy.prepare(request, false),
            &[],
            &crate::embeddings::NoopEmbedder,
        )
        .unwrap();
        assert_eq!(
            selected.capsules.len(),
            2,
            "both eligible claims must reach arbitration before delivery budgeting"
        );
        let selected = policy.arbitrate(query, selected, None, 0.0);
        let delivered =
            policy.render_for_query(query, selected, true, crate::serving::EVAL_EXPOSURE_ID);
        assert_eq!(delivered.capsules.len(), 1);
        assert_eq!(delivered.payload["answerability"]["status"], "conflicting");
        assert!(delivered.payload["used_tokens"].as_u64().unwrap() <= 6000);
    }
}