second-brain-core 0.12.0

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
pub mod blend;
mod onnx_rerank;
pub mod raw_fallback;
pub mod rerank;
pub mod rrf;

pub use rerank::{RerankScorer, RerankTimeoutError, Reranker};

use std::collections::HashMap;

use anyhow::Result;
use uuid::Uuid;

use crate::index::Indexes;
use crate::query::{QueryRequest, QueryResult};
use crate::schema::Memory;
use crate::sqlite_store::SqliteStore;
use crate::store::Store;
use blend::BlendWeights;

/// Ceiling on the widened BM25 fetch a scoped query may ask for.
const SCOPED_LEXICAL_MAX_K: usize = 5000;

/// Dense and lexical candidate lists, each best-first as (memory id, score).
#[derive(Debug, Clone, Default)]
pub struct Candidates {
    pub dense: Vec<(Uuid, f32)>,
    pub lexical: Vec<(Uuid, f32)>,
    /// Set when generation scanned the caller's entire scope, so this pool is
    /// every memory the filter admits rather than a relevance-ranked slice of
    /// the store.
    pub scope_exhausted: bool,
    /// For a memory one of whose chunks hit the query: (chunk ord, chunk
    /// cosine) of its best chunk. Rerank scores the window around that ord.
    pub best_chunk: BestChunks,
}

/// Memory id to (chunk ord, chunk cosine) of its best-matching chunk.
pub type BestChunks = HashMap<Uuid, (usize, f32)>;

impl Candidates {
    pub fn new(dense: Vec<(Uuid, f32)>, lexical: Vec<(Uuid, f32)>) -> Self {
        Self {
            dense,
            lexical,
            scope_exhausted: false,
            best_chunk: HashMap::new(),
        }
    }
}

/// Folds chunk hits into the dense list: a memory scores the better of its
/// own vector and its best chunk, and the list is re-sorted and cut to `k`.
/// Without chunk hits the list comes back untouched, so a store with no
/// chunks ranks exactly as before chunks existed.
fn merge_chunk_hits(
    dense: Vec<(Uuid, f32)>,
    chunk_hits: Vec<(Uuid, f32, usize)>,
    k: usize,
) -> (Vec<(Uuid, f32)>, BestChunks) {
    if chunk_hits.is_empty() {
        return (dense, HashMap::new());
    }
    let best_chunk: BestChunks = chunk_hits
        .iter()
        .map(|(id, similarity, ord)| (*id, (*ord, *similarity)))
        .collect();
    let mut merged = dense;
    let listed: std::collections::HashSet<Uuid> = merged.iter().map(|(id, _)| *id).collect();
    for (id, similarity) in merged.iter_mut() {
        if let Some((_, chunk)) = best_chunk.get(id) {
            *similarity = similarity.max(*chunk);
        }
    }
    merged.extend(
        chunk_hits
            .iter()
            .filter(|(id, _, _)| !listed.contains(id))
            .map(|(id, similarity, _)| (*id, *similarity)),
    );
    merged.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
    merged.truncate(k);
    (merged, best_chunk)
}

/// `chunk_search` keeps one hit per memory, so it is asked for this many
/// times `dense_k` chunk hits to leave room for memories with several.
const CHUNK_K_FACTOR: usize = 3;

#[derive(Debug, Clone, Copy)]
pub struct RetrievalTunables {
    pub dense_k: usize,
    pub lexical_k: usize,
    pub fuse_top: usize,
    pub rerank_gate: f32,
    pub cosine_gate: f32,
    /// Membership floor, in cosine, for a scope generation scanned whole. It
    /// sits under `cosine_gate` because naming a scope is the caller
    /// asserting the haystack, so a weak real match must still come back.
    /// Calibrated on the gold set (`sb-recall-eval floor-sweep`,
    /// evals/exhausted-floor.md) as the highest floor that keeps 99% of gold
    /// memories answerable from their own project. With the BGE query
    /// instruction applied, the best match in an unrelated project has a
    /// median cosine of 0.65, so this floor rarely empties an unrelated
    /// scope; it only drops noise.
    pub exhausted_cosine_gate: f32,
    /// How many of each candidate list's top entries always enter the fused
    /// list, whatever RRF makes of them. 0 is plain RRF.
    pub fusion_floor: usize,
    /// Use sentence chunks: as dense candidates (a memory scores its best
    /// chunk when that beats its own vector), as the cosine primary, and as a
    /// rerank window scored beside the whole memory. False ranks exactly as
    /// before chunks existed.
    pub chunk_rerank: bool,
    /// Also rerank the whole memory beside its chunk window and keep the
    /// better score. False scores a chunked memory on its window alone, which
    /// keeps the rerank call the size it was before chunks.
    pub rerank_whole_chunked: bool,
    /// Answer a reranked query with nothing unless some result reaches
    /// `blend::ABSTAIN_RERANK_BAR`; an answer that has one keeps every result
    /// past `rerank_gate`. A caller that abstains must treat an empty answer
    /// as final rather than fall back to an unranked search.
    pub abstain: bool,
    /// Order results by `blend::source_rank` before score. On the reranked
    /// path only results reaching `blend::ABSTAIN_RERANK_BAR` are ordered so;
    /// the rest follow them by score.
    pub source_order: bool,
    pub weights: BlendWeights,
}

impl Default for RetrievalTunables {
    fn default() -> Self {
        Self {
            dense_k: 150,
            lexical_k: 150,
            fuse_top: 100,
            rerank_gate: 0.30,
            cosine_gate: blend::MIN_SIMILARITY,
            exhausted_cosine_gate: blend::EXHAUSTED_MIN_SIMILARITY,
            fusion_floor: 0,
            chunk_rerank: true,
            rerank_whole_chunked: true,
            abstain: false,
            source_order: false,
            weights: BlendWeights::default(),
        }
    }
}

#[derive(Default)]
pub struct Retriever {
    pub tunables: RetrievalTunables,
}

/// Where a project-first answer came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectScope {
    Project,
    /// Nothing in the project cleared the bar, so the answer, possibly empty,
    /// is from the wide search.
    OtherProjects,
}

#[derive(Debug, Clone)]
pub struct ProjectFirst {
    pub results: Vec<QueryResult>,
    pub scope: ProjectScope,
}

pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }
    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
    let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
    if na == 0.0 || nb == 0.0 {
        return 0.0;
    }
    dot / (na * nb)
}

