eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! ADR 0064 code-anchored recall — the reverse lookup from a code surface
//! (path globs, exact symbols, or a parsed git-diff path set) to the memories
//! anchored on it. bd-u875s.2.
//!
//! This module is the deterministic query engine: candidate matching, the
//! ADR §3 ranking objective (`freshness × confidence × level_tilt` with a
//! warnings-first kind bonus), conjunctive `--kind`/`--level` filtering,
//! token-budget truncation with a stable continuation cursor, and the three
//! ADR §5 degradation codes. It is pure: rows come in as
//! [`RecallCandidateRow`] values (fetched from the `memory_anchor_index`
//! derived table by the DB layer), and the same inputs always produce a
//! byte-identical [`RecallReport`]. A recall failure must never block an
//! edit, so everything here degrades instead of erroring.

use crate::models::{MemoryAnchorFreshnessState, MemoryAnchorKind};
use crate::output::governor::{
    CURSOR_SCHEMA_V1, CursorPayload, CursorRejection, decode_cursor, derive_workspace_mac_key,
    encode_cursor,
};
use crate::search::scoring::{freshness_drift_multiplier, stale_anchor_floor};

/// Response payload schema carried under `ee.response.v2` `data.recall`.
pub const RECALL_SCHEMA_V1: &str = "ee.recall.v1";

/// Domain-separation salt for the recall continuation-cursor params hash
/// ([`recall_query_hash`]). The cursor WIRE form is the shared ADR 0063
/// governor codec (`ee.cursor.v1`, see [`crate::output::governor`]); this
/// constant is retained only as a stable hashing salt so the bound query hash
/// stays byte-stable across the migration (bd-36l0c). The bespoke
/// `ee.recall.cursor.v1` wire schema is superseded.
pub const RECALL_CURSOR_SCHEMA_V1: &str = "ee.recall.cursor.v1";

/// The reverse index has no rows for this workspace (nothing anchored yet).
/// Info-severity; never a hard error (ADR 0064 §5).
pub const ANCHOR_INDEX_EMPTY_CODE: &str = "anchor_index_empty";

/// Reverse-index generation is behind the DB generation.
pub const ANCHOR_INDEX_STALE_CODE: &str = "anchor_index_stale";

/// The index had anchored rows for the requested surface but `--kind`/
/// `--level`/`--stale` filters removed them all — distinct from
/// [`ANCHOR_INDEX_EMPTY_CODE`] so hook authors can tell the difference.
pub const RECALL_FILTERED_EMPTY_CODE: &str = "recall_filtered_empty";

/// Repair command for a stale or empty reverse index.
pub const ANCHOR_INDEX_REPAIR: &str = "ee index rebuild --workspace .";

/// Bounded candidate scan (ADR 0064 §3). The per-path/per-symbol lookups are
/// already narrow; this cap is the defensive ceiling for pathological
/// workspaces. Callers fetching more rows than this should truncate before
/// calling [`evaluate_recall`]; the engine also enforces it.
pub const RECALL_CANDIDATE_SCAN_CAP: usize = 4096;

/// Single-line content preview budget (chars), mirroring the existing
/// 240-char preview discipline.
pub const RECALL_CONTENT_PREVIEW_MAX_CHARS: usize = 240;

/// Memory kinds that receive the ADR §3 warnings-first bonus.
pub const RECALL_KIND_BONUS_KINDS: [&str; 3] = ["failure", "risk", "anti-pattern"];

/// Multiplier applied to [`RECALL_KIND_BONUS_KINDS`] memories.
pub const RECALL_KIND_BONUS: f32 = 1.15;

/// One candidate row from the `memory_anchor_index` reverse index, joined
/// with the owning memory's ranking fields. `normalized_path` is set for
/// `path` anchors, `symbol` for `symbol` anchors; the engine ignores rows
/// where neither is set.
#[derive(Clone, Debug, PartialEq)]
pub struct RecallCandidateRow {
    pub memory_id: String,
    pub anchor_kind: MemoryAnchorKind,
    pub normalized_path: Option<String>,
    pub symbol: Option<String>,
    pub freshness_state: MemoryAnchorFreshnessState,
    /// Reverse-index row generation (stamped at write time).
    pub row_generation: i64,
    /// Owning memory's level wire form (`procedural | semantic | episodic |
    /// working`).
    pub level: String,
    /// Owning memory's kind wire form (e.g. `rule`, `failure`, `risk`).
    pub kind: String,
    /// Owning memory's confidence in `[0.0, 1.0]`.
    pub confidence: f32,
    /// Owning memory's full content; the engine derives the preview.
    pub content: String,
    /// True when the owning memory carries a tombstone. Tombstoned memories
    /// are excluded at query time regardless of index hygiene.
    pub tombstoned: bool,
    pub tags: Vec<String>,
    pub provenance: Vec<RecallProvenanceRef>,
}

/// One provenance pointer on a recalled memory.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecallProvenanceRef {
    pub uri: String,
    pub source_type: String,
}

/// A recall request. `paths` are case-sensitive fnmatch-style globs,
/// `symbols` are exact names, and `diff_paths` is an already-parsed changed
/// path set (see [`diff_changed_paths`]); the three selector families compose
/// as OR with result dedup by memory id. `kinds`/`levels` filter the matched
/// set conjunctively BEFORE ranking (ADR 0064 §2). With no selectors at all
/// the engine deterministically matches nothing — the CLI surface
/// (bd-u875s.3) requires at least one selector.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RecallQuery {
    pub paths: Vec<String>,
    pub symbols: Vec<String>,
    pub diff_paths: Vec<String>,
    pub kinds: Vec<String>,
    pub levels: Vec<String>,
    /// Keep only `suspect | stale` items and append per-item repair hints —
    /// the agent-facing view of what ADR 0056 penalizes silently.
    pub stale_only: bool,
    /// Token budget for the item list; `None` means unbounded.
    pub max_tokens: Option<u32>,
    /// Rank offset for continuation (decoded from a validated cursor).
    pub offset: usize,
    /// Opt-in rank reduction for a drifted (`suspect | stale`) code anchor
    /// (bd-2vq2z.1, Phase-6 pass 2 — supersedes ADR 0056 part B). The default of
    /// `0.0` means FLAG, DON'T PENALIZE: a drifted memory keeps its rank and is
    /// surfaced only via its `freshness_state`. The CLI resolves this from
    /// `[retrieval] stale_anchor_penalty`; `RecallQuery::default()` leaves it at
    /// `0.0`, the neutral value. It never participates in the cursor query hash.
    pub stale_anchor_penalty: f32,
}

/// The anchor a memory was recalled through.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecallAnchor {
    pub kind: String,
    pub path: Option<String>,
    pub symbol: Option<String>,
}

/// ADR §3 score factors, surfaced so every item is explainable.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RecallScoreComponents {
    pub freshness: f32,
    pub confidence: f32,
    pub level_tilt: f32,
    pub kind_bonus: f32,
}

/// One ranked recall item (`ee.recall.v1` `items[]`).
#[derive(Clone, Debug, PartialEq)]
pub struct RecallItem {
    pub memory_id: String,
    pub anchor: RecallAnchor,
    pub freshness_state: String,
    pub score_components: RecallScoreComponents,
    pub score: f32,
    pub level: String,
    pub kind: String,
    pub content_preview: String,
    pub provenance: Vec<RecallProvenanceRef>,
    pub tags: Vec<String>,
    /// Suggested next command for stale items; `None` when current.
    pub repair: Option<String>,
}

/// One `degraded[]` entry the recall pipeline may emit. Pinned to the
/// canonical envelope shape (`code`, `severity`, `message`, `repair`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecallDegradation {
    pub code: &'static str,
    pub severity: &'static str,
    pub message: String,
    pub repair: Option<String>,
}

/// Deterministic recall result (`ee.recall.v1`).
#[derive(Clone, Debug, PartialEq)]
pub struct RecallReport {
    pub schema: &'static str,
    pub items: Vec<RecallItem>,
    /// `MAX(generation)` across the workspace's reverse-index rows; `None`
    /// when the index has no rows at all.
    pub index_generation: Option<i64>,
    pub db_generation: i64,
    pub degraded: Vec<RecallDegradation>,
    /// Post-filter match count before offset/budget truncation.
    pub total_matched: usize,
    pub truncated: bool,
    pub dropped_count: usize,
    pub continuation_cursor: Option<String>,
}

/// Level tilt per ADR 0064 §3. Unknown levels (defensive: the DB constrains
/// the vocabulary) sink to the working-memory tilt rather than inventing a
/// new constant.
#[must_use]
pub fn recall_level_tilt(level: &str) -> f32 {
    match level {
        "procedural" => 1.0,
        "semantic" => 0.8,
        "episodic" => 0.6,
        _ => 0.3,
    }
}

/// Kind bonus per ADR 0064 §3: warnings first.
#[must_use]
pub fn recall_kind_bonus(kind: &str) -> f32 {
    if RECALL_KIND_BONUS_KINDS.contains(&kind) {
        RECALL_KIND_BONUS
    } else {
        1.0
    }
}

/// Case-sensitive fnmatch-style glob match (ADR 0064 §2): `*` matches any
/// run of characters (including `/`), `?` matches one character, `[...]` and
/// `[!...]` match character sets. An empty pattern matches only the empty
/// string, so it never matches a real normalized path.
#[must_use]
pub fn recall_glob_match(pattern: &str, text: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let text: Vec<char> = text.chars().collect();
    let mut p = 0;
    let mut t = 0;
    let mut star: Option<(usize, usize)> = None;
    while t < text.len() {
        if p < pattern.len() {
            match pattern[p] {
                '*' => {
                    star = Some((p, t));
                    p += 1;
                    continue;
                }
                '?' => {
                    p += 1;
                    t += 1;
                    continue;
                }
                '[' => match match_char_class(&pattern, p, text[t]) {
                    Some((true, next_p)) => {
                        p = next_p;
                        t += 1;
                        continue;
                    }
                    Some((false, _)) => {}
                    // Unterminated class: `[` is a literal.
                    None => {
                        if text[t] == '[' {
                            p += 1;
                            t += 1;
                            continue;
                        }
                    }
                },
                literal => {
                    if literal == text[t] {
                        p += 1;
                        t += 1;
                        continue;
                    }
                }
            }
        }
        // Mismatch: backtrack to the last `*`, consuming one more text char.
        match star {
            Some((star_p, star_t)) => {
                p = star_p + 1;
                t = star_t + 1;
                star = Some((star_p, star_t + 1));
            }
            None => return false,
        }
    }
    while p < pattern.len() && pattern[p] == '*' {
        p += 1;
    }
    p == pattern.len()
}

/// Match one `[...]` character class starting at `pattern[open]`. Returns
/// `(matched, index_after_class)` or `None` when the class is unterminated
/// (in which case `[` is treated as a literal by the caller's fallthrough).
fn match_char_class(pattern: &[char], open: usize, ch: char) -> Option<(bool, usize)> {
    let mut i = open + 1;
    let negated = matches!(pattern.get(i), Some('!' | '^'));
    if negated {
        i += 1;
    }
    let class_start = i;
    let mut matched = false;
    while i < pattern.len() {
        if pattern[i] == ']' && i > class_start {
            return Some((matched != negated, i + 1));
        }
        if i + 2 < pattern.len() && pattern[i + 1] == '-' && pattern[i + 2] != ']' {
            if pattern[i] <= ch && ch <= pattern[i + 2] {
                matched = true;
            }
            i += 3;
        } else {
            if pattern[i] == ch {
                matched = true;
            }
            i += 1;
        }
    }
    None
}

/// Normalize a caller-supplied path selector to the reverse index's
/// normalized form: strip a leading `./`. Absolute selectors are returned
/// as-is and simply never match (normalized paths are workspace-relative by
/// construction); rejecting them here would turn a no-op into an error on
/// the hook path.
#[must_use]
pub fn normalize_recall_path_selector(selector: &str) -> String {
    selector.strip_prefix("./").unwrap_or(selector).to_owned()
}

fn diff_name_only_changed_paths(name_only_text: &str) -> Vec<String> {
    let mut paths = std::collections::BTreeSet::new();
    for line in name_only_text.lines() {
        let line = line.trim_end();
        if line.is_empty() {
            continue;
        }
        paths.insert(normalize_recall_path_selector(line));
    }
    paths.into_iter().collect()
}

fn unified_diff_non_path_line(line: &str) -> bool {
    line.starts_with("--- ")
        || line.starts_with("diff ")
        || line.starts_with("index ")
        || line.starts_with("@@")
        || line.starts_with("new file mode ")
        || line.starts_with("deleted file mode ")
        || line.starts_with("old mode ")
        || line.starts_with("new mode ")
        || line.starts_with("similarity index ")
        || line.starts_with("dissimilarity index ")
        || line.starts_with("rename from ")
        || line.starts_with("rename to ")
        || line.starts_with("copy from ")
        || line.starts_with("copy to ")
        || line.starts_with("Binary files ")
        || line.starts_with("GIT binary patch")
        || line.starts_with("literal ")
        || line.starts_with("delta ")
        || line.starts_with('+')
        || line.starts_with('-')
        || line.starts_with(' ')
        || line.starts_with('\\')
}

/// Extract the changed path set from `git diff --name-only` output (one path
/// per line) or a unified diff (`+++ b/<path>` headers). Paths are
/// normalized, deduplicated, and sorted; `/dev/null` targets are skipped.
#[must_use]
pub fn diff_changed_paths(diff_text: &str) -> Vec<String> {
    let looks_like_unified_diff = diff_text.lines().any(|line| {
        let line = line.trim_end();
        line.starts_with("diff --git a/")
            || line.starts_with("@@")
            || line.strip_prefix("+++ ").is_some_and(|target| {
                target.trim() == "/dev/null" || target.trim().starts_with("b/")
            })
    });
    if !looks_like_unified_diff {
        return diff_name_only_changed_paths(diff_text);
    }

    let mut paths = std::collections::BTreeSet::new();
    for line in diff_text.lines() {
        let line = line.trim_end();
        if line.is_empty() {
            continue;
        }
        if let Some(rest) = line.strip_prefix("+++ ") {
            let target = rest.trim();
            if target == "/dev/null" {
                continue;
            }
            let target = target.strip_prefix("b/").unwrap_or(target);
            paths.insert(normalize_recall_path_selector(target));
            continue;
        }
        if unified_diff_non_path_line(line) {
            continue;
        }
        // `--name-only` form: a bare path per line.
        paths.insert(normalize_recall_path_selector(line));
    }
    paths.into_iter().collect()
}

/// Deterministic single-line content preview (≤ [`RECALL_CONTENT_PREVIEW_MAX_CHARS`]
/// chars): whitespace collapsed, char-boundary-safe truncation with a
/// trailing ellipsis.
#[must_use]
pub fn recall_content_preview(content: &str) -> String {
    let single_line = content.split_whitespace().collect::<Vec<_>>().join(" ");
    if single_line.chars().count() <= RECALL_CONTENT_PREVIEW_MAX_CHARS {
        return single_line;
    }
    let mut preview: String = single_line
        .chars()
        .take(RECALL_CONTENT_PREVIEW_MAX_CHARS - 1)
        .collect();
    preview.push('…');
    preview
}

/// Deterministic token estimate for one rendered recall item, consistent
/// with the whitespace-based estimate the handoff surface uses. Counts the
/// fields an agent actually reads: id, anchor display, preview, and tags.
#[must_use]
pub fn recall_item_token_estimate(item: &RecallItem) -> usize {
    let anchor_display = item
        .anchor
        .path
        .as_deref()
        .or(item.anchor.symbol.as_deref())
        .unwrap_or_default();
    let text_len_words = item.memory_id.split_whitespace().count()
        + anchor_display.split_whitespace().count()
        + item.content_preview.split_whitespace().count()
        + item
            .tags
            .iter()
            .map(|tag| tag.split_whitespace().count())
            .sum::<usize>();
    text_len_words.saturating_mul(4) / 3
}

/// Stable hash binding a continuation cursor to the logical query (selector
/// and filter fields only — budget and offset intentionally excluded so a
/// continuation page reuses the same hash).
#[must_use]
pub fn recall_query_hash(query: &RecallQuery) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(RECALL_CURSOR_SCHEMA_V1.as_bytes());
    let mut feed = |label: &str, values: &[String]| {
        hasher.update(b"\0");
        hasher.update(label.as_bytes());
        let mut sorted: Vec<&String> = values.iter().collect();
        sorted.sort();
        for value in sorted {
            hasher.update(b"\0");
            hasher.update(value.as_bytes());
        }
    };
    feed("paths", &query.paths);
    feed("symbols", &query.symbols);
    feed("diff_paths", &query.diff_paths);
    feed("kinds", &query.kinds);
    feed("levels", &query.levels);
    hasher.update(if query.stale_only {
        b"\0stale:1"
    } else {
        b"\0stale:0"
    });
    hasher.finalize().to_hex().chars().take(12).collect()
}

/// Deterministic MAC-key scope for recall budget-continuation cursors.
///
/// Recall's cursor was never workspace-scoped — the prior bespoke
/// `cursor_signature` used a fixed BLAKE3 context. The per-page query binding
/// is carried by the cursor `paramsHash` ([`recall_query_hash`]) and the
/// `dbGeneration` bind-check, exactly as before. This fixed scope preserves
/// that behavior while moving the wire form onto the shared `ee.cursor.v1`
/// governor codec (bd-36l0c).
const RECALL_CURSOR_MAC_SCOPE: &str = "ee.recall.budget-continuation cursor mac v1";

fn recall_cursor_mac_key() -> [u8; 32] {
    derive_workspace_mac_key(RECALL_CURSOR_MAC_SCOPE)
}

/// Encode a recall budget-continuation cursor onto the shared `ee.cursor.v1`
/// governor codec. `next_offset` is the rank offset the continuation page
/// resumes from; recall pages the flat `data.recall.items[]` array by rank
/// offset, so the offset rides in the payload `positionKey`. `dropped_count`
/// is the honest count of ranked items still unemitted when the cursor was
/// issued (governor `droppedCount`). Returns `None` only on the practically
/// unreachable serialization failure, in which case the page is reported
/// truncated without a continuation token.
#[must_use]
fn encode_recall_cursor(
    query: &RecallQuery,
    next_offset: usize,
    dropped_count: usize,
    db_generation: i64,
) -> Option<String> {
    let payload = CursorPayload {
        schema: CURSOR_SCHEMA_V1.to_owned(),
        target_schema: RECALL_SCHEMA_V1.to_owned(),
        db_generation: u64::try_from(db_generation).unwrap_or(0),
        position_key: next_offset.to_string(),
        dropped_count: u64::try_from(dropped_count).unwrap_or(0),
        params_hash: recall_query_hash(query),
    };
    encode_cursor(&payload, &recall_cursor_mac_key()).ok()
}

/// Evaluate a recall query over candidate rows (ADR 0064 §§2–5).
///
/// `index_generation` is `MAX(generation)` over the workspace's reverse-index
/// rows (`None` when the index is empty); `db_generation` is the live
/// workspace generation. Determinism contract: identical inputs produce a
/// byte-identical report, ranking ties resolve by ascending memory id, and a
/// smaller token budget yields a strict prefix of a larger budget's items.
#[must_use]
pub fn evaluate_recall(
    query: &RecallQuery,
    rows: &[RecallCandidateRow],
    index_generation: Option<i64>,
    db_generation: i64,
) -> RecallReport {
    let mut degraded = Vec::new();

    match index_generation {
        None => degraded.push(RecallDegradation {
            code: ANCHOR_INDEX_EMPTY_CODE,
            severity: "info",
            message: "anchor reverse index has no rows for this workspace; nothing is anchored yet"
                .to_owned(),
            repair: Some(ANCHOR_INDEX_REPAIR.to_owned()),
        }),
        Some(generation) if generation < db_generation => degraded.push(RecallDegradation {
            code: ANCHOR_INDEX_STALE_CODE,
            severity: "low",
            message: format!(
                "anchor reverse index generation {generation} is behind database generation {db_generation}; results may miss recent memories"
            ),
            repair: Some(ANCHOR_INDEX_REPAIR.to_owned()),
        }),
        Some(_) => {}
    }

    let normalized_paths: Vec<String> = query
        .paths
        .iter()
        .map(|selector| normalize_recall_path_selector(selector))
        .collect();
    let diff_set: std::collections::BTreeSet<String> = query
        .diff_paths
        .iter()
        .map(|selector| normalize_recall_path_selector(selector))
        .collect();
    let symbol_set: std::collections::BTreeSet<&str> =
        query.symbols.iter().map(String::as_str).collect();

    // Surface matching (OR across selector families), tombstone exclusion,
    // bounded scan, dedup by memory id keeping the freshest anchor.
    let mut best_per_memory: std::collections::BTreeMap<&str, &RecallCandidateRow> =
        std::collections::BTreeMap::new();
    for row in rows.iter().take(RECALL_CANDIDATE_SCAN_CAP) {
        if row.tombstoned {
            continue;
        }
        let path_matched = row.normalized_path.as_deref().is_some_and(|path| {
            diff_set.contains(path)
                || normalized_paths
                    .iter()
                    .any(|pattern| recall_glob_match(pattern, path))
        });
        let symbol_matched = row
            .symbol
            .as_deref()
            .is_some_and(|symbol| symbol_set.contains(symbol));
        if !path_matched && !symbol_matched {
            continue;
        }
        best_per_memory
            .entry(row.memory_id.as_str())
            .and_modify(|kept| {
                if anchor_row_preference(row) < anchor_row_preference(kept) {
                    *kept = row;
                }
            })
            .or_insert(row);
    }
    let surface_match_count = best_per_memory.len();

    // Conjunctive pre-ranking filters (ADR §2).
    let filtered: Vec<&RecallCandidateRow> = best_per_memory
        .into_values()
        .filter(|row| query.kinds.is_empty() || query.kinds.iter().any(|kind| kind == &row.kind))
        .filter(|row| {
            query.levels.is_empty() || query.levels.iter().any(|level| level == &row.level)
        })
        .filter(|row| {
            !query.stale_only
                || matches!(
                    row.freshness_state,
                    MemoryAnchorFreshnessState::Suspect | MemoryAnchorFreshnessState::Stale
                )
        })
        .collect();

    if surface_match_count > 0 && filtered.is_empty() {
        degraded.push(RecallDegradation {
            code: RECALL_FILTERED_EMPTY_CODE,
            severity: "info",
            message: format!(
                "{surface_match_count} anchored memorie(s) matched the surface but kind/level/stale filters removed them all"
            ),
            repair: None,
        });
    }

    // Rank (ADR §3): score descending, stable tie-break by memory id.
    let mut scored: Vec<RecallItem> = filtered
        .into_iter()
        .map(|row| score_row(row, query.stale_anchor_penalty))
        .collect();
    scored.sort_by(|left, right| {
        right
            .score
            .partial_cmp(&left.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| left.memory_id.cmp(&right.memory_id))
    });

    let total_matched = scored.len();
    let paged: Vec<RecallItem> = scored.into_iter().skip(query.offset).collect();

    // Token-budget truncation: keep the longest prefix under budget.
    let (items, dropped_count) = match query.max_tokens {
        None => (paged, 0),
        Some(budget) => {
            let budget = budget as usize;
            let total = paged.len();
            let mut kept = Vec::new();
            let mut spent = 0_usize;
            let mut dropped = 0_usize;
            for (idx, item) in paged.into_iter().enumerate() {
                let cost = recall_item_token_estimate(&item);
                if spent + cost <= budget {
                    spent += cost;
                    kept.push(item);
                } else {
                    dropped = total - idx;
                    break;
                }
            }
            (kept, dropped)
        }
    };

    let truncated = dropped_count > 0;
    let continuation_cursor = if truncated && !items.is_empty() {
        encode_recall_cursor(
            query,
            query.offset + items.len(),
            dropped_count,
            db_generation,
        )
    } else {
        None
    };

    RecallReport {
        schema: RECALL_SCHEMA_V1,
        items,
        index_generation,
        db_generation,
        degraded,
        total_matched,
        truncated,
        dropped_count,
        continuation_cursor,
    }
}