impl Retriever {
    /// Index-side candidate generation: dense and lexical top-k, both
    /// best-first. Separated from rank() so the eval harness can feed rank()
    /// through its CachingStore while candidates come from real indexes.
    pub fn candidates(
        &self,
        indexes: &Indexes,
        store: &SqliteStore,
        request: &QueryRequest,
    ) -> Result<Candidates> {
        let source = request.filters.source.as_deref();
        let memory_type = request.filters.memory_type;
        let project_path = request.filters.project_path.as_deref();
        if source.is_some() || memory_type.is_some() || project_path.is_some() {
            return self.scoped_candidates(
                indexes,
                store,
                request,
                source,
                memory_type,
                project_path,
            );
        }
        let dense_k = self.tunables.dense_k;
        let dense = indexes.vector_search(store, &request.embedding, dense_k)?;
        let chunk_hits = if self.tunables.chunk_rerank {
            indexes.chunk_search(store, &request.embedding, dense_k * CHUNK_K_FACTOR)?
        } else {
            Vec::new()
        };
        let (dense, best_chunk) = merge_chunk_hits(dense, chunk_hits, dense_k);
        let lexical = indexes.bm25_search(&request.text, self.tunables.lexical_k)?;
        Ok(Candidates {
            best_chunk,
            ..Candidates::new(dense, lexical)
        })
    }

    /// Candidate generation for a query scoped by source, type, and/or
    /// project.
    ///
    /// The unfiltered path picks its shortlist before the filter is known, so
    /// a memory outside the global top-k cannot be reached however narrow the
    /// scope is; the scope must therefore constrain generation rather than
    /// trim its output. Dense becomes an exhaustive cosine scan of the
    /// matching subset, which is affordable because the store already
    /// brute-forces `vector_search` over the whole table, making a subset scan
    /// strictly cheaper. Lexical over-fetches and intersects instead, because
    /// the tantivy schema carries only body text and cannot filter on source
    /// or project.
    #[allow(clippy::too_many_arguments)]
    fn scoped_candidates(
        &self,
        indexes: &Indexes,
        store: &SqliteStore,
        request: &QueryRequest,
        source: Option<&str>,
        memory_type: Option<crate::schema::MemoryType>,
        project_path: Option<&str>,
    ) -> Result<Candidates> {
        let dense: Vec<(Uuid, f32)> = store
            .filtered_vector_search(
                &request.embedding,
                source,
                memory_type,
                project_path,
                self.tunables.dense_k,
            )?
            .into_iter()
            .map(|(memory, similarity)| (memory.id, similarity))
            .collect();

        // Exhaustion is judged on memories before chunk hits merge in: it
        // says the scope held fewer memories than dense_k, which chunks of
        // those same memories cannot change.
        let exhausted = dense.len() < self.tunables.dense_k;
        let chunk_hits = if self.tunables.chunk_rerank {
            store.filtered_chunk_search(
                &request.embedding,
                source,
                memory_type,
                project_path,
                self.tunables.dense_k,
            )?
        } else {
            Vec::new()
        };
        let (dense, best_chunk) = merge_chunk_hits(dense, chunk_hits, self.tunables.dense_k);

        // A short list means the scan ran out of scope rather than out of room,
        // so dense already holds every memory the filter admits and no lexical
        // sweep can add one. This is the common case for a narrow scope, and it
        // keeps the scope-wide id read below off that path entirely.
        if exhausted {
            return Ok(Candidates {
                dense,
                lexical: Vec::new(),
                scope_exhausted: true,
                best_chunk,
            });
        }

        // Widen the sweep by the scope's inverse selectivity: a scope holding
        // one row in a thousand needs a proportionally deeper BM25 list before
        // any in-scope document appears at all. The cap bounds the worst case,
        // and a scope too narrow to survive it loses nothing, because the dense
        // side of this pair already scanned it exhaustively.
        let scoped = store
            .scoped_count(source, memory_type, project_path)?
            .max(1);
        let total = <SqliteStore as Store>::memory_count(store)?.max(scoped);
        let widen = total.div_ceil(scoped);
        let k = self
            .tunables
            .lexical_k
            .saturating_mul(widen)
            .min(SCOPED_LEXICAL_MAX_K);

        // Membership is resolved against the fetched hits, never by reading the
        // scope out, so this stays bounded by k however large the scope is.
        let hits = indexes.bm25_search(&request.text, k)?;
        let hit_ids: Vec<Uuid> = hits.iter().map(|(id, _)| *id).collect();
        let in_scope = store.retain_in_scope(&hit_ids, source, memory_type, project_path)?;
        let lexical = hits
            .into_iter()
            .filter(|(id, _)| in_scope.contains(id))
            .take(self.tunables.lexical_k)
            .collect();
        Ok(Candidates {
            best_chunk,
            ..Candidates::new(dense, lexical)
        })
    }

    /// Fuse, gate, and blend pre-computed candidates. With a scorer the
    /// primary term is its 0..1 cross-encoder score gated at rerank_gate;
    /// without one it is cosine similarity gated at the legacy cosine_gate,
    /// recomputed from stored embeddings for candidates that arrived through
    /// the lexical list only.
    pub fn rank<S: Store + ?Sized>(
        &self,
        store: &S,
        request: &QueryRequest,
        pool: &Candidates,
        reranker: Option<&dyn RerankScorer>,
    ) -> Result<Vec<QueryResult>> {
        let mut ranked = self.ranked_shortlist(store, request, pool, reranker)?;
        ranked.truncate(request.limit);
        Ok(ranked)
    }