/// Dedup preference when one memory matches through several anchors: freshest
/// first, then path anchors before symbol anchors, then the anchor value —
/// all deterministic.
fn anchor_row_preference(row: &RecallCandidateRow) -> (u8, MemoryAnchorKind, String) {
    (
        row.freshness_state.rank(),
        row.anchor_kind,
        row.normalized_path
            .clone()
            .or_else(|| row.symbol.clone())
            .unwrap_or_default(),
    )
}

fn score_row(row: &RecallCandidateRow, stale_anchor_penalty: f32) -> RecallItem {
    // bd-2vq2z.1 (Phase-6 pass 2): drift is a FLAG, not a rank penalty. With the
    // default `stale_anchor_penalty` of 0.0 the floor is 1.0, so a drifted anchor
    // keeps its rank and is surfaced only via `freshness_state`. An operator may
    // opt into a small tie-breaker via `[retrieval] stale_anchor_penalty`.
    let freshness = freshness_drift_multiplier(
        row.freshness_state,
        stale_anchor_floor(stale_anchor_penalty),
    );
    let confidence = row.confidence.clamp(0.0, 1.0);
    let level_tilt = recall_level_tilt(&row.level);
    let kind_bonus = recall_kind_bonus(&row.kind);
    let score = freshness * confidence * level_tilt * kind_bonus;
    let stale_ish = matches!(
        row.freshness_state,
        MemoryAnchorFreshnessState::Suspect | MemoryAnchorFreshnessState::Stale
    );
    RecallItem {
        memory_id: row.memory_id.clone(),
        anchor: RecallAnchor {
            kind: row.anchor_kind.as_str().to_owned(),
            path: row.normalized_path.clone(),
            symbol: row.symbol.clone(),
        },
        freshness_state: row.freshness_state.as_str().to_owned(),
        score_components: RecallScoreComponents {
            freshness,
            confidence,
            level_tilt,
            kind_bonus,
        },
        score,
        level: row.level.clone(),
        kind: row.kind.clone(),
        content_preview: recall_content_preview(&row.content),
        provenance: row.provenance.clone(),
        tags: row.tags.clone(),
        repair: stale_ish.then(|| format!("ee why {} --workspace . --json", row.memory_id)),
    }
}

/// Fetch candidates from the `memory_anchor_index` derived table and
/// evaluate the query (bd-u875s.2 DB wiring). Narrow indexed lookups serve
/// exact path selectors, diff path sets, and symbols; glob selectors fall
/// back to a bounded scan of the workspace's path rows. Tags are
/// batch-loaded; provenance maps the owning memory's provenance URI.
pub fn run_recall(
    connection: &crate::db::DbConnection,
    workspace_id: &str,
    query: &RecallQuery,
) -> crate::db::Result<RecallReport> {
    let db_generation = i64::try_from(
        connection
            .get_workspace_generation(workspace_id)?
            .unwrap_or(0),
    )
    .unwrap_or(i64::MAX);
    let index_generation = connection.memory_anchor_index_generation(workspace_id)?;

    let normalized_selectors: Vec<String> = query
        .paths
        .iter()
        .map(|selector| normalize_recall_path_selector(selector))
        .collect();
    let has_glob_selector = normalized_selectors
        .iter()
        .any(|selector| selector.contains(['*', '?', '[']));
    let mut exact_paths: Vec<String> = normalized_selectors
        .iter()
        .filter(|selector| !selector.contains(['*', '?', '[']))
        .cloned()
        .chain(
            query
                .diff_paths
                .iter()
                .map(|selector| normalize_recall_path_selector(selector)),
        )
        .collect();
    exact_paths.sort();
    exact_paths.dedup();

    let mut candidates = Vec::new();
    if has_glob_selector {
        candidates.extend(connection.query_anchor_index_path_candidates(
            workspace_id,
            None,
            RECALL_CANDIDATE_SCAN_CAP,
        )?);
    } else if !exact_paths.is_empty() {
        candidates.extend(connection.query_anchor_index_path_candidates(
            workspace_id,
            Some(&exact_paths),
            RECALL_CANDIDATE_SCAN_CAP,
        )?);
    }
    if !query.symbols.is_empty() {
        candidates.extend(connection.query_anchor_index_symbol_candidates(
            workspace_id,
            &query.symbols,
            RECALL_CANDIDATE_SCAN_CAP,
        )?);
    }

    let memory_ids: Vec<&str> = {
        let mut ids: Vec<&str> = candidates
            .iter()
            .map(|candidate| candidate.memory_id.as_str())
            .collect();
        ids.sort_unstable();
        ids.dedup();
        ids
    };
    let tags_by_memory = connection.get_memory_tags_batch(&memory_ids)?;

    let rows: Vec<RecallCandidateRow> = candidates
        .into_iter()
        .map(|candidate| {
            let tags = tags_by_memory
                .get(&candidate.memory_id)
                .cloned()
                .unwrap_or_default();
            let provenance = candidate
                .provenance_uri
                .as_ref()
                .map(|uri| {
                    vec![RecallProvenanceRef {
                        uri: uri.clone(),
                        source_type: "memory_provenance".to_owned(),
                    }]
                })
                .unwrap_or_default();
            RecallCandidateRow {
                memory_id: candidate.memory_id,
                anchor_kind: candidate.anchor_kind,
                normalized_path: candidate.normalized_path,
                symbol: candidate.symbol,
                freshness_state: candidate.freshness_state,
                row_generation: candidate.generation,
                level: candidate.level,
                kind: candidate.kind,
                confidence: candidate.confidence,
                content: candidate.content,
                tombstoned: candidate.tombstoned,
                tags,
                provenance,
            }
        })
        .collect();

    // Path and symbol recall only reads the anchor index. Missing embeddings
    // do not affect these results and must not trigger model loading or an
    // unrelated per-response degradation (including during daemon warm-up).
    Ok(evaluate_recall(
        query,
        &rows,
        index_generation,
        db_generation,
    ))
}

// ---------------------------------------------------------------------------
// CLI-facing surface helpers (bd-u875s.3)
// ---------------------------------------------------------------------------

/// `git_unavailable`-family degraded code (ADR 0064 §2) for a failed
/// read-only git shell-out behind `--diff`/`--diff-staged`. Recall-specific
/// rather than the shared `git_unavailable` because that code's fixture
/// pins swarm-brief/workspace-hygiene repair strings; a git failure here
/// degrades the diff selector to an empty path set and never blocks recall.
pub const RECALL_GIT_UNAVAILABLE_CODE: &str = "recall_git_unavailable";

/// Collect the changed-path set for `--diff <ref>` / `--diff-staged` by
/// shelling out to git read-only (`git -C <workspace> diff --name-only`).
/// Path extraction only; hunk ranges are reserved for future span-level
/// matching (ADR 0064 §2). Errors are returned as plain strings so the CLI
/// layer can degrade (`git_unavailable`) instead of failing the command.
pub fn collect_diff_paths_via_git(
    workspace_path: &std::path::Path,
    reference: Option<&str>,
    staged: bool,
) -> Result<Vec<String>, String> {
    if let Some(reference) = reference {
        // Refs are positional git arguments; refuse option-shaped values so
        // a hostile selector cannot smuggle flags into the invocation.
        if reference.starts_with('-') || reference.is_empty() {
            return Err(format!(
                "invalid git ref {reference:?}: refs must not be empty or start with '-'"
            ));
        }
    }
    let mut command = std::process::Command::new("git");
    command
        .arg("-C")
        .arg(workspace_path)
        .arg("diff")
        .arg("--name-only");
    if staged {
        command.arg("--cached");
    }
    if let Some(reference) = reference {
        command.arg(reference);
    }
    command.arg("--");
    let output = command
        .output()
        .map_err(|error| format!("failed to spawn git: {error}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!(
            "git diff exited with {}: {}",
            output.status,
            stderr.trim()
        ));
    }
    Ok(diff_name_only_changed_paths(&String::from_utf8_lossy(
        &output.stdout,
    )))
}

/// Outcome of resolving an optional `--cursor` flag against the live query
/// and DB generation (budget-continuation lane, shared `ee.cursor.v1` codec).
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RecallCursorResolution {
    /// No cursor supplied; start at rank offset zero.
    Fresh,
    /// Cursor validated; resume from this rank offset if the post-ranking
    /// total still matches the cursor's honest remaining-count claim.
    Resume { offset: usize, dropped_count: usize },
    /// Cursor malformed, tampered, or bound to a different query
    /// (`cursor_invalid`).
    RejectedInvalid,
    /// Cursor was issued at an older DB generation (`cursor_stale`); pages
    /// cannot partition the result set honestly across writes.
    RejectedStale {
        cursor_generation: i64,
        current_generation: i64,
    },
}

/// Resolve an optional encoded cursor against the query's stable hash and
/// the current DB generation. Rejections map to the ADR 0063 cursor
/// vocabulary (`cursor_invalid` / `cursor_stale`); they degrade, never error.
#[must_use]
pub fn resolve_recall_cursor(
    encoded: Option<&str>,
    query: &RecallQuery,
    current_db_generation: i64,
) -> RecallCursorResolution {
    let Some(encoded) = encoded else {
        return RecallCursorResolution::Fresh;
    };
    let expected_params_hash = recall_query_hash(query);
    let current_generation = u64::try_from(current_db_generation).unwrap_or(0);
    match decode_cursor(
        encoded,
        &recall_cursor_mac_key(),
        &expected_params_hash,
        current_generation,
    ) {
        // A cursor minted for another governed surface (shared MAC scope,
        // improbable params collision) must never page recall items.
        Ok(payload) if payload.target_schema != RECALL_SCHEMA_V1 => {
            RecallCursorResolution::RejectedInvalid
        }
        // The rank offset rides in `positionKey`; `droppedCount` is the
        // remaining ranked-item count at issuance. Both must survive parsing
        // so the caller can reject cursors that no longer partition honestly.
        Ok(payload) => {
            let Ok(offset) = payload.position_key.parse::<usize>() else {
                return RecallCursorResolution::RejectedInvalid;
            };
            let Ok(dropped_count) = usize::try_from(payload.dropped_count) else {
                return RecallCursorResolution::RejectedInvalid;
            };
            RecallCursorResolution::Resume {
                offset,
                dropped_count,
            }
        }
        Err(CursorRejection::Invalid) => RecallCursorResolution::RejectedInvalid,
        Err(CursorRejection::Stale {
            cursor_generation,
            current_generation,
        }) => RecallCursorResolution::RejectedStale {
            cursor_generation: i64::try_from(cursor_generation).unwrap_or(i64::MAX),
            current_generation: i64::try_from(current_generation).unwrap_or(i64::MAX),
        },
    }
}

/// Check that a decoded recall cursor still describes the ranked result set.
/// A stale, forged, or legacy cursor must not silently restart, skip, or
/// duplicate items; the CLI maps `false` to the rejected-cursor empty page.
#[must_use]
pub fn recall_cursor_page_is_honest(
    offset: usize,
    dropped_count: usize,
    total_matched: usize,
) -> bool {
    offset > 0 && offset < total_matched && total_matched - offset == dropped_count
}

/// One response-level degraded entry for the recall CLI surface: the three
/// engine codes plus the CLI-only git/cursor/budget-truncation entries, with
/// optional structured `details` for the envelope.
#[derive(Clone, Debug, PartialEq)]
pub struct RecallDegradedEntry {
    pub code: String,
    pub severity: String,
    pub message: String,
    pub repair: Option<String>,
    pub details: Option<serde_json::Value>,
}

impl RecallDegradedEntry {
    /// Lift an engine degradation into the CLI view.
    #[must_use]
    pub fn from_engine(entry: &RecallDegradation) -> Self {
        Self {
            code: entry.code.to_owned(),
            severity: entry.severity.to_owned(),
            message: entry.message.clone(),
            repair: entry.repair.clone(),
            details: None,
        }
    }

    /// `git_unavailable` (warning): the `--diff` selector degraded to an
    /// empty path set because the read-only git shell-out failed.
    #[must_use]
    pub fn git_unavailable(reason: &str) -> Self {
        Self {
            code: RECALL_GIT_UNAVAILABLE_CODE.to_owned(),
            severity: "warning".to_owned(),
            message: format!(
                "--diff selector degraded to an empty path set because git was unavailable: {reason}"
            ),
            repair: Some(
                "Re-run inside a git worktree with git on PATH, or use --path/--symbol selectors."
                    .to_owned(),
            ),
            details: None,
        }
    }

    /// `cursor_invalid` (low), mirroring the canonical ADR 0063 wording.
    #[must_use]
    pub fn cursor_invalid() -> Self {
        Self {
            code: "cursor_invalid".to_owned(),
            severity: "low".to_owned(),
            message: "Continuation cursor failed validation (MAC mismatch, parameter mismatch, \
                      or legacy format)."
                .to_owned(),
            repair: Some(
                "Re-run the command without --cursor to start a fresh page sequence.".to_owned(),
            ),
            details: None,
        }
    }

    /// `cursor_stale` (low), mirroring the canonical ADR 0063 wording.
    #[must_use]
    pub fn cursor_stale(cursor_generation: i64, current_generation: i64) -> Self {
        Self {
            code: "cursor_stale".to_owned(),
            severity: "low".to_owned(),
            message: format!(
                "Continuation cursor was issued at DB generation {cursor_generation} but the \
                 workspace is now at generation {current_generation}; pages cannot partition the \
                 result set honestly across writes."
            ),
            repair: Some(
                "Re-run the command without --cursor to start a fresh page sequence.".to_owned(),
            ),
            details: None,
        }
    }

    /// `output_truncated_budget` (info): trailing items dropped to satisfy
    /// `--budget-tokens`. One truncation vocabulary across surfaces (ADR
    /// 0064 §5 supersedes the early `recall_budget_truncated` name); the
    /// recall budget lane reuses the governor code with recall-appropriate
    /// repair text and carries the shared `ee.cursor.v1` continuation cursor
    /// in `details`.
    #[must_use]
    pub fn budget_truncated(
        dropped_count: usize,
        continuation_cursor: &str,
        budget_tokens: u32,
    ) -> Self {
        Self {
            code: crate::output::governor::OUTPUT_TRUNCATED_BUDGET_CODE.to_owned(),
            severity: "info".to_owned(),
            message: format!(
                "Dropped {dropped_count} trailing item(s) at the declared truncation point to \
                 satisfy the recall budget of {budget_tokens} tokens."
            ),
            repair: Some(
                "Re-run with a larger --budget-tokens value, or resume from \
                 details.continuationCursor with --cursor."
                    .to_owned(),
            ),
            details: Some(serde_json::json!({
                "droppedCount": dropped_count,
                "continuationCursor": continuation_cursor,
            })),
        }
    }

    /// `output_budget_unsatisfiable` (medium): the recall item floor exceeds
    /// `--budget-tokens`, so no honest continuation cursor can reproduce the
    /// ranked set under the requested budget.
    #[must_use]
    pub fn budget_unsatisfiable(dropped_count: usize, budget_tokens: u32) -> Self {
        Self {
            code: crate::output::governor::OUTPUT_BUDGET_UNSATISFIABLE_CODE.to_owned(),
            severity: "medium".to_owned(),
            message: format!(
                "Recall budget unsatisfiable: dropped {dropped_count} item(s) because the next \
                 ranked item exceeds the recall budget of {budget_tokens} tokens."
            ),
            repair: Some(
                "Re-run with a larger --budget-tokens value, or omit the flag.".to_owned(),
            ),
            details: Some(serde_json::json!({
                "droppedCount": dropped_count,
                "budgetTokens": budget_tokens,
            })),
        }
    }

    /// Envelope-shaped JSON (`code`, `severity`, `message`, `repair`,
    /// optional `details`).
    #[must_use]
    pub fn to_json(&self) -> serde_json::Value {
        let mut entry = serde_json::json!({
            "code": self.code,
            "severity": self.severity,
            "message": self.message,
            "repair": self.repair,
        });
        if let Some(details) = &self.details
            && let Some(object) = entry.as_object_mut()
        {
            object.insert("details".to_owned(), details.clone());
        }
        entry
    }
}

/// The normalized query echoed back under `data.recall.query` (ADR 0064
/// appendix). Selector and filter fields only — offsets are cursor-internal.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RecallQueryEcho {
    pub paths: Vec<String>,
    pub symbols: Vec<String>,
    pub diff_ref: Option<String>,
    pub diff_staged: bool,
    pub kinds: Vec<String>,
    pub levels: Vec<String>,
    pub stale_only: bool,
    pub budget_tokens: Option<u32>,
}

/// Shared CLI/daemon orchestration, including cursor and degradation semantics.
pub fn recall_for_workspace(
    workspace_path: &std::path::Path,
    database_path: Option<&std::path::Path>,
    request: &RecallQueryEcho,
    cursor: Option<&str>,
) -> Result<(RecallReport, Vec<RecallDegradedEntry>), crate::models::DomainError> {
    use crate::models::DomainError;
    if request.paths.is_empty()
        && request.symbols.is_empty()
        && request.diff_ref.is_none()
        && !request.diff_staged
    {
        return Err(DomainError::Usage {
            message: "ee recall requires at least one selector: --path, --symbol, --diff, or --diff-staged".to_owned(),
            repair: Some("ee recall --path 'src/**' --workspace . --json".to_owned()),
        });
    }
    if request.budget_tokens == Some(0) {
        return Err(DomainError::Usage {
            message: "ee recall --budget-tokens must be greater than zero".to_owned(),
            repair: Some("Re-run with --budget-tokens 400 or omit the flag.".to_owned()),
        });
    }
    if request.diff_ref.is_some() && request.diff_staged {
        return Err(DomainError::Usage {
            message: "--diff and --diff-staged cannot be combined".to_owned(),
            repair: Some("Select one git diff mode.".to_owned()),
        });
    }
    let default_database = workspace_path.join(".ee").join("ee.db");
    let database_path = database_path.unwrap_or(&default_database);
    if !database_path.exists() {
        return Err(crate::core::storeless_workspace_error(database_path));
    }
    let storage_error = |message| DomainError::Storage {
        message,
        repair: Some("ee doctor --json".to_owned()),
    };
    let connection = crate::db::DbConnection::open_file(database_path).map_err(|error| {
        DomainError::Storage {
            message: format!("Failed to open database: {error}"),
            repair: Some("ee status --json".to_owned()),
        }
    })?;
    connection.migrate().map_err(|error| DomainError::Storage {
        message: format!("Failed to migrate database: {error}"),
        repair: Some("ee migrate run --workspace . --json".to_owned()),
    })?;
    let canonical = workspace_path
        .canonicalize()
        .unwrap_or_else(|_| workspace_path.to_path_buf());
    let workspace_id = crate::core::workspace::bound_workspace_id_or_hash(
        &connection,
        &crate::core::workspace::stable_workspace_id(&canonical),
        &[workspace_path, canonical.as_path()],
    )?;
    let mut extra_degraded = Vec::new();
    let diff_paths = if request.diff_ref.is_some() || request.diff_staged {
        match collect_diff_paths_via_git(
            workspace_path,
            request.diff_ref.as_deref(),
            request.diff_staged,
        ) {
            Ok(paths) => paths,
            Err(reason) => {
                extra_degraded.push(RecallDegradedEntry::git_unavailable(&reason));
                Vec::new()
            }
        }
    } else {
        Vec::new()
    };
    let mut query = RecallQuery {
        paths: request.paths.clone(),
        symbols: request.symbols.clone(),
        diff_paths,
        kinds: request.kinds.clone(),
        levels: request.levels.clone(),
        stale_only: request.stale_only,
        max_tokens: request.budget_tokens,
        offset: 0,
        stale_anchor_penalty: crate::search::scoring::DEFAULT_STALE_ANCHOR_PENALTY,
    };
    let db_generation = connection
        .get_workspace_generation(&workspace_id)
        .map_err(|error| storage_error(format!("Failed to read workspace generation: {error}")))?
        .map_or(0, |value| i64::try_from(value).unwrap_or(i64::MAX));
    let mut resume_cursor = None;
    let rejected = match resolve_recall_cursor(cursor, &query, db_generation) {
        RecallCursorResolution::Fresh => false,
        RecallCursorResolution::Resume {
            offset,
            dropped_count,
        } => {
            query.offset = offset;
            resume_cursor = Some((offset, dropped_count));
            false
        }
        RecallCursorResolution::RejectedInvalid => {
            extra_degraded.push(RecallDegradedEntry::cursor_invalid());
            true
        }
        RecallCursorResolution::RejectedStale {
            cursor_generation,
            current_generation,
        } => {
            extra_degraded.push(RecallDegradedEntry::cursor_stale(
                cursor_generation,
                current_generation,
            ));
            true
        }
    };
    let mut report = if rejected {
        let index_generation = connection
            .memory_anchor_index_generation(&workspace_id)
            .map_err(|error| {
                storage_error(format!("Failed to read anchor index generation: {error}"))
            })?;
        empty_recall_report_for_rejected_cursor(index_generation, db_generation)
    } else {
        run_recall(&connection, &workspace_id, &query)
            .map_err(|error| storage_error(format!("Failed to run recall: {error}")))?
    };
    if let Some((offset, dropped_count)) = resume_cursor
        && !recall_cursor_page_is_honest(offset, dropped_count, report.total_matched)
    {
        extra_degraded.push(RecallDegradedEntry::cursor_invalid());
        report =
            empty_recall_report_for_rejected_cursor(report.index_generation, report.db_generation);
    }
    let mut degraded: Vec<_> = report
        .degraded
        .iter()
        .map(RecallDegradedEntry::from_engine)
        .collect();
    degraded.append(&mut extra_degraded);
    if report.truncated
        && let Some(budget) = request.budget_tokens
    {
        degraded.push(match report.continuation_cursor.as_deref() {
            Some(cursor) => {
                RecallDegradedEntry::budget_truncated(report.dropped_count, cursor, budget)
            }
            None => RecallDegradedEntry::budget_unsatisfiable(report.dropped_count, budget),
        });
    }
    Ok((report, degraded))
}