    /// `rank` before its cut to `request.limit`: at most `3 * request.limit`
    /// results, blended from the top `3 * request.limit` candidates by
    /// primary score, in answer order.
    fn ranked_shortlist<S: Store + ?Sized>(
        &self,
        store: &S,
        request: &QueryRequest,
        pool: &Candidates,
        reranker: Option<&dyn RerankScorer>,
    ) -> Result<Vec<QueryResult>> {
        let dense_ids: Vec<Uuid> = pool.dense.iter().map(|(id, _)| *id).collect();
        let lexical_ids: Vec<Uuid> = pool.lexical.iter().map(|(id, _)| *id).collect();
        let fused = rrf::fuse_with_floor(
            &[&dense_ids, &lexical_ids],
            rrf::RRF_K,
            self.tunables.fuse_top,
            self.tunables.fusion_floor,
        );
        let best_chunk = |id: &Uuid| {
            self.tunables
                .chunk_rerank
                .then(|| pool.best_chunk.get(id).copied())
                .flatten()
        };
        let dense_sim: HashMap<Uuid, f32> = pool.dense.iter().copied().collect();

        let mut candidates: Vec<Memory> = Vec::new();
        for (id, _) in &fused {
            let Some(memory) = store.get_memory_with_embedding(*id)? else {
                continue;
            };
            // The indexes lag the store by an outbox drain, so a candidate
            // can be a row recall must no longer show.
            if memory.tier != crate::schema::Tier::Hot || memory.superseded_by.is_some() {
                continue;
            }
            if let Some(min_conf) = request.filters.min_confidence
                && memory.confidence < min_conf
            {
                continue;
            }
            if let Some(ref source) = request.filters.source
                && !store.source_admits(&memory, source)?
            {
                continue;
            }
            if let Some(ref mt) = request.filters.memory_type
                && &memory.memory_type != mt
            {
                continue;
            }
            candidates.push(memory);
        }

        let cosine_primaries = |cands: &[Memory]| -> Vec<f32> {
            cands
                .iter()
                .map(|m| {
                    let whole = dense_sim
                        .get(&m.id)
                        .copied()
                        .unwrap_or_else(|| cosine(&request.embedding, &m.embedding));
                    best_chunk(&m.id).map_or(whole, |(_, chunk)| whole.max(chunk))
                })
                .collect()
        };

        // A saturated rerank pool, or an overloaded remote scorer, must
        // degrade this query, not fail it: the caller gets the non-reranked
        // hybrid answer (still RRF-fused, still graph/recency blended)
        // instead of an error, the same way the recall route already
        // degrades to the legacy engine on other hybrid-path failures.
        let (primaries, reranked) = match reranker {
            Some(r) => {
                // Windows follow the whole memories in the same call; each
                // candidate's primary is the better of its two scores.
                let mut windows: Vec<(usize, String)> = Vec::new();
                for (i, m) in candidates.iter().enumerate() {
                    if let Some((ord, _)) = best_chunk(&m.id)
                        && let Some(window) = store.chunk_window(m.id, ord)?
                    {
                        windows.push((i, window));
                    }
                }
                let whole_too = self.tunables.rerank_whole_chunked;
                let mut firsts: Vec<&str> = candidates.iter().map(|m| m.content.as_str()).collect();
                if !whole_too {
                    for (i, w) in &windows {
                        firsts[*i] = w.as_str();
                    }
                }
                let docs: Vec<&str> = firsts
                    .into_iter()
                    .chain(
                        windows
                            .iter()
                            .filter(|_| whole_too)
                            .map(|(_, w)| w.as_str()),
                    )
                    .collect();
                match r.rerank(&request.text, &docs) {
                    // Zipping a short score list would silently drop the
                    // unscored tail of the candidates.
                    Ok(scores) if scores.len() != docs.len() => anyhow::bail!(
                        "rerank scorer returned {} scores for {} documents",
                        scores.len(),
                        docs.len()
                    ),
                    Ok(mut scores) => {
                        let window_scores = scores.split_off(candidates.len());
                        for ((i, _), score) in windows.iter().zip(window_scores) {
                            scores[*i] = scores[*i].max(score);
                        }
                        (scores, true)
                    }
                    Err(e) if e.downcast_ref::<RerankTimeoutError>().is_some() => {
                        tracing::warn!(
                            "rerank unavailable ({e}); falling back to the \
                             non-reranked hybrid path for this query"
                        );
                        (cosine_primaries(&candidates), false)
                    }
                    Err(e) => return Err(e),
                }
            }
            None => (cosine_primaries(&candidates), false),
        };
        // An exhausted scope is every memory the caller's filter admits, so a
        // gate calibrated for slicing a whole-store ranking would blank the
        // answer to a question that named its own haystack; a cross-encoder
        // is no help there either, because it scores a weak real match
        // ("job title" against a memory stating the job) below outright
        // nonsense. Membership therefore falls back to a relaxed cosine floor
        // on that path, while the reranked primary still orders the answer.
        let cosines = cosine_primaries(&candidates);
        let admitted = |i: usize, primary: f32| -> bool {
            if pool.scope_exhausted {
                cosines[i] >= self.tunables.exhausted_cosine_gate
            } else if reranked {
                primary >= self.tunables.rerank_gate
            } else {
                primary >= self.tunables.cosine_gate
            }
        };

        let query_entity_ids = blend::resolve_query_entities(store, &request.filters.entity_names);

        // Blend over at most limit*3 candidates ranked by the primary term,
        // mirroring the legacy engine's vector_search(limit*3) pool. Graph and
        // recency carry enough weight that blending a wider fused pool lets
        // recent, well-connected memories displace strong matches wholesale.
        let mut shortlist: Vec<(usize, Memory, f32)> = candidates
            .into_iter()
            .zip(primaries)
            .enumerate()
            .map(|(i, (memory, primary))| (i, memory, primary))
            .collect();
        shortlist.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
        shortlist.truncate(request.limit * 3);

        let mut scored: Vec<QueryResult> = Vec::new();
        for (i, memory, primary) in shortlist {
            // Membership is gated on the primary term alone, exactly like the
            // legacy path: graph and recency only re-rank.
            if !admitted(i, primary) {
                continue;
            }
            let recency = blend::compute_recency(&memory);
            let graph =
                blend::compute_graph_relevance(store, &memory, &query_entity_ids).unwrap_or(0.0);
            let score = blend::blend(primary, graph, recency, self.tunables.weights);
            let score = blend::apply_project_affinity(
                score,
                &memory,
                request.filters.project_path.as_deref(),
            );
            scored.push(QueryResult {
                memory,
                score,
                relevance: primary,
                path: Vec::new(),
            });
        }

        // An exhausted named scope keeps its relaxed floor, for the reason
        // given at `admitted`.
        if self.tunables.abstain
            && reranked
            && !pool.scope_exhausted
            && !scored
                .iter()
                .any(|r| r.relevance >= blend::ABSTAIN_RERANK_BAR)
        {
            scored.clear();
        }

        // A weak note ranked by its source alone would push a strong raw
        // match out of the answer.
        let source_rank = |r: &QueryResult| {
            if !self.tunables.source_order {
                (false, 0)
            } else if reranked && r.relevance < blend::ABSTAIN_RERANK_BAR {
                (true, 0)
            } else {
                (false, blend::source_rank(&r.memory.source))
            }
        };
        scored.sort_by(|a, b| {
            source_rank(a).cmp(&source_rank(b)).then(
                b.score
                    .partial_cmp(&a.score)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
        });
        Ok(scored)
    }

    /// Ranks `project`'s memories first and searches `request`'s wider scope
    /// only when nothing in the project clears the bar. `generate` makes the
    /// candidates for either request. The project was not named by the
    /// caller, so its pass never gets the relaxed floor of an exhausted named
    /// scope.
    pub fn rank_project_first<S, G>(
        &self,
        store: &S,
        request: &QueryRequest,
        project: &str,
        mut generate: G,
        reranker: Option<&dyn RerankScorer>,
    ) -> Result<ProjectFirst>
    where
        S: Store + ?Sized,
        G: FnMut(&QueryRequest) -> Result<Candidates>,
    {
        let mut local = request.clone();
        local.filters.project_path = Some(project.to_string());
        let mut pool = generate(&local)?;
        pool.scope_exhausted = false;
        let results = self.rank(store, &local, &pool, reranker)?;
        if !results.is_empty() {
            return Ok(ProjectFirst {
                results,
                scope: ProjectScope::Project,
            });
        }
        let pool = generate(request)?;
        Ok(ProjectFirst {
            results: self.rank(store, request, &pool, reranker)?,
            scope: ProjectScope::OtherProjects,
        })
    }

    /// `rank_project_first` in one pass, for a caller that cannot afford a
    /// second rerank: ranks `request`'s scope once and moves `project`'s
    /// results that reach `blend::ABSTAIN_RERANK_BAR` ahead of the rest, the
    /// bar that decides `rank_project_first`'s project pass, so a weak local
    /// match never displaces a strong one from elsewhere. A project memory
    /// outside the blended shortlist of the wide scope (the top
    /// `3 * request.limit` by primary score) is not looked for. On
    /// an answer the scorer could not rerank, relevance is cosine, which the
    /// bar does not calibrate, so the order then means little.
    pub fn rank_project_preferred<S, G>(
        &self,
        store: &S,
        request: &QueryRequest,
        project: &str,
        mut generate: G,
        reranker: Option<&dyn RerankScorer>,
    ) -> Result<ProjectFirst>
    where
        S: Store + ?Sized,
        G: FnMut(&QueryRequest) -> Result<Candidates>,
    {
        let pool = generate(request)?;
        let mut results = self.ranked_shortlist(store, request, &pool, reranker)?;
        let in_project = |r: &QueryResult| {
            r.memory.project_path.as_deref() == Some(project)
                && r.relevance >= blend::ABSTAIN_RERANK_BAR
        };
        results.sort_by_key(|r| !in_project(r));
        results.truncate(request.limit);
        let scope = if results.first().is_some_and(in_project) {
            ProjectScope::Project
        } else {
            ProjectScope::OtherProjects
        };
        Ok(ProjectFirst { results, scope })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::query::QueryFilters;
    use crate::schema::{Conversation, Entity, MemoryType, Relation};
    use crate::store::Store;
    use chrono::Utc;

    struct StubStore {
        memories: Vec<Memory>,
    }

    impl Store for StubStore {
        fn store_memory(&self, _: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn get_memory(&self, id: Uuid) -> Result<Option<Memory>> {
            Ok(self.memories.iter().find(|m| m.id == id).cloned())
        }
        fn get_memory_with_embedding(&self, id: Uuid) -> Result<Option<Memory>> {
            self.get_memory(id)
        }
        fn delete_memory(&self, _: Uuid) -> Result<()> {
            unimplemented!()
        }
        fn store_entity(&self, _: &Entity) -> Result<()> {
            unimplemented!()
        }
        fn get_entity(&self, _: Uuid) -> Result<Option<Entity>> {
            Ok(None)
        }
        fn find_entity_by_name(&self, _: &str) -> Result<Option<Entity>> {
            Ok(None)
        }
        fn store_conversation(&self, _: &Conversation) -> Result<()> {
            unimplemented!()
        }
        fn store_relation(&self, _: &Relation) -> Result<()> {
            unimplemented!()
        }
        fn get_relations(
            &self,
            _: Uuid,
            _: Option<crate::schema::RelationType>,
        ) -> Result<Vec<Relation>> {
            Ok(Vec::new())
        }
        fn vector_search(&self, _: &[f32], _: usize) -> Result<Vec<(Memory, f32)>> {
            unimplemented!()
        }
        fn filtered_vector_search(
            &self,
            embedding: &[f32],
            source: Option<&str>,
            memory_type: Option<MemoryType>,
            project_path: Option<&str>,
            limit: usize,
        ) -> Result<Vec<(Memory, f32)>> {
            let mut scored: Vec<(Memory, f32)> = self
                .memories
                .iter()
                .filter(|m| source.is_none_or(|s| m.source == s))
                .filter(|m| memory_type.is_none_or(|t| m.memory_type == t))
                .filter(|m| project_path.is_none_or(|p| m.project_path.as_deref() == Some(p)))
                .map(|m| (m.clone(), cosine(embedding, &m.embedding)))
                .collect();
            scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
            scored.truncate(limit);
            Ok(scored)
        }
        fn traverse(&self, _: Uuid, _: u32) -> Result<Vec<(Memory, Vec<Relation>)>> {
            unimplemented!()
        }
        fn memories_by_source(&self, _: &str) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn memories_by_type(&self, _: MemoryType) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn update_memory(&self, _: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn record_access(&self, _: &Memory) -> Result<()> {
            unimplemented!()
        }
        fn bm25_search(&self, _: &str, _: usize) -> Result<Vec<Memory>> {
            unimplemented!()
        }
        fn memory_count(&self) -> Result<usize> {
            unimplemented!()
        }
        fn all_memory_ids(&self) -> Result<Vec<Uuid>> {
            unimplemented!()
        }
        fn all_relations(&self) -> Result<Vec<Relation>> {
            unimplemented!()
        }
        /// The stub keeps a memory's chunk window in its `context`.
        fn chunk_window(&self, memory_id: Uuid, _: usize) -> Result<Option<String>> {
            Ok(self
                .memories
                .iter()
                .find(|m| m.id == memory_id)
                .and_then(|m| m.context.clone()))
        }
    }

    fn memory(content: &str, embedding: Vec<f32>) -> Memory {
        let mut m = Memory::new(
            content.to_string(),
            MemoryType::Semantic,
            "test".to_string(),
            String::new(),
        );
        m.embedding = embedding;
        m
    }

    fn request(embedding: Vec<f32>) -> QueryRequest {
        QueryRequest {
            text: "query".to_string(),
            embedding,
            limit: 10,
            filters: QueryFilters::default(),
        }
    }

    #[test]
    fn candidate_on_both_lists_outranks_dense_only_at_equal_similarity() {
        let both = memory("on both lists", vec![1.0, 0.0]);
        let dense_only = memory("dense only", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![both.clone(), dense_only.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![(dense_only.id, 0.9), (both.id, 0.9)];
        let lexical = vec![(both.id, 5.0)];
        let results = store_rank(
            &retriever,
            &store,
            &request(vec![1.0, 0.0]),
            &dense,
            &lexical,
        );

        assert_eq!(results[0].memory.id, both.id);
    }

    #[test]
    fn low_cosine_candidate_is_gated_out_on_the_no_rerank_path() {
        let strong = memory("strong match", vec![1.0, 0.0]);
        let weak = memory("weak match", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![strong.clone(), weak.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![(strong.id, 0.92), (weak.id, 0.45)];
        let results = store_rank(&retriever, &store, &request(vec![1.0, 0.0]), &dense, &[]);

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].memory.id, strong.id);
    }

    #[test]
    fn lexical_only_candidate_gets_cosine_from_stored_embedding() {
        // Arrives only via BM25; its stored embedding matches the query
        // exactly, so cosine = 1.0 clears the 0.59 gate.
        let lexical_hit = memory("lexical only", vec![0.6, 0.8]);
        let store = StubStore {
            memories: vec![lexical_hit.clone()],
        };
        let retriever = Retriever::default();

        let lexical = vec![(lexical_hit.id, 3.0)];
        let results = store_rank(&retriever, &store, &request(vec![0.6, 0.8]), &[], &lexical);

        assert_eq!(results.len(), 1);
    }

    #[test]
    fn blend_only_reorders_the_primary_shortlist() {
        // Legacy recall blended graph/recency over at most limit*3 candidates
        // ranked by similarity; a wider pool must not let a fresh but weakly
        // similar memory displace strong matches, so candidates outside the
        // top limit*3 by primary are excluded before blending.
        let old = |content: &str, sim: f32| {
            let mut m = memory(content, vec![1.0, 0.0]);
            m.created_at = Utc::now() - chrono::Duration::days(200);
            m.last_accessed = m.created_at;
            (m, sim)
        };
        let (a, a_sim) = old("strong a", 0.95);
        let (b, b_sim) = old("strong b", 0.94);
        let (c, c_sim) = old("strong c", 0.93);
        let fresh = memory("fresh diluter", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![a.clone(), b.clone(), c.clone(), fresh.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![
            (a.id, a_sim),
            (b.id, b_sim),
            (c.id, c_sim),
            (fresh.id, 0.60),
        ];
        let mut req = request(vec![1.0, 0.0]);
        req.limit = 1;
        let results = retriever
            .rank(&store, &req, &Candidates::new(dense, Vec::new()), None)
            .unwrap();

        assert_eq!(results[0].memory.id, a.id);
    }

    #[test]
    fn source_filter_still_applies() {
        let mut filtered = memory("wrong source", vec![1.0, 0.0]);
        filtered.source = "other".to_string();
        let kept = memory("right source", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![filtered.clone(), kept.clone()],
        };
        let retriever = Retriever::default();

        let mut req = request(vec![1.0, 0.0]);
        req.filters.source = Some("test".to_string());
        let dense = vec![(filtered.id, 0.9), (kept.id, 0.9)];
        let results = store_rank(&retriever, &store, &req, &dense, &[]);

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].memory.id, kept.id);
    }

    #[test]
    fn archived_and_superseded_candidates_are_dropped_by_rank() {
        // The outbox drains every few seconds, so a candidate list can name a
        // row the store has since retired or superseded.
        let live = memory("live", vec![1.0, 0.0]);
        let mut archived = memory("archived", vec![1.0, 0.0]);
        archived.tier = crate::schema::Tier::Archived;
        let mut superseded = memory("superseded", vec![1.0, 0.0]);
        superseded.superseded_by = Some(live.id);
        let store = StubStore {
            memories: vec![live.clone(), archived.clone(), superseded.clone()],
        };
        let retriever = Retriever::default();

        let dense = vec![(archived.id, 0.99), (superseded.id, 0.98), (live.id, 0.9)];
        let results = store_rank(&retriever, &store, &request(vec![1.0, 0.0]), &dense, &[]);

        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![live.id]);
    }

    #[test]
    fn an_exhausted_scope_keeps_a_similarity_floor() {
        // A cosine of 0.3 is noise in any scope; one just over the floor is
        // a real but weak match.
        let w = blend::EXHAUSTED_MIN_SIMILARITY + 0.005;
        let weak = memory("weak match", vec![w, (1.0f32 - w * w).sqrt()]);
        let noise = memory("noise", vec![0.3, (1.0f32 - 0.09).sqrt()]);
        let store = StubStore {
            memories: vec![weak.clone(), noise.clone()],
        };
        let retriever = Retriever::default();
        let pool = Candidates {
            dense: vec![(weak.id, w), (noise.id, 0.3)],
            lexical: Vec::new(),
            scope_exhausted: true,
            best_chunk: HashMap::new(),
        };

        let results = retriever
            .rank(&store, &request(vec![1.0, 0.0]), &pool, None)
            .unwrap();

        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![weak.id]);
    }

    #[test]
    fn an_exhausted_scope_gates_on_cosine_even_when_reranked() {
        struct LowScorer;
        impl RerankScorer for LowScorer {
            fn rerank(&self, _: &str, docs: &[&str]) -> Result<Vec<f32>> {
                Ok(docs.iter().map(|_| 0.02).collect())
            }
        }
        let w = blend::EXHAUSTED_MIN_SIMILARITY + 0.005;
        let weak = memory("weak match", vec![w, (1.0f32 - w * w).sqrt()]);
        let noise = memory("noise", vec![0.3, (1.0f32 - 0.09).sqrt()]);
        let store = StubStore {
            memories: vec![weak.clone(), noise.clone()],
        };
        let retriever = Retriever::default();
        let pool = Candidates {
            dense: vec![(weak.id, w), (noise.id, 0.3)],
            lexical: Vec::new(),
            scope_exhausted: true,
            best_chunk: HashMap::new(),
        };

        let results = retriever
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&LowScorer))
            .unwrap();

        let ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![weak.id]);
    }

    fn store_rank(
        retriever: &Retriever,
        store: &StubStore,
        request: &QueryRequest,
        dense: &[(Uuid, f32)],
        lexical: &[(Uuid, f32)],
    ) -> Vec<QueryResult> {
        retriever
            .rank(
                store,
                request,
                &Candidates::new(dense.to_vec(), lexical.to_vec()),
                None,
            )
            .unwrap()
    }

    /// Scores 0.8 for any document naming the planted fact and 0.1 for the
    /// rest, and records every call's documents.
    struct FactScorer {
        calls: std::sync::Mutex<Vec<Vec<String>>>,
    }

    impl FactScorer {
        fn new() -> Self {
            Self {
                calls: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    impl RerankScorer for FactScorer {
        fn rerank(&self, _: &str, docs: &[&str]) -> Result<Vec<f32>> {
            self.calls
                .lock()
                .unwrap()
                .push(docs.iter().map(|d| d.to_string()).collect());
            Ok(docs
                .iter()
                .map(|d| if d.contains("fact") { 0.8 } else { 0.1 })
                .collect())
        }
    }

    fn chunked_pool(dense: Vec<(Uuid, f32)>, best_chunk: &[(Uuid, usize, f32)]) -> Candidates {
        let mut pool = Candidates::new(dense, Vec::new());
        pool.best_chunk = best_chunk
            .iter()
            .map(|(id, ord, sim)| (*id, (*ord, *sim)))
            .collect();
        pool
    }

    #[test]
    fn the_rerank_primary_is_the_better_of_the_whole_memory_and_its_chunk_window() {
        let mut buried = memory("a long paragraph about many things", vec![1.0, 0.0]);
        buried.context = Some("the window holding the fact".to_string());
        let mut whole = memory("the fact stated outright", vec![1.0, 0.0]);
        whole.context = Some("a window about nothing".to_string());
        let plain = memory("nothing relevant here", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![buried.clone(), whole.clone(), plain.clone()],
        };
        let pool = chunked_pool(
            vec![(buried.id, 0.7), (whole.id, 0.7), (plain.id, 0.7)],
            &[(buried.id, 2, 0.7), (whole.id, 0, 0.6)],
        );
        let scorer = FactScorer::new();

        let results = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&scorer))
            .unwrap();

        let mut ids: Vec<Uuid> = results.iter().map(|r| r.memory.id).collect();
        ids.sort();
        let mut expected = vec![buried.id, whole.id];
        expected.sort();
        assert_eq!(ids, expected, "plain reranks at 0.1, under the gate");
        let calls = scorer.calls.lock().unwrap();
        assert_eq!(calls.len(), 1, "whole memories and windows share one call");
        assert_eq!(
            calls[0],
            vec![
                "a long paragraph about many things",
                "the fact stated outright",
                "nothing relevant here",
                "the window holding the fact",
                "a window about nothing",
            ]
        );
    }

    #[test]
    fn without_whole_reranking_a_chunked_memory_is_scored_on_its_window_alone() {
        let mut buried = memory("a long paragraph about many things", vec![1.0, 0.0]);
        buried.context = Some("the window holding the fact".to_string());
        let plain = memory("the fact stated outright", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![buried.clone(), plain.clone()],
        };
        let pool = chunked_pool(
            vec![(buried.id, 0.7), (plain.id, 0.7)],
            &[(buried.id, 2, 0.7)],
        );
        let scorer = FactScorer::new();
        let retriever = Retriever {
            tunables: RetrievalTunables {
                rerank_whole_chunked: false,
                ..RetrievalTunables::default()
            },
        };

        let results = retriever
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&scorer))
            .unwrap();

        assert_eq!(results.len(), 2);
        assert_eq!(
            scorer.calls.lock().unwrap()[0],
            vec!["the window holding the fact", "the fact stated outright"]
        );
    }