/// Four-decimal score rounding for stable JSON output, mirroring the
/// CLI-wide `score_json_value` discipline.
fn score_json(value: f32) -> serde_json::Value {
    let rounded = (f64::from(value) * 10_000.0).round() / 10_000.0;
    serde_json::Number::from_f64(rounded).map_or(serde_json::Value::Null, serde_json::Value::Number)
}

fn recall_item_json(item: &RecallItem) -> serde_json::Value {
    serde_json::json!({
        "memoryId": item.memory_id,
        "anchor": {
            "kind": item.anchor.kind,
            "path": item.anchor.path,
            "symbol": item.anchor.symbol,
        },
        "freshnessState": item.freshness_state,
        "scoreComponents": {
            "freshness": score_json(item.score_components.freshness),
            "confidence": score_json(item.score_components.confidence),
            "levelTilt": score_json(item.score_components.level_tilt),
            "kindBonus": score_json(item.score_components.kind_bonus),
        },
        "score": score_json(item.score),
        "level": item.level,
        "kind": item.kind,
        "contentPreview": item.content_preview,
        "provenance": item.provenance.iter().map(|reference| serde_json::json!({
            "uri": reference.uri,
            "sourceType": reference.source_type,
        })).collect::<Vec<_>>(),
        "tags": item.tags,
        "repair": item.repair,
    })
}

/// Build the `data` payload for the `ee.response.v2` envelope:
/// `{"command": "recall", "recall": {…ee.recall.v1…}}`. The declared
/// governor truncation point is `data.recall.items[]`.
#[must_use]
pub fn recall_data_json(report: &RecallReport, query: &RecallQueryEcho) -> serde_json::Value {
    serde_json::json!({
        "command": "recall",
        "recall": {
            "schema": report.schema,
            "query": {
                "paths": query.paths,
                "symbols": query.symbols,
                "diffRef": query.diff_ref,
                "diffStaged": query.diff_staged,
                "kinds": query.kinds,
                "levels": query.levels,
                "staleOnly": query.stale_only,
                "budgetTokens": query.budget_tokens,
            },
            "items": report.items.iter().map(recall_item_json).collect::<Vec<_>>(),
            "indexGeneration": report.index_generation,
            "dbGeneration": report.db_generation,
            "totalMatched": report.total_matched,
            "truncated": report.truncated,
            "droppedCount": report.dropped_count,
            "continuationCursor": report.continuation_cursor,
        },
    })
}

/// Render the token-tight markdown prepend block (pack markdown discipline:
/// smallest output, provenance per item, repair hints on stale items).
#[must_use]
pub fn render_recall_markdown(report: &RecallReport, degraded: &[RecallDegradedEntry]) -> String {
    let mut output = String::new();
    if report.truncated {
        output.push_str(&format!(
            "## recall · {} of {} anchored memories ({} dropped by budget)\n",
            report.items.len(),
            report.total_matched,
            report.dropped_count
        ));
    } else {
        output.push_str(&format!(
            "## recall · {} anchored memorie(s)\n",
            report.items.len()
        ));
    }
    for (rank, item) in report.items.iter().enumerate() {
        let anchor_display = item
            .anchor
            .path
            .as_deref()
            .or(item.anchor.symbol.as_deref())
            .unwrap_or("-");
        output.push_str(&format!(
            "\n{}. {} · {} · {}/{} · {}\n   {}\n",
            rank + 1,
            item.memory_id,
            anchor_display,
            item.level,
            item.kind,
            item.freshness_state,
            item.content_preview
        ));
        if !item.provenance.is_empty() {
            let uris: Vec<&str> = item
                .provenance
                .iter()
                .map(|reference| reference.uri.as_str())
                .collect();
            output.push_str(&format!("   src: {}\n", uris.join(", ")));
        }
        if let Some(repair) = &item.repair {
            output.push_str(&format!("   repair: {repair}\n"));
        }
    }
    for entry in degraded {
        match &entry.repair {
            Some(repair) => {
                output.push_str(&format!("\ndegraded: {} ({})\n", entry.code, repair));
            }
            None => output.push_str(&format!("\ndegraded: {}\n", entry.code)),
        }
    }
    output
}

/// Build the empty page returned when a continuation cursor is rejected.
/// Generations are reported honestly; items stay empty so a rejected cursor
/// can never duplicate or skip elements of a prior page sequence.
#[must_use]
pub fn empty_recall_report_for_rejected_cursor(
    index_generation: Option<i64>,
    db_generation: i64,
) -> RecallReport {
    RecallReport {
        schema: RECALL_SCHEMA_V1,
        items: Vec::new(),
        index_generation,
        db_generation,
        degraded: Vec::new(),
        total_matched: 0,
        truncated: false,
        dropped_count: 0,
        continuation_cursor: None,
    }
}

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

    fn sample_item() -> RecallItem {
        RecallItem {
            memory_id: "mem_00000000000000000000000001".to_owned(),
            anchor: RecallAnchor {
                kind: "path".to_owned(),
                path: Some("src/db/mod.rs".to_owned()),
                symbol: None,
            },
            freshness_state: "current".to_owned(),
            score_components: RecallScoreComponents {
                freshness: 1.0,
                confidence: 0.8,
                level_tilt: 1.0,
                kind_bonus: 1.0,
            },
            score: 0.8,
            level: "procedural".to_owned(),
            kind: "rule".to_owned(),
            content_preview: "Always run the verify script.".to_owned(),
            provenance: vec![RecallProvenanceRef {
                uri: "test://prov".to_owned(),
                source_type: "memory_provenance".to_owned(),
            }],
            tags: vec!["ci".to_owned()],
            repair: None,
        }
    }

    fn sample_report(items: Vec<RecallItem>) -> RecallReport {
        let total_matched = items.len();
        RecallReport {
            schema: RECALL_SCHEMA_V1,
            items,
            index_generation: Some(7),
            db_generation: 7,
            degraded: Vec::new(),
            total_matched,
            truncated: false,
            dropped_count: 0,
            continuation_cursor: None,
        }
    }

    #[test]
    fn cursor_resolution_fresh_resume_invalid_stale() {
        let query = RecallQuery {
            paths: vec!["src/db/mod.rs".to_owned()],
            ..RecallQuery::default()
        };
        assert_eq!(
            resolve_recall_cursor(None, &query, 7),
            RecallCursorResolution::Fresh
        );

        let cursor = encode_recall_cursor(&query, 3, 1, 7).expect("cursor encodes");
        assert_eq!(
            resolve_recall_cursor(Some(cursor.as_str()), &query, 7),
            RecallCursorResolution::Resume {
                offset: 3,
                dropped_count: 1,
            }
        );
        assert_eq!(
            resolve_recall_cursor(Some("garbage"), &query, 7),
            RecallCursorResolution::RejectedInvalid
        );
        assert_eq!(
            resolve_recall_cursor(Some(cursor.as_str()), &query, 9),
            RecallCursorResolution::RejectedStale {
                cursor_generation: 7,
                current_generation: 9,
            }
        );
        // A cursor bound to a different query is invalid, not stale.
        let other_query = RecallQuery {
            paths: vec!["src/core/recall.rs".to_owned()],
            ..RecallQuery::default()
        };
        assert_eq!(
            resolve_recall_cursor(Some(cursor.as_str()), &other_query, 7),
            RecallCursorResolution::RejectedInvalid
        );
    }

    #[test]
    fn data_json_shape_matches_adr_appendix() {
        let report = sample_report(vec![sample_item()]);
        let query = RecallQueryEcho {
            paths: vec!["src/db/*.rs".to_owned()],
            ..RecallQueryEcho::default()
        };
        let data = recall_data_json(&report, &query);
        assert_eq!(data["command"], "recall");
        let recall = &data["recall"];
        assert_eq!(recall["schema"], RECALL_SCHEMA_V1);
        assert_eq!(recall["query"]["paths"][0], "src/db/*.rs");
        assert_eq!(recall["query"]["staleOnly"], false);
        assert_eq!(recall["items"][0]["memoryId"], sample_item().memory_id);
        assert_eq!(recall["items"][0]["anchor"]["path"], "src/db/mod.rs");
        assert_eq!(recall["items"][0]["scoreComponents"]["confidence"], 0.8);
        assert_eq!(recall["indexGeneration"], 7);
        assert_eq!(recall["dbGeneration"], 7);
        assert_eq!(recall["truncated"], false);
        assert_eq!(recall["continuationCursor"], serde_json::Value::Null);
    }

    #[test]
    fn markdown_block_is_token_tight_with_provenance_and_degraded() {
        let mut stale = sample_item();
        stale.memory_id = "mem_00000000000000000000000002".to_owned();
        stale.freshness_state = "stale".to_owned();
        stale.repair =
            Some("ee why mem_00000000000000000000000002 --workspace . --json".to_owned());
        let report = sample_report(vec![sample_item(), stale]);
        let degraded = vec![RecallDegradedEntry::from_engine(&RecallDegradation {
            code: ANCHOR_INDEX_STALE_CODE,
            severity: "low",
            message: "behind".to_owned(),
            repair: Some(ANCHOR_INDEX_REPAIR.to_owned()),
        })];
        let markdown = render_recall_markdown(&report, &degraded);
        assert!(markdown.starts_with("## recall · 2 anchored memorie(s)\n"));
        assert!(markdown.contains("1. mem_00000000000000000000000001 · src/db/mod.rs"));
        assert!(markdown.contains("src: test://prov"));
        assert!(markdown.contains("repair: ee why mem_00000000000000000000000002"));
        assert!(markdown.contains("degraded: anchor_index_stale (ee index rebuild"));
    }

    #[test]
    fn markdown_block_reports_budget_truncation_counts() {
        let mut report = sample_report(vec![sample_item()]);
        report.total_matched = 5;
        report.truncated = true;
        report.dropped_count = 4;
        let markdown = render_recall_markdown(&report, &[]);
        assert!(markdown.starts_with("## recall · 1 of 5 anchored memories (4 dropped by budget)"));
    }

    #[test]
    fn budget_truncated_entry_carries_cursor_details() {
        let entry = RecallDegradedEntry::budget_truncated(4, "cursor-string", 400);
        assert_eq!(
            entry.code,
            crate::output::governor::OUTPUT_TRUNCATED_BUDGET_CODE
        );
        assert_eq!(entry.severity, "info");
        let json = entry.to_json();
        assert_eq!(json["details"]["droppedCount"], 4);
        assert_eq!(json["details"]["continuationCursor"], "cursor-string");
    }

    #[test]
    fn budget_unsatisfiable_entry_carries_repair_details() {
        let entry = RecallDegradedEntry::budget_unsatisfiable(4, 1);
        assert_eq!(
            entry.code,
            crate::output::governor::OUTPUT_BUDGET_UNSATISFIABLE_CODE
        );
        assert_eq!(entry.severity, "medium");
        let json = entry.to_json();
        assert_eq!(json["details"]["droppedCount"], 4);
        assert_eq!(json["details"]["budgetTokens"], 1);
    }

    #[test]
    fn git_ref_validation_rejects_option_shaped_refs() {
        let workspace = std::path::Path::new(".");
        let result = collect_diff_paths_via_git(workspace, Some("--output=/tmp/x"), false);
        assert!(result.is_err());
        let result = collect_diff_paths_via_git(workspace, Some(""), false);
        assert!(result.is_err());
    }
}

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

    fn row(memory_id: &str, path: Option<&str>, symbol: Option<&str>) -> RecallCandidateRow {
        RecallCandidateRow {
            memory_id: memory_id.to_owned(),
            anchor_kind: if path.is_some() {
                MemoryAnchorKind::Path
            } else {
                MemoryAnchorKind::Symbol
            },
            normalized_path: path.map(str::to_owned),
            symbol: symbol.map(str::to_owned),
            freshness_state: MemoryAnchorFreshnessState::Current,
            row_generation: 7,
            level: "procedural".to_owned(),
            kind: "rule".to_owned(),
            confidence: 0.8,
            content: "Always run the verify script before pushing.".to_owned(),
            tombstoned: false,
            tags: vec!["ci".to_owned()],
            provenance: vec![RecallProvenanceRef {
                uri: "test://prov".to_owned(),
                source_type: "test".to_owned(),
            }],
        }
    }

    fn path_query(globs: &[&str]) -> RecallQuery {
        RecallQuery {
            paths: globs.iter().map(|glob| (*glob).to_owned()).collect(),
            ..RecallQuery::default()
        }
    }

    #[test]
    fn glob_matching_edges() {
        // Empty glob matches nothing real.
        assert!(!recall_glob_match("", "src/db/mod.rs"));
        assert!(recall_glob_match("", ""));
        // Exact, star (crossing `/`), question mark, char classes.
        assert!(recall_glob_match("src/db/mod.rs", "src/db/mod.rs"));
        assert!(recall_glob_match("src/*.rs", "src/db/mod.rs"));
        assert!(recall_glob_match("src/**", "src/core/recall.rs"));
        assert!(recall_glob_match("src/db/mod.r?", "src/db/mod.rs"));
        assert!(recall_glob_match("src/[cd]b/mod.rs", "src/db/mod.rs"));
        assert!(recall_glob_match("src/[!x]b/mod.rs", "src/db/mod.rs"));
        assert!(!recall_glob_match("src/[!d]b/mod.rs", "src/db/mod.rs"));
        assert!(recall_glob_match(
            "tests/[a-f]ixture.rs",
            "tests/fixture.rs"
        ));
        // Case sensitivity is preserved.
        assert!(!recall_glob_match("SRC/*.rs", "src/db/mod.rs"));
        // Trailing-star and star-only forms.
        assert!(recall_glob_match("*", "anything/at/all.rs"));
        assert!(!recall_glob_match("src/*.toml", "src/db/mod.rs"));
        // Unterminated class falls back to literal `[`.
        assert!(recall_glob_match("src/[ab", "src/[ab"));
        assert!(!recall_glob_match("src/[ab", "src/a"));
    }

    #[test]
    fn path_selector_normalization() {
        assert_eq!(
            normalize_recall_path_selector("./src/db/mod.rs"),
            "src/db/mod.rs"
        );
        assert_eq!(
            normalize_recall_path_selector("src/db/mod.rs"),
            "src/db/mod.rs"
        );
        // Absolute selectors stay as-is and simply never match the
        // workspace-relative index.
        assert_eq!(normalize_recall_path_selector("/etc/passwd"), "/etc/passwd");
        let rows = vec![row("mem_a", Some("src/db/mod.rs"), None)];
        let report = evaluate_recall(&path_query(&["/src/db/mod.rs"]), &rows, Some(7), 7);
        assert!(report.items.is_empty());
    }

    #[test]
    fn diff_path_parsing_handles_both_forms() {
        let name_only = "src/db/mod.rs\nsrc/core/recall.rs\n\nsrc/db/mod.rs\n";
        assert_eq!(
            diff_changed_paths(name_only),
            vec!["src/core/recall.rs".to_owned(), "src/db/mod.rs".to_owned()]
        );
        let unified = "diff --git a/src/db/mod.rs b/src/db/mod.rs\nindex 111..222 100644\n--- a/src/db/mod.rs\n+++ b/src/db/mod.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context\ndiff --git a/gone.rs b/gone.rs\n--- a/gone.rs\n+++ /dev/null\n";
        assert_eq!(
            diff_changed_paths(unified),
            vec!["src/db/mod.rs".to_owned()]
        );
    }

    #[test]
    fn unified_diff_metadata_lines_are_not_paths() {
        let unified = concat!(
            "diff --git a/src/new.rs b/src/new.rs\n",
            "new file mode 100644\n",
            "index 0000000..1111111\n",
            "--- /dev/null\n",
            "+++ b/src/new.rs\n",
            "@@ -0,0 +1 @@\n",
            "+pub fn new_file() {}\n",
            "diff --git a/src/old_name.rs b/src/renamed.rs\n",
            "similarity index 87%\n",
            "rename from src/old_name.rs\n",
            "rename to src/renamed.rs\n",
            "--- a/src/old_name.rs\n",
            "+++ b/src/renamed.rs\n",
            "@@ -1 +1 @@\n",
            "-old\n",
            "+new\n",
            "diff --git a/assets/logo.bin b/assets/logo.bin\n",
            "Binary files a/assets/logo.bin and b/assets/logo.bin differ\n",
            "diff --git a/src/mode_only.rs b/src/mode_only.rs\n",
            "old mode 100644\n",
            "new mode 100755\n",
            "diff --git a/src/deleted.rs b/src/deleted.rs\n",
            "deleted file mode 100644\n",
            "--- a/src/deleted.rs\n",
            "+++ /dev/null\n",
        );

        assert_eq!(
            diff_changed_paths(unified),
            vec!["src/new.rs".to_owned(), "src/renamed.rs".to_owned()]
        );
    }

    #[test]
    fn diff_name_only_parsing_keeps_hunk_like_filenames() {
        let name_only = "+added.rs\n-removed.rs\n leading-space.rs\n\\literal.rs\n";

        assert_eq!(
            diff_name_only_changed_paths(name_only),
            vec![
                " leading-space.rs".to_owned(),
                "+added.rs".to_owned(),
                "-removed.rs".to_owned(),
                "\\literal.rs".to_owned(),
            ]
        );
        assert_eq!(
            diff_changed_paths(name_only),
            diff_name_only_changed_paths(name_only)
        );
    }

    #[test]
    fn ranking_is_deterministic_with_stable_tie_breaks() {
        let mut first = row("mem_b", Some("src/a.rs"), None);
        let mut second = row("mem_a", Some("src/b.rs"), None);
        // Identical scores -> ascending memory id.
        first.confidence = 0.8;
        second.confidence = 0.8;
        let rows = vec![first.clone(), second.clone()];
        let report = evaluate_recall(&path_query(&["src/*.rs"]), &rows, Some(7), 7);
        let ids: Vec<&str> = report
            .items
            .iter()
            .map(|item| item.memory_id.as_str())
            .collect();
        assert_eq!(ids, vec!["mem_a", "mem_b"]);
        // Same inputs -> identical report (determinism).
        let again = evaluate_recall(&path_query(&["src/*.rs"]), &rows, Some(7), 7);
        assert_eq!(report, again);
        // Reversed input order does not change ranking.
        let reversed = evaluate_recall(&path_query(&["src/*.rs"]), &[second, first], Some(7), 7);
        assert_eq!(report, reversed);
    }

    #[test]
    fn scoring_follows_adr_objective() {
        let mut warning = row("mem_warn", Some("src/a.rs"), None);
        warning.kind = "failure".to_owned();
        warning.level = "episodic".to_owned();
        warning.confidence = 0.5;
        warning.freshness_state = MemoryAnchorFreshnessState::Suspect;
        let report = evaluate_recall(&path_query(&["src/*.rs"]), &[warning], Some(7), 7);
        let item = &report.items[0];
        assert!((item.score_components.freshness - 1.0).abs() < 1e-6);
        assert!((item.score_components.confidence - 0.5).abs() < 1e-6);
        assert!((item.score_components.level_tilt - 0.6).abs() < 1e-6);
        assert!((item.score_components.kind_bonus - 1.15).abs() < 1e-6);
        let expected = 1.0 * 0.5 * 0.6 * 1.15;
        assert!((item.score - expected).abs() < 1e-6);
        // Suspect/stale items carry a repair hint.
        assert_eq!(
            item.repair.as_deref(),
            Some("ee why mem_warn --workspace . --json")
        );
    }

    #[test]
    fn tombstoned_memories_are_excluded() {
        let mut dead = row("mem_dead", Some("src/a.rs"), None);
        dead.tombstoned = true;
        let live = row("mem_live", Some("src/a.rs"), None);
        let report = evaluate_recall(&path_query(&["src/*.rs"]), &[dead, live], Some(7), 7);
        let ids: Vec<&str> = report
            .items
            .iter()
            .map(|item| item.memory_id.as_str())
            .collect();
        assert_eq!(ids, vec!["mem_live"]);
    }

    #[test]
    fn dedup_keeps_freshest_anchor_per_memory() {
        let mut stale_path = row("mem_a", Some("src/a.rs"), None);
        stale_path.freshness_state = MemoryAnchorFreshnessState::Stale;
        let mut fresh_symbol = row("mem_a", None, Some("Recall::run"));
        fresh_symbol.anchor_kind = MemoryAnchorKind::Symbol;
        let query = RecallQuery {
            paths: vec!["src/*.rs".to_owned()],
            symbols: vec!["Recall::run".to_owned()],
            ..RecallQuery::default()
        };
        let report = evaluate_recall(&query, &[stale_path, fresh_symbol], Some(7), 7);
        assert_eq!(report.items.len(), 1);
        assert_eq!(report.items[0].anchor.kind, "symbol");
        assert_eq!(report.items[0].freshness_state, "current");
    }

    #[test]
    fn drifted_anchor_is_flagged_not_penalized_by_default() {
        // bd-2vq2z.1 (Phase-6 pass 2): with the default stale_anchor_penalty of
        // 0.0, a stale-anchored memory keeps the SAME freshness multiplier (and
        // therefore the same score, all else equal) as a current one. The drift
        // is surfaced via `freshness_state`, never by suppressing the rank.
        let mut stale = row("mem_stale", Some("src/a.rs"), None);
        stale.freshness_state = MemoryAnchorFreshnessState::Stale;
        let current = row("mem_current", Some("src/a.rs"), None);

        let report = evaluate_recall(
            &path_query(&["src/*.rs"]),
            &[stale.clone(), current.clone()],
            Some(7),
            7,
        );
        let stale_item = report
            .items
            .iter()
            .find(|item| item.memory_id == "mem_stale")
            .expect("stale memory present (flagged, not suppressed)");
        let current_item = report
            .items
            .iter()
            .find(|item| item.memory_id == "mem_current")
            .expect("current memory present");
        assert_eq!(
            stale_item.freshness_state, "stale",
            "the drift is still surfaced as a flag"
        );
        assert_eq!(
            stale_item.score_components.freshness, 1.0,
            "default penalty 0.0 -> neutral freshness multiplier (flag, don't penalize)"
        );
        assert_eq!(
            stale_item.score_components.freshness, current_item.score_components.freshness,
            "a drifted memory keeps its rank under the default config"
        );
    }

    #[test]
    fn default_stale_anchor_survives_tight_budget_tie() {
        // Under the default "flag, don't penalize" policy, a stale anchor can
        // still win a deterministic tie and survive a one-item recall budget.
        let mut stale = row("mem_a_stale", Some("src/a.rs"), None);
        stale.freshness_state = MemoryAnchorFreshnessState::Stale;
        let current = row("mem_b_current", Some("src/a.rs"), None);
        let rows = vec![stale, current];

        let mut query = path_query(&["src/*.rs"]);
        let unbounded = evaluate_recall(&query, &rows, Some(7), 7);
        assert_eq!(unbounded.items.len(), 2);
        assert_eq!(unbounded.items[0].memory_id, "mem_a_stale");
        assert_eq!(unbounded.items[0].score_components.freshness, 1.0);

        let per_item_budget =
            u32::try_from(recall_item_token_estimate(&unbounded.items[0])).expect("budget fits");
        query.max_tokens = Some(per_item_budget);
        let tight = evaluate_recall(&query, &rows, Some(7), 7);
        assert_eq!(tight.items.len(), 1);
        assert_eq!(tight.items[0].memory_id, "mem_a_stale");
        assert_eq!(tight.items[0].freshness_state, "stale");
        assert!(tight.truncated);
    }

    #[test]
    fn opt_in_stale_anchor_penalty_ranks_drift_down_without_vanishing() {
        // An operator may opt into a small tie-breaker. With a configured penalty
        // the stale anchor ranks below an otherwise-identical fresh one, but its
        // score stays strictly positive (it never vanishes).
        let mut stale = row("mem_stale", Some("src/a.rs"), None);
        stale.freshness_state = MemoryAnchorFreshnessState::Stale;
        let current = row("mem_current", Some("src/a.rs"), None);

        let mut query = path_query(&["src/*.rs"]);
        query.stale_anchor_penalty = 0.6;
        let report = evaluate_recall(&query, &[stale.clone(), current.clone()], Some(7), 7);
        let stale_item = report
            .items
            .iter()
            .find(|item| item.memory_id == "mem_stale")
            .expect("stale memory present");
        let current_item = report
            .items
            .iter()
            .find(|item| item.memory_id == "mem_current")
            .expect("current memory present");
        assert!(
            stale_item.score < current_item.score,
            "an opt-in penalty ranks the drifted memory below the fresh one"
        );
        assert!(stale_item.score > 0.0, "penalized but never vanishes");
        // Ordering: the fresh memory sorts first.
        assert_eq!(report.items[0].memory_id, "mem_current");
    }

    #[test]
    fn invalid_stale_anchor_penalty_is_neutral_in_recall() {
        let mut stale = row("mem_stale", Some("src/a.rs"), None);
        stale.freshness_state = MemoryAnchorFreshnessState::Stale;
        let current = row("mem_current", Some("src/a.rs"), None);

        for invalid_penalty in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.25] {
            let mut query = path_query(&["src/*.rs"]);
            query.stale_anchor_penalty = invalid_penalty;
            let report = evaluate_recall(&query, &[stale.clone(), current.clone()], Some(7), 7);
            let stale_item = report
                .items
                .iter()
                .find(|item| item.memory_id == "mem_stale")
                .expect("stale memory present");
            let current_item = report
                .items
                .iter()
                .find(|item| item.memory_id == "mem_current")
                .expect("current memory present");
            assert_eq!(
                stale_item.score_components.freshness, 1.0,
                "invalid penalty {invalid_penalty:?} stays neutral"
            );
            assert_eq!(
                stale_item.score, current_item.score,
                "invalid penalty {invalid_penalty:?} must not silently demote stale anchors"
            );
        }
    }

    #[test]
    fn filters_compose_conjunctively_and_emit_filtered_empty() {
        let rows = vec![row("mem_a", Some("src/a.rs"), None)];
        let mut query = path_query(&["src/*.rs"]);
        query.kinds = vec!["failure".to_owned()];
        let report = evaluate_recall(&query, &rows, Some(7), 7);
        assert!(report.items.is_empty());
        assert_eq!(report.degraded.len(), 1);
        assert_eq!(report.degraded[0].code, RECALL_FILTERED_EMPTY_CODE);
        assert_eq!(report.degraded[0].severity, "info");
    }

    #[test]
    fn empty_index_and_stale_index_emit_distinct_codes() {
        let empty = evaluate_recall(&path_query(&["src/*.rs"]), &[], None, 5);
        assert_eq!(empty.degraded.len(), 1);
        assert_eq!(empty.degraded[0].code, ANCHOR_INDEX_EMPTY_CODE);
        assert_eq!(empty.degraded[0].severity, "info");
        assert_eq!(
            empty.degraded[0].repair,
            Some(ANCHOR_INDEX_REPAIR.to_owned())
        );

        let rows = vec![row("mem_a", Some("src/a.rs"), None)];
        let stale = evaluate_recall(&path_query(&["src/*.rs"]), &rows, Some(3), 5);
        assert_eq!(stale.degraded.len(), 1);
        assert_eq!(stale.degraded[0].code, ANCHOR_INDEX_STALE_CODE);
        assert_eq!(stale.degraded[0].severity, "low");
        assert_eq!(
            stale.degraded[0].repair,
            Some(ANCHOR_INDEX_REPAIR.to_owned())
        );
        // Stale detection never blocks results.
        assert_eq!(stale.items.len(), 1);

        let current = evaluate_recall(&path_query(&["src/*.rs"]), &rows, Some(5), 5);
        assert!(current.degraded.is_empty());
    }

    #[test]
    fn budget_truncation_boundaries() {
        let rows: Vec<RecallCandidateRow> = (0..4)
            .map(|index| row(&format!("mem_{index}"), Some("src/a.rs"), None))
            .collect();
        let unbounded = evaluate_recall(&path_query(&["src/*.rs"]), &rows, Some(7), 7);
        assert_eq!(unbounded.items.len(), 4);
        assert!(!unbounded.truncated);
        assert!(unbounded.continuation_cursor.is_none());

        let per_item = recall_item_token_estimate(&unbounded.items[0]);
        assert!(per_item > 0);

        // Zero budget: nothing fits, everything dropped. The public CLI
        // rejects this upfront, but the pure core still must not mint a
        // same-offset cursor that would loop forever if a caller bypassed the
        // CLI guard.
        let mut query = path_query(&["src/*.rs"]);
        query.max_tokens = Some(0);
        let zero = evaluate_recall(&query, &rows, Some(7), 7);
        assert!(zero.items.is_empty());
        assert_eq!(zero.dropped_count, 4);
        assert!(zero.truncated);
        assert!(zero.continuation_cursor.is_none());

        // Exactly-fits: all four kept, no cursor.
        let exact_budget = u32::try_from(per_item * 4).expect("budget fits in u32");
        query.max_tokens = Some(exact_budget);
        let exact = evaluate_recall(&query, &rows, Some(7), 7);
        assert_eq!(exact.items.len(), 4);
        assert!(!exact.truncated);
        assert!(exact.continuation_cursor.is_none());

        // One token short: a strict prefix is kept, the rest dropped.
        query.max_tokens = Some(exact_budget - 1);
        let short = evaluate_recall(&query, &rows, Some(7), 7);
        assert_eq!(short.items.len(), 3);
        assert_eq!(short.dropped_count, 1);
        assert!(short.truncated);
        // Smaller budget yields a strict prefix of the larger budget's items.
        assert_eq!(short.items[..], exact.items[..3],);
    }

    #[test]
    fn continuation_cursor_round_trip_and_paging() {
        let rows: Vec<RecallCandidateRow> = (0..4)
            .map(|index| row(&format!("mem_{index}"), Some("src/a.rs"), None))
            .collect();
        let mut query = path_query(&["src/*.rs"]);
        let per_item = {
            let probe = evaluate_recall(&query, &rows, Some(7), 7);
            recall_item_token_estimate(&probe.items[0])
        };
        query.max_tokens = Some(u32::try_from(per_item * 2).expect("budget fits"));
        let first_page = evaluate_recall(&query, &rows, Some(7), 7);
        assert_eq!(first_page.items.len(), 2);
        assert_eq!(first_page.dropped_count, 2);
        let encoded = first_page
            .continuation_cursor
            .clone()
            .expect("cursor present");

        assert_eq!(
            resolve_recall_cursor(Some(encoded.as_str()), &query, 7),
            RecallCursorResolution::Resume {
                offset: 2,
                dropped_count: 2,
            }
        );

        let mut second_query = query.clone();
        second_query.offset = 2;
        let second_page = evaluate_recall(&second_query, &rows, Some(7), 7);
        assert_eq!(second_page.items.len(), 2);
        assert!(!second_page.truncated);
        // Pages partition the ranked list without overlap.
        let first_ids: Vec<&str> = first_page
            .items
            .iter()
            .map(|item| item.memory_id.as_str())
            .collect();
        let second_ids: Vec<&str> = second_page
            .items
            .iter()
            .map(|item| item.memory_id.as_str())
            .collect();
        assert_eq!(first_ids, vec!["mem_0", "mem_1"]);
        assert_eq!(second_ids, vec!["mem_2", "mem_3"]);
    }

    #[test]
    fn cursor_rejects_tamper_query_mismatch_and_stale_generation() {
        let query = RecallQuery {
            paths: vec!["src/db/mod.rs".to_owned()],
            ..RecallQuery::default()
        };
        let encoded = encode_recall_cursor(&query, 2, 1, 7).expect("cursor encodes");
        // Round-trips against the same query and generation.
        assert_eq!(
            resolve_recall_cursor(Some(encoded.as_str()), &query, 7),
            RecallCursorResolution::Resume {
                offset: 2,
                dropped_count: 1,
            }
        );

        // Tampered wire form -> BLAKE3 MAC fails -> invalid (never a silent
        // resume of a forged offset).
        let tampered = match encoded.strip_prefix('A') {
            Some(rest) => format!("B{rest}"),
            None => format!("A{}", &encoded[1..]),
        };
        assert_eq!(
            resolve_recall_cursor(Some(tampered.as_str()), &query, 7),
            RecallCursorResolution::RejectedInvalid
        );
        assert_eq!(
            resolve_recall_cursor(Some("garbage"), &query, 7),
            RecallCursorResolution::RejectedInvalid
        );

        // Wrong query -> invalid (paramsHash mismatch), not stale.
        let other_query = RecallQuery {
            paths: vec!["src/core/recall.rs".to_owned()],
            ..RecallQuery::default()
        };
        assert_eq!(
            resolve_recall_cursor(Some(encoded.as_str()), &other_query, 7),
            RecallCursorResolution::RejectedInvalid
        );

        // Generation moved forward -> stale rejection, never silent reordering.
        assert_eq!(
            resolve_recall_cursor(Some(encoded.as_str()), &query, 9),
            RecallCursorResolution::RejectedStale {
                cursor_generation: 7,
                current_generation: 9,
            }
        );
        // Same query and generation still validates.
        assert_eq!(
            resolve_recall_cursor(Some(encoded.as_str()), &query, 7),
            RecallCursorResolution::Resume {
                offset: 2,
                dropped_count: 1,
            }
        );
    }

    #[test]
    fn cursor_honesty_requires_offset_and_dropped_count_to_match_total() {
        assert!(recall_cursor_page_is_honest(2, 2, 4));
        assert!(!recall_cursor_page_is_honest(0, 4, 4));
        assert!(!recall_cursor_page_is_honest(3, 2, 4));
        assert!(!recall_cursor_page_is_honest(2, 1, 4));
        assert!(!recall_cursor_page_is_honest(4, 0, 4));

        let query = path_query(&["src/*.rs"]);
        let cursor = encode_recall_cursor(&query, 3, 99, 7).expect("cursor encodes");
        let RecallCursorResolution::Resume {
            offset,
            dropped_count,
        } = resolve_recall_cursor(Some(cursor.as_str()), &query, 7)
        else {
            panic!("cursor should authenticate before honesty check");
        };
        assert_eq!(offset, 3);
        assert_eq!(dropped_count, 99);
        assert!(!recall_cursor_page_is_honest(offset, dropped_count, 4));
    }

    #[test]
    fn query_hash_is_order_insensitive_and_budget_insensitive() {
        let base = RecallQuery {
            paths: vec!["src/*.rs".to_owned(), "docs/*.md".to_owned()],
            symbols: vec!["A::b".to_owned()],
            ..RecallQuery::default()
        };
        let mut reordered = base.clone();
        reordered.paths.reverse();
        assert_eq!(recall_query_hash(&base), recall_query_hash(&reordered));
        let mut budgeted = base.clone();
        budgeted.max_tokens = Some(100);
        budgeted.offset = 2;
        assert_eq!(recall_query_hash(&base), recall_query_hash(&budgeted));
        let mut different = base;
        different.stale_only = true;
        assert_ne!(recall_query_hash(&different), recall_query_hash(&reordered));
    }

    #[test]
    fn stale_only_filters_and_keeps_repair_hints() {
        let current = row("mem_current", Some("src/a.rs"), None);
        let mut suspect = row("mem_suspect", Some("src/a.rs"), None);
        suspect.freshness_state = MemoryAnchorFreshnessState::Suspect;
        let mut query = path_query(&["src/*.rs"]);
        query.stale_only = true;
        let report = evaluate_recall(&query, &[current, suspect], Some(7), 7);
        assert_eq!(report.items.len(), 1);
        assert_eq!(report.items[0].memory_id, "mem_suspect");
        assert!(report.items[0].repair.is_some());
    }

    #[test]
    fn content_preview_is_single_line_and_bounded() {
        let multiline = "first line\nsecond   line\tthird";
        assert_eq!(
            recall_content_preview(multiline),
            "first line second line third"
        );
        let long = "word ".repeat(100);
        let preview = recall_content_preview(&long);
        assert!(preview.chars().count() <= RECALL_CONTENT_PREVIEW_MAX_CHARS);
        assert!(preview.ends_with('…'));
        // Multibyte safety: truncation respects char boundaries.
        let unicode = "é".repeat(500);
        let unicode_preview = recall_content_preview(&unicode);
        assert_eq!(
            unicode_preview.chars().count(),
            RECALL_CONTENT_PREVIEW_MAX_CHARS
        );
    }

    #[test]
    fn no_selectors_match_nothing_deterministically() {
        let rows = vec![row("mem_a", Some("src/a.rs"), None)];
        let report = evaluate_recall(&RecallQuery::default(), &rows, Some(7), 7);
        assert!(report.items.is_empty());
        assert_eq!(report.total_matched, 0);
        // No surface was requested, so no filtered-empty degradation either.
        assert!(report.degraded.is_empty());
    }

    fn wrapper_test_db() -> (crate::db::DbConnection, String) {
        let connection = crate::db::DbConnection::open_memory().expect("open in-memory db");
        connection.migrate().expect("migrate");
        let workspace_id = format!("wsp_{:026}", 1);
        connection
            .insert_workspace(
                &workspace_id,
                &crate::db::CreateWorkspaceInput {
                    path: "/recall-wrapper-test".to_owned(),
                    name: Some("recall-wrapper-test".to_owned()),
                },
            )
            .expect("insert workspace");
        (connection, workspace_id)
    }

    fn wrapper_test_file_db() -> (tempfile::TempDir, crate::db::DbConnection, String) {
        let temp = tempfile::tempdir().expect("tempdir");
        let workspace_path = temp.path().canonicalize().expect("canonical workspace");
        std::fs::create_dir_all(workspace_path.join(".ee")).expect("create .ee");
        let database_path = workspace_path.join(".ee").join("ee.db");
        let connection = crate::db::DbConnection::open_file(&database_path).expect("open file db");
        connection.migrate().expect("migrate");
        let workspace_id = format!("wsp_{:026}", 2);
        connection
            .insert_workspace(
                &workspace_id,
                &crate::db::CreateWorkspaceInput {
                    path: workspace_path.to_string_lossy().into_owned(),
                    name: Some("recall-file-wrapper-test".to_owned()),
                },
            )
            .expect("insert workspace");
        (temp, connection, workspace_id)
    }

    fn wrapper_insert_memory(
        connection: &crate::db::DbConnection,
        workspace_id: &str,
        id: &str,
        content: &str,
    ) {
        connection
            .insert_memory(
                id,
                &crate::db::CreateMemoryInput {
                    workspace_id: workspace_id.to_owned(),
                    level: "procedural".to_owned(),
                    kind: "rule".to_owned(),
                    content: content.to_owned(),
                    workflow_id: None,
                    confidence: 0.9,
                    utility: 0.8,
                    importance: 0.7,
                    provenance_uri: Some("test://recall-wrapper".to_owned()),
                    trust_class: "human_explicit".to_owned(),
                    trust_subclass: None,
                    tags: vec!["recall-test".to_owned()],
                    valid_from: None,
                    valid_to: None,
                },
            )
            .expect("insert memory");
    }

    #[test]
    fn run_recall_round_trips_through_the_reverse_index() {
        let (connection, workspace_id) = wrapper_test_db();
        let memory_id = format!("mem_{:026}", 1);
        wrapper_insert_memory(
            &connection,
            &workspace_id,
            &memory_id,
            "Check `src/db/mod.rs` and `DbConnection::open_memory()` before edits.",
        );

        // Exact path, glob, and symbol selectors all resolve through the
        // derived table written by insert_memory's single extraction walk.
        for query in [
            RecallQuery {
                paths: vec!["src/db/mod.rs".to_owned()],
                ..RecallQuery::default()
            },
            RecallQuery {
                paths: vec!["src/db/*.rs".to_owned()],
                ..RecallQuery::default()
            },
            RecallQuery {
                symbols: vec!["DbConnection::open_memory".to_owned()],
                ..RecallQuery::default()
            },
        ] {
            let report = run_recall(&connection, &workspace_id, &query).expect("run recall");
            assert_eq!(report.items.len(), 1, "query {query:?} must match");
            assert_eq!(report.items[0].memory_id, memory_id);
            assert_eq!(report.items[0].tags, vec!["recall-test".to_owned()]);
            assert_eq!(report.items[0].provenance.len(), 1);
            // Freshly written rows carry the current generation: no
            // degradations, index generation matches DB generation.
            assert!(
                report.degraded.is_empty(),
                "unexpected: {:?}",
                report.degraded
            );
            assert_eq!(report.index_generation, Some(report.db_generation));
        }
    }

    #[test]
    fn run_recall_without_embeddings_preserves_anchor_results_without_degradation() {
        let (_temp, connection, workspace_id) = wrapper_test_file_db();
        let memory_id = format!("mem_{:026}", 9);
        wrapper_insert_memory(
            &connection,
            &workspace_id,
            &memory_id,
            "Check `src/core/model.rs` when semantic lifecycle readiness changes.",
        );

        let report = run_recall(
            &connection,
            &workspace_id,
            &RecallQuery {
                paths: vec!["src/core/model.rs".to_owned()],
                ..RecallQuery::default()
            },
        )
        .expect("run recall");

        assert_eq!(report.items.len(), 1);
        assert_eq!(report.items[0].memory_id, memory_id);
        assert!(
            report.degraded.is_empty(),
            "anchor recall must work without an embedding model: {:?}",
            report.degraded
        );
    }

    #[test]
    fn run_recall_reports_empty_then_stale_index_honestly() {
        let (connection, workspace_id) = wrapper_test_db();

        // No memories at all: empty-index degradation, never an error.
        let empty = run_recall(
            &connection,
            &workspace_id,
            &RecallQuery {
                paths: vec!["src/**".to_owned()],
                ..RecallQuery::default()
            },
        )
        .expect("run recall on empty index");
        assert!(empty.items.is_empty());
        assert_eq!(empty.degraded.len(), 1);
        assert_eq!(empty.degraded[0].code, ANCHOR_INDEX_EMPTY_CODE);

        // One anchored memory: fresh. A later anchorless write advances the
        // DB generation without touching the reverse index, so recall
        // reports the index stale until a rebuild re-stamps it.
        let anchored = format!("mem_{:026}", 2);
        wrapper_insert_memory(
            &connection,
            &workspace_id,
            &anchored,
            "Durable note about `src/core/recall.rs` ranking.",
        );
        let anchorless = format!("mem_{:026}", 3);
        wrapper_insert_memory(
            &connection,
            &workspace_id,
            &anchorless,
            "Plain prose note with no code anchors at all.",
        );
        let query = RecallQuery {
            paths: vec!["src/core/recall.rs".to_owned()],
            ..RecallQuery::default()
        };
        let stale = run_recall(&connection, &workspace_id, &query).expect("run recall");
        assert_eq!(
            stale.items.len(),
            1,
            "stale detection must not block results"
        );
        assert_eq!(stale.degraded.len(), 1);
        assert_eq!(stale.degraded[0].code, ANCHOR_INDEX_STALE_CODE);

        // The rebuild path re-stamps rows at the current generation.
        connection
            .refresh_memory_anchor_index_for_memory(
                &workspace_id,
                &anchored,
                "Durable note about `src/core/recall.rs` ranking.",
            )
            .expect("refresh reverse index");
        let fresh = run_recall(&connection, &workspace_id, &query).expect("run recall");
        assert!(
            fresh.degraded.is_empty(),
            "unexpected: {:?}",
            fresh.degraded
        );
        assert_eq!(fresh.items.len(), 1);
    }

    #[test]
    fn run_recall_excludes_tombstoned_memories() {
        let (connection, workspace_id) = wrapper_test_db();
        let memory_id = format!("mem_{:026}", 4);
        wrapper_insert_memory(
            &connection,
            &workspace_id,
            &memory_id,
            "Tombstone target anchored to `src/db/migrate.rs`.",
        );
        let query = RecallQuery {
            paths: vec!["src/db/migrate.rs".to_owned()],
            ..RecallQuery::default()
        };
        assert_eq!(
            run_recall(&connection, &workspace_id, &query)
                .expect("run recall")
                .items
                .len(),
            1
        );
        connection
            .tombstone_memory(&memory_id)
            .expect("tombstone memory");
        let report = run_recall(&connection, &workspace_id, &query).expect("run recall");
        assert!(
            report.items.is_empty(),
            "tombstoned memories must be excluded at query time"
        );
    }

    #[test]
    fn candidate_scan_is_bounded() {
        let rows: Vec<RecallCandidateRow> = (0..(RECALL_CANDIDATE_SCAN_CAP + 50))
            .map(|index| row(&format!("mem_{index:06}"), Some("src/a.rs"), None))
            .collect();
        let report = evaluate_recall(&path_query(&["src/*.rs"]), &rows, Some(7), 7);
        assert_eq!(report.total_matched, RECALL_CANDIDATE_SCAN_CAP);
    }
}