    #[test]
    fn with_chunk_rerank_off_windows_are_neither_scored_nor_counted() {
        let mut buried = memory("a long paragraph about many things", vec![1.0, 0.0]);
        buried.context = Some("the window holding the fact".to_string());
        let store = StubStore {
            memories: vec![buried.clone()],
        };
        let pool = chunked_pool(vec![(buried.id, 0.7)], &[(buried.id, 2, 0.7)]);
        let scorer = FactScorer::new();
        let retriever = Retriever {
            tunables: RetrievalTunables {
                chunk_rerank: false,
                ..RetrievalTunables::default()
            },
        };

        let results = retriever
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&scorer))
            .unwrap();

        assert!(results.is_empty());
        assert_eq!(
            scorer.calls.lock().unwrap()[0],
            vec!["a long paragraph about many things"]
        );
    }

    #[test]
    fn the_cosine_primary_takes_the_best_chunk_when_it_beats_the_memory() {
        let buried = memory("far as a whole", vec![0.0, 1.0]);
        let store = StubStore {
            memories: vec![buried.clone()],
        };
        let mut pool = chunked_pool(Vec::new(), &[(buried.id, 1, 0.9)]);
        pool.lexical = vec![(buried.id, 3.0)];

        let results = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &pool, None)
            .unwrap();
        assert_eq!(results.len(), 1, "cosine 0 as a whole, 0.9 by its chunk");

        let mut exhausted = pool.clone();
        exhausted.scope_exhausted = true;
        let results = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &exhausted, None)
            .unwrap();
        assert_eq!(results.len(), 1, "the exhausted floor also sees the chunk");
    }

    /// Scores each document by the first entry of its table whose key the
    /// document contains, 0.0 when none does.
    struct TableScorer(Vec<(&'static str, f32)>);

    impl RerankScorer for TableScorer {
        fn rerank(&self, _: &str, docs: &[&str]) -> Result<Vec<f32>> {
            Ok(docs
                .iter()
                .map(|d| {
                    self.0
                        .iter()
                        .find(|(key, _)| d.contains(key))
                        .map_or(0.0, |(_, score)| *score)
                })
                .collect())
        }
    }

    fn abstaining() -> Retriever {
        Retriever {
            tunables: RetrievalTunables {
                abstain: true,
                ..RetrievalTunables::default()
            },
        }
    }

    fn reranked_ids(
        retriever: &Retriever,
        store: &StubStore,
        dense: Vec<(Uuid, f32)>,
        scorer: &TableScorer,
    ) -> Vec<Uuid> {
        retriever
            .rank(
                store,
                &request(vec![1.0, 0.0]),
                &Candidates::new(dense, Vec::new()),
                Some(scorer),
            )
            .unwrap()
            .iter()
            .map(|r| r.memory.id)
            .collect()
    }

    #[test]
    fn abstention_answers_in_full_when_one_result_clears_the_bar() {
        let above = memory("above the bar", vec![1.0, 0.0]);
        let below = memory("below the bar", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![above.clone(), below.clone()],
        };
        let scorer = TableScorer(vec![
            ("above", blend::ABSTAIN_RERANK_BAR + 0.01),
            ("below", blend::ABSTAIN_RERANK_BAR - 0.01),
        ]);
        assert!(blend::ABSTAIN_RERANK_BAR - 0.01 >= RetrievalTunables::default().rerank_gate);
        let dense = vec![(above.id, 0.9), (below.id, 0.9)];

        let kept = reranked_ids(&abstaining(), &store, dense, &scorer);
        assert_eq!(kept, vec![above.id, below.id]);
    }

    #[test]
    fn abstention_returns_nothing_when_no_result_clears_the_bar_and_only_when_asked() {
        let weak = memory("weak match", vec![1.0, 0.0]);
        let weaker = memory("weaker match", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![weak.clone(), weaker.clone()],
        };
        let scorer = TableScorer(vec![
            ("weaker", RetrievalTunables::default().rerank_gate + 0.01),
            ("weak", blend::ABSTAIN_RERANK_BAR - 0.01),
        ]);
        let dense = vec![(weak.id, 0.9), (weaker.id, 0.9)];

        assert!(reranked_ids(&abstaining(), &store, dense.clone(), &scorer).is_empty());

        let unchanged = reranked_ids(&Retriever::default(), &store, dense, &scorer);
        assert_eq!(unchanged.len(), 2, "abstention is off by default");
    }

    #[test]
    fn abstention_leaves_the_cosine_path_on_its_gate() {
        let weak = memory("weak but over the cosine gate", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![weak.clone()],
        };
        let dense = vec![(weak.id, blend::MIN_SIMILARITY + 0.01)];
        let results = abstaining()
            .rank(
                &store,
                &request(vec![1.0, 0.0]),
                &Candidates::new(dense, Vec::new()),
                None,
            )
            .unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn a_result_carries_the_relevance_its_membership_was_judged_on() {
        let m = memory("a scored memory", vec![1.0, 0.0]);
        let store = StubStore {
            memories: vec![m.clone()],
        };
        let pool = Candidates::new(vec![(m.id, 0.83)], Vec::new());

        let cosine_path = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &pool, None)
            .unwrap();
        assert!((cosine_path[0].relevance - 0.83).abs() < 1e-6);

        let scorer = TableScorer(vec![("scored", 0.71)]);
        let reranked = Retriever::default()
            .rank(&store, &request(vec![1.0, 0.0]), &pool, Some(&scorer))
            .unwrap();
        assert!((reranked[0].relevance - 0.71).abs() < 1e-6);
    }

    #[test]
    fn source_order_puts_agent_notes_then_distillates_then_raws() {
        let mut note = memory("agent note", vec![1.0, 0.0]);
        note.source = crate::schema::AGENT_NOTE_SOURCE.to_string();
        let mut distillate = memory("distillate", vec![1.0, 0.0]);
        distillate.source = "consolidation".to_string();
        let mut raw = memory("raw", vec![1.0, 0.0]);
        raw.source = "claude-code".to_string();
        let store = StubStore {
            memories: vec![note.clone(), distillate.clone(), raw.clone()],
        };
        let scorer = TableScorer(vec![("raw", 0.95), ("distillate", 0.85), ("note", 0.75)]);
        let dense = vec![(raw.id, 0.9), (distillate.id, 0.9), (note.id, 0.9)];

        let by_score = reranked_ids(&Retriever::default(), &store, dense.clone(), &scorer);
        assert_eq!(by_score, vec![raw.id, distillate.id, note.id]);

        let ordered = Retriever {
            tunables: RetrievalTunables {
                source_order: true,
                ..RetrievalTunables::default()
            },
        };
        let by_source = reranked_ids(&ordered, &store, dense, &scorer);
        assert_eq!(by_source, vec![note.id, distillate.id, raw.id]);
    }

    #[test]
    fn source_order_never_lifts_a_result_below_the_bar_over_one_above_it() {
        let mut weak_note = memory("weak note", vec![1.0, 0.0]);
        weak_note.source = crate::schema::AGENT_NOTE_SOURCE.to_string();
        let mut distillate = memory("strong distillate", vec![1.0, 0.0]);
        distillate.source = "consolidation".to_string();
        let mut raw = memory("strong raw", vec![1.0, 0.0]);
        raw.source = "claude-code".to_string();
        let mut weak_raw = memory("weak raw", vec![1.0, 0.0]);
        weak_raw.source = "claude-code".to_string();
        let store = StubStore {
            memories: vec![
                weak_note.clone(),
                distillate.clone(),
                raw.clone(),
                weak_raw.clone(),
            ],
        };
        let scorer = TableScorer(vec![
            ("strong raw", 0.95),
            ("strong distillate", blend::ABSTAIN_RERANK_BAR + 0.01),
            ("weak raw", blend::ABSTAIN_RERANK_BAR - 0.02),
            ("weak note", blend::ABSTAIN_RERANK_BAR - 0.05),
        ]);
        let dense = vec![
            (raw.id, 0.9),
            (distillate.id, 0.9),
            (weak_raw.id, 0.9),
            (weak_note.id, 0.9),
        ];
        let ordered = Retriever {
            tunables: RetrievalTunables {
                source_order: true,
                ..RetrievalTunables::default()
            },
        };

        let ids = reranked_ids(&ordered, &store, dense, &scorer);

        assert_eq!(ids, vec![distillate.id, raw.id, weak_raw.id, weak_note.id]);
    }

    #[test]
    fn source_order_ranks_remembered_notes_with_distillates_above_raws() {
        assert_eq!(blend::source_rank(crate::schema::AGENT_NOTE_SOURCE), 0);
        assert_eq!(blend::source_rank("consolidation"), 1);
        for explicit in crate::schema::EXPLICIT_SOURCES {
            if *explicit != crate::schema::AGENT_NOTE_SOURCE {
                assert_eq!(blend::source_rank(explicit), 1, "{explicit}");
            }
        }
        for raw in ["claude-code", "cursor", "codex", "obsidian"] {
            assert_eq!(blend::source_rank(raw), 2, "{raw}");
        }
    }

    const LOCAL: &str = "-work-local";

    fn in_project(content: &str, project: &str) -> Memory {
        let mut m = memory(content, vec![1.0, 0.0]);
        m.project_path = Some(project.to_string());
        m
    }

    /// A pool for whichever scope the request names: every stored memory in
    /// it, cosine-scored from the stored vectors, exhausted when scoped.
    fn scoped_pool(store: &StubStore, request: &QueryRequest) -> Candidates {
        let scope = request.filters.project_path.as_deref();
        let dense: Vec<(Uuid, f32)> = store
            .memories
            .iter()
            .filter(|m| scope.is_none_or(|p| m.project_path.as_deref() == Some(p)))
            .map(|m| (m.id, cosine(&request.embedding, &m.embedding)))
            .collect();
        Candidates {
            scope_exhausted: scope.is_some(),
            ..Candidates::new(dense, Vec::new())
        }
    }

    fn project_first(
        store: &StubStore,
        scorer: &TableScorer,
        scopes: &std::cell::RefCell<Vec<Option<String>>>,
    ) -> ProjectFirst {
        abstaining()
            .rank_project_first(
                store,
                &request(vec![1.0, 0.0]),
                LOCAL,
                |r| {
                    scopes.borrow_mut().push(r.filters.project_path.clone());
                    Ok(scoped_pool(store, r))
                },
                Some(scorer),
            )
            .unwrap()
    }

    fn project_preferred(
        store: &StubStore,
        scorer: &TableScorer,
        scopes: &std::cell::RefCell<Vec<Option<String>>>,
    ) -> ProjectFirst {
        abstaining()
            .rank_project_preferred(
                store,
                &request(vec![1.0, 0.0]),
                LOCAL,
                |r| {
                    scopes.borrow_mut().push(r.filters.project_path.clone());
                    Ok(scoped_pool(store, r))
                },
                Some(scorer),
            )
            .unwrap()
    }

    #[test]
    fn project_preferred_ranks_once_and_puts_the_project_first() {
        let local = in_project("local weaker", LOCAL);
        let elsewhere = in_project("elsewhere stronger", "-work-other");
        let store = StubStore {
            memories: vec![elsewhere.clone(), local.clone()],
        };
        let scorer = TableScorer(vec![("weaker", 0.7), ("stronger", 0.95)]);
        let scopes = std::cell::RefCell::new(Vec::new());

        let answer = project_preferred(&store, &scorer, &scopes);

        assert_eq!(answer.scope, ProjectScope::Project);
        let ids: Vec<Uuid> = answer.results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![local.id, elsewhere.id]);
        assert_eq!(scopes.into_inner(), vec![None], "one wide pass");
    }

    #[test]
    fn project_preferred_finds_a_project_match_ranked_below_the_limit() {
        let first = in_project("elsewhere best", "-work-other");
        let second = in_project("elsewhere next", "-work-other");
        let local = in_project("local good", LOCAL);
        let store = StubStore {
            memories: vec![first, second, local.clone()],
        };
        let scorer = TableScorer(vec![("best", 0.9), ("next", 0.8), ("good", 0.6)]);

        let answer = abstaining()
            .rank_project_preferred(
                &store,
                &QueryRequest {
                    limit: 1,
                    ..request(vec![1.0, 0.0])
                },
                LOCAL,
                |r| Ok(scoped_pool(&store, r)),
                Some(&scorer),
            )
            .unwrap();

        assert_eq!(answer.scope, ProjectScope::Project);
        let ids: Vec<Uuid> = answer.results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![local.id]);
    }

    #[test]
    fn project_preferred_looks_no_deeper_than_the_blend_shortlist() {
        let others: Vec<Memory> = ["first", "second", "third"]
            .iter()
            .map(|c| {
                let mut m = in_project(&format!("elsewhere {c}"), "-work-other");
                // Stale, so the fresher local memory would win a wider blend
                // despite its lower primary score; without it this test
                // passes on a shortlist of any depth.
                m.last_accessed = Utc::now() - chrono::Duration::days(60);
                m
            })
            .collect();
        let local = in_project("local fourth", LOCAL);
        let mut memories = others.clone();
        memories.push(local);
        let store = StubStore { memories };
        let scorer = TableScorer(vec![
            ("first", 0.95),
            ("second", 0.9),
            ("third", 0.85),
            ("fourth", 0.8),
        ]);

        let answer = abstaining()
            .rank_project_preferred(
                &store,
                &QueryRequest {
                    limit: 1,
                    ..request(vec![1.0, 0.0])
                },
                LOCAL,
                |r| Ok(scoped_pool(&store, r)),
                Some(&scorer),
            )
            .unwrap();

        assert_eq!(answer.scope, ProjectScope::OtherProjects);
        let ids: Vec<Uuid> = answer.results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![others[0].id]);
    }

    #[test]
    fn project_preferred_keeps_a_weak_project_match_behind_a_strong_one_elsewhere() {
        let local = in_project("local noise", LOCAL);
        let elsewhere = in_project("elsewhere answer", "-work-other");
        let store = StubStore {
            memories: vec![local.clone(), elsewhere.clone()],
        };
        let scorer = TableScorer(vec![
            ("noise", blend::ABSTAIN_RERANK_BAR - 0.01),
            ("answer", 0.9),
        ]);
        let scopes = std::cell::RefCell::new(Vec::new());

        let answer = project_preferred(&store, &scorer, &scopes);

        assert_eq!(answer.scope, ProjectScope::OtherProjects);
        let ids: Vec<Uuid> = answer.results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![elsewhere.id, local.id]);
        assert_eq!(scopes.into_inner(), vec![None]);
    }

    #[test]
    fn project_first_answers_from_the_project_when_something_there_clears_the_bar() {
        let local = in_project("local answer", LOCAL);
        let elsewhere = in_project("elsewhere answer", "-work-other");
        let store = StubStore {
            memories: vec![local.clone(), elsewhere.clone()],
        };
        let scorer = TableScorer(vec![("answer", 0.9)]);
        let scopes = std::cell::RefCell::new(Vec::new());

        let answer = project_first(&store, &scorer, &scopes);

        assert_eq!(answer.scope, ProjectScope::Project);
        let ids: Vec<Uuid> = answer.results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![local.id]);
        assert_eq!(scopes.into_inner(), vec![Some(LOCAL.to_string())]);
    }

    #[test]
    fn project_first_searches_other_projects_when_nothing_local_clears_the_bar() {
        let local = in_project("local noise", LOCAL);
        let elsewhere = in_project("elsewhere answer", "-work-other");
        let store = StubStore {
            memories: vec![local.clone(), elsewhere.clone()],
        };
        let scorer = TableScorer(vec![
            ("noise", blend::ABSTAIN_RERANK_BAR - 0.01),
            ("answer", 0.9),
        ]);
        let scopes = std::cell::RefCell::new(Vec::new());

        let answer = project_first(&store, &scorer, &scopes);

        assert_eq!(answer.scope, ProjectScope::OtherProjects);
        let ids: Vec<Uuid> = answer.results.iter().map(|r| r.memory.id).collect();
        assert_eq!(ids, vec![elsewhere.id, local.id]);
        assert_eq!(scopes.into_inner(), vec![Some(LOCAL.to_string()), None]);
    }

    #[test]
    fn project_first_keeps_the_bar_for_its_implicit_scope() {
        // The project was never named by the caller, so the relaxed floor an
        // exhausted named scope gets must not admit a local result the
        // reranker scores as noise.
        let local = in_project("local noise", LOCAL);
        let store = StubStore {
            memories: vec![local.clone()],
        };
        let scorer = TableScorer(vec![("noise", 0.02)]);
        let scopes = std::cell::RefCell::new(Vec::new());

        let answer = project_first(&store, &scorer, &scopes);

        assert!(answer.results.is_empty());
        assert_eq!(answer.scope, ProjectScope::OtherProjects);
    }

    #[test]
    fn project_first_with_nothing_stored_for_the_project_searches_everywhere() {
        let elsewhere = in_project("elsewhere answer", "-work-other");
        let store = StubStore {
            memories: vec![elsewhere.clone()],
        };
        let scorer = TableScorer(vec![("answer", 0.9)]);
        let scopes = std::cell::RefCell::new(Vec::new());

        let answer = project_first(&store, &scorer, &scopes);

        assert_eq!(answer.scope, ProjectScope::OtherProjects);
        assert_eq!(answer.results.len(), 1);
    }
}