vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
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
//! Shared search service used by both CLI and MCP.
//!
//! Encapsulates the common hybrid search flow: create embedding provider,
//! resolve the reranker for the query, compute fetch limits, execute search,
//! apply filters.

use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use anyhow::Result;
use tokio::sync::OnceCell;
use tracing::warn;

use crate::config::{InferenceBackend, VeraConfig};
use crate::embedding::{CachedEmbeddingProvider, DynamicProvider, EmbeddingProvider};
use crate::retrieval::dynamic_reranker::DynamicReranker;
use crate::retrieval::exact_matches::augment_exact_match_candidates_with_store;
pub use crate::retrieval::exact_matches::augment_multi_query_exact_matches;
use crate::retrieval::hybrid::{
    SearchStores, compute_vector_candidates, search_hybrid_reranked_with_stores,
    search_hybrid_with_stores,
};
use crate::retrieval::query_classifier::{QueryType, classify_query, params_for_query_type};
use crate::retrieval::ranking::{RankingStage, is_path_weighted_query};
use crate::retrieval::{apply_filters, search_bm25_with_stores_and_filters};
use crate::types::{SearchFilters, SearchResult};

/// Timing data for each stage of the search pipeline.
#[derive(Debug, Default)]
pub struct SearchTimings {
    pub embedding: Option<Duration>,
    pub bm25: Option<Duration>,
    pub vector: Option<Duration>,
    pub fusion: Option<Duration>,
    pub reranking: Option<Duration>,
    pub augmentation: Option<Duration>,
    pub total: Option<Duration>,
}

impl From<crate::retrieval::hybrid::HybridTimings> for SearchTimings {
    fn from(t: crate::retrieval::hybrid::HybridTimings) -> Self {
        SearchTimings {
            embedding: t.embedding,
            bm25: t.bm25,
            vector: t.vector,
            fusion: t.fusion,
            reranking: t.reranking,
            augmentation: None,
            total: None,
        }
    }
}

/// Reusable search dependencies for a process or command invocation.
///
/// Local backends can take hundreds of milliseconds or seconds to initialize.
/// Keeping the provider and reranker here lets CLI multi-query search, deep
/// search, MCP, and eval reuse loaded models across repeated queries.
pub struct SearchContext {
    provider: Option<CachedEmbeddingProvider<DynamicProvider>>,
    model_name: Option<String>,
    provider_error: Option<String>,
    backend: InferenceBackend,
    stores: Mutex<Option<(PathBuf, Arc<SearchStores>)>>,
    /// Cross-encoder session, built on first query that actually reranks.
    ///
    /// `None` inside the cell means "unavailable": either reranking is off in
    /// config, or construction failed. See `reranker` for why that outcome is
    /// cached.
    reranker: OnceCell<Option<DynamicReranker>>,
    #[cfg(test)]
    reranker_builds: std::sync::atomic::AtomicUsize,
}

impl SearchContext {
    pub async fn new(config: &VeraConfig, backend: InferenceBackend) -> Self {
        let (provider, model_name, provider_error) =
            match crate::embedding::create_dynamic_provider(config, backend).await {
                Ok((provider, model_name)) => (
                    Some(CachedEmbeddingProvider::with_namespace(
                        provider,
                        512,
                        &model_name,
                    )),
                    Some(model_name),
                    None,
                ),
                Err(err) => {
                    warn!(
                        "Failed to create embedding provider ({}), using BM25-only search",
                        err
                    );
                    (None, None, Some(err.to_string()))
                }
            };

        Self {
            provider,
            model_name,
            provider_error,
            backend,
            stores: Mutex::new(None),
            reranker: OnceCell::new(),
            #[cfg(test)]
            reranker_builds: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    pub fn bm25_only() -> Self {
        Self {
            provider: None,
            model_name: None,
            provider_error: None,
            // Unused: with no embedding provider `search` returns on the
            // BM25-only path before any reranker is resolved.
            backend: InferenceBackend::Api,
            stores: Mutex::new(None),
            reranker: OnceCell::new(),
            #[cfg(test)]
            reranker_builds: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// Resolve the cross-encoder for one query, or `None` when this query does
    /// not rerank or no reranker is available.
    ///
    /// The heuristic is evaluated before the build, so a query that skips
    /// reranking never touches the session.
    async fn reranker_for_query(
        &self,
        config: &VeraConfig,
        has_intent: bool,
        query: &str,
        filters: &SearchFilters,
    ) -> Option<&DynamicReranker> {
        if !reranking_wanted(has_intent, query, filters) {
            return None;
        }
        self.reranker(config).await
    }

    /// Number of times the reranker build actually ran. `OnceCell` caps it at
    /// one; the interesting assertion is that it stays zero.
    #[cfg(test)]
    fn reranker_build_count(&self) -> usize {
        self.reranker_builds
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Resolve the cross-encoder, building it the first time one is needed.
    ///
    /// The local ONNX session is roughly a gigabyte of resident memory, and the
    /// majority of queries never reach the reranker, so it must not be built
    /// before the query is known (issue #100).
    ///
    /// Construction is cached on the context, not per query: MCP keeps one
    /// `SearchContext` for the life of the session, so a long session pays the
    /// load once. A failed build is cached the same way, deliberately. Retrying
    /// per query would turn one missing model or unusable execution provider
    /// into a multi-second stall on every subsequent search, and the failure
    /// causes are static for a process (absent asset, bad EP, unset API key).
    /// The cache is per context, so a new process or a rebuilt context retries.
    async fn reranker(&self, config: &VeraConfig) -> Option<&DynamicReranker> {
        self.reranker
            .get_or_init(|| async {
                #[cfg(test)]
                self.reranker_builds
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                crate::retrieval::create_dynamic_reranker(config, self.backend)
                    .await
                    .unwrap_or_else(|err| {
                        warn!("Failed to create reranker ({})", err);
                        None
                    })
            })
            .await
            .as_ref()
    }

    pub fn embedding_provider(&self) -> Option<&CachedEmbeddingProvider<DynamicProvider>> {
        self.provider.as_ref()
    }

    pub fn model_name(&self) -> Option<&str> {
        self.model_name.as_deref()
    }

    fn search_stores(&self, index_dir: &Path) -> Result<Arc<SearchStores>> {
        let mut cached = self
            .stores
            .lock()
            .map_err(|_| anyhow::anyhow!("search store cache lock poisoned"))?;
        if let Some((cached_dir, stores)) = cached.as_ref()
            && cached_dir == index_dir
        {
            return Ok(Arc::clone(stores));
        }

        let stores = Arc::new(SearchStores::open(index_dir)?);
        *cached = Some((index_dir.to_path_buf(), Arc::clone(&stores)));
        Ok(stores)
    }

    pub async fn search(
        &self,
        index_dir: &Path,
        query: &str,
        intent: Option<&str>,
        config: &VeraConfig,
        filters: &SearchFilters,
        result_limit: usize,
    ) -> Result<(Vec<SearchResult>, SearchTimings)> {
        let total_start = Instant::now();
        // `query` (raw) drives BM25, classification, expansion and exact-match
        // augmentation. The intent prefix only enriches the semantic side
        // (embedding + reranker); sending it to BM25 makes Tantivy parse
        // `intent:` as a non-existent field and fail. See issue #20.
        let vector_query = build_query_with_intent(query, intent);
        // True when an intent prefix was actually applied (non-empty intent).
        let has_intent = matches!(vector_query, std::borrow::Cow::Owned(_));
        let fetch_limit = compute_fetch_limit(query, filters, result_limit);
        let stores = self.search_stores(index_dir)?;

        let Some(provider) = self.provider.as_ref() else {
            if let Some(error) = self.provider_error.as_deref() {
                warn!(
                    "embedding provider unavailable ({}), using BM25-only search",
                    error
                );
            }
            return run_bm25_only(
                query,
                filters,
                fetch_limit,
                result_limit,
                total_start,
                &stores,
            );
        };

        let mut stored_dim = config.embedding.max_stored_dim;

        // Check metadata mismatch
        let index_meta = stores.bm25_metadata.lock().ok().map(|metadata_store| {
            (
                metadata_store.get_index_meta("model_name").unwrap_or(None),
                metadata_store
                    .get_index_meta("embedding_dim")
                    .unwrap_or(None),
                metadata_store
                    .get_index_meta("document_prefix")
                    .unwrap_or(None),
            )
        });
        if let Some((Some(s_model), Some(s_dim), s_prefix)) = index_meta {
            if let Some(model_name) = self.model_name.as_deref()
                && !crate::config::model_names_match_with_aliases(
                    &s_model,
                    model_name,
                    &config.embedding.model_aliases,
                )
            {
                warn!(
                    "Index model '{}' does not match active model '{}'; using BM25-only search",
                    s_model, model_name
                );
                return run_bm25_only(
                    query,
                    filters,
                    fetch_limit,
                    result_limit,
                    total_start,
                    &stores,
                );
            }
            // A changed document prefix means the stored vectors live in a
            // different vector space. Indexes written before this guard have
            // no stored prefix, and their documents were never prefixed.
            let active_prefix = provider.document_prefix_identity();
            if s_prefix.as_deref().unwrap_or("") != active_prefix {
                warn!(
                    "Index document prefix '{}' does not match active prefix '{}'; using BM25-only search (re-index to restore vector search)",
                    s_prefix.as_deref().unwrap_or(""),
                    active_prefix
                );
                return run_bm25_only(
                    query,
                    filters,
                    fetch_limit,
                    result_limit,
                    total_start,
                    &stores,
                );
            }
            if let Ok(dim) = s_dim.parse::<usize>() {
                if let Some(provider_dim) = provider.expected_dim()
                    && provider_dim < dim
                {
                    warn!(
                        "Index dimension {} exceeds provider dimension {}; using BM25-only search",
                        dim, provider_dim
                    );
                    return run_bm25_only(
                        query,
                        filters,
                        fetch_limit,
                        result_limit,
                        total_start,
                        &stores,
                    );
                }
                stored_dim = dim;
            }
        }

        // Decide before building: only a query that will actually be reranked
        // pays for the cross-encoder session. An explicit intent is a semantic
        // signal only the reranker/embedding side can use, so it forces
        // reranking on. A reranker that is unavailable degrades to plain hybrid
        // search, as it did when the build happened up front.
        let reranker = self
            .reranker_for_query(config, has_intent, query, filters)
            .await;
        let reranker_enabled = reranker.is_some();

        // Classify query to adapt fusion parameters.
        let query_type = classify_query(query);
        let query_params = params_for_query_type(query_type);
        let rrf_k = query_params.rrf_k;
        let vector_candidates = effective_vector_candidates(fetch_limit, query_params);
        let rerank_candidates =
            effective_rerank_candidates(config.retrieval.rerank_candidates, result_limit);

        let ranking_stage = if reranker_enabled {
            RankingStage::PostRerank
        } else {
            RankingStage::Initial
        };

        let (results, hybrid_timings) = if let Some(reranker) = reranker {
            search_hybrid_reranked_with_stores(
                index_dir,
                provider,
                reranker,
                query,
                vector_query.as_ref(),
                filters,
                fetch_limit,
                result_limit,
                rrf_k,
                stored_dim,
                rerank_candidates,
                vector_candidates,
                crate::config::graph_augmentation_enabled(),
                Arc::clone(&stores),
            )
            .await?
        } else {
            search_hybrid_with_stores(
                index_dir,
                provider,
                query,
                vector_query.as_ref(),
                filters,
                fetch_limit,
                rrf_k,
                stored_dim,
                vector_candidates,
                Arc::clone(&stores),
            )
            .await?
        };

        let mut timings = SearchTimings::from(hybrid_timings);

        let aug_start = Instant::now();
        let indexed_files = stores.indexed_files()?;
        let metadata_store = stores
            .bm25_metadata
            .lock()
            .map_err(|_| anyhow::anyhow!("BM25 metadata store lock poisoned"))?;
        let results = augment_exact_match_candidates_with_store(
            &metadata_store,
            &indexed_files,
            query,
            results,
            ranking_stage,
            filters,
        )?;
        timings.augmentation = Some(aug_start.elapsed());

        timings.total = Some(total_start.elapsed());
        Ok((apply_filters(results, filters, result_limit), timings))
    }
}

/// Execute a search against the index at `index_dir`.
///
/// Attempts hybrid search (BM25 + vector + optional reranking). Falls
/// back to BM25-only when embedding API is unavailable.
pub fn execute_search(
    index_dir: &Path,
    query: &str,
    intent: Option<&str>,
    config: &VeraConfig,
    filters: &SearchFilters,
    result_limit: usize,
    backend: InferenceBackend,
) -> Result<(Vec<SearchResult>, SearchTimings)> {
    let rt = tokio::runtime::Runtime::new()?;
    let context = rt.block_on(SearchContext::new(config, backend));
    rt.block_on(context.search(index_dir, query, intent, config, filters, result_limit))
}

/// Build the semantic query text used for embedding and reranking.
///
/// When an `--intent` is supplied it is prefixed as `intent: <intent> | <query>`
/// (intent whitespace collapsed) to steer the embedding model. The raw `query`
/// is returned unchanged when no usable intent is present. This prefixed form
/// must never reach BM25: Tantivy's `QueryParser` treats `intent:` as a field
/// query and there is no such field. See issue #20.
pub(crate) fn build_query_with_intent<'a>(
    query: &'a str,
    intent: Option<&str>,
) -> std::borrow::Cow<'a, str> {
    let intent = intent
        .map(|value| value.split_whitespace().collect::<Vec<_>>().join(" "))
        .filter(|value| !value.is_empty());
    match intent {
        // Only allocate when an intent prefix is actually applied; otherwise
        // borrow the raw query.
        Some(intent) => std::borrow::Cow::Owned(format!("intent: {intent} | {query}")),
        None => std::borrow::Cow::Borrowed(query),
    }
}

/// Compute how many candidates to keep through fusion before final truncation.
///
/// Broad natural-language queries need a larger pool even without explicit
/// filters so deterministic ranking can surface structural chunks that raw RRF
/// scores placed outside the requested result window.
fn compute_fetch_limit(query: &str, filters: &SearchFilters, result_limit: usize) -> usize {
    let mut fetch_limit = if filters.is_empty() {
        result_limit
    } else {
        result_limit.saturating_mul(3).max(result_limit + 20)
    };

    // Path globs are applied post-retrieval, so we need a much larger pool
    // to ensure enough matching files survive filtering.
    if !filters.path_glob.is_empty() {
        fetch_limit = fetch_limit.max(result_limit.saturating_mul(10).max(result_limit + 100));
    }

    if filters.exact_paths.is_some() {
        fetch_limit = fetch_limit.max(result_limit.saturating_mul(12).max(result_limit + 200));
    }

    if needs_structural_overfetch(query, filters) {
        fetch_limit = fetch_limit.max(result_limit.saturating_mul(8).max(result_limit + 140));
    } else if matches!(classify_query(query), QueryType::NaturalLanguage) {
        fetch_limit = fetch_limit.max(result_limit.saturating_mul(3).max(result_limit + 40));
    }

    fetch_limit
}

fn needs_structural_overfetch(query: &str, filters: &SearchFilters) -> bool {
    matches!(classify_query(query), QueryType::NaturalLanguage)
        && query.split_whitespace().count() >= 4
        && filters.path_glob.is_empty()
        && filters.exact_paths.is_none()
        && filters.symbol_type.is_none()
        && !is_path_weighted_query(query)
}

fn effective_vector_candidates(
    fetch_limit: usize,
    query_params: crate::retrieval::query_classifier::QueryParams,
) -> usize {
    compute_vector_candidates(fetch_limit, query_params.vector_candidate_multiplier)
}

fn effective_rerank_candidates(configured: usize, result_limit: usize) -> usize {
    configured.max(result_limit)
}

/// Decide whether this query wants the cross-encoder reranker.
///
/// Skip heuristics (short identifier / path-weighted / exact-path or
/// symbol-type filtered lookups) are based on the raw query. But when the user
/// supplies an `--intent`, they are asking for semantic ranking, so the
/// reranker must run even for short raw queries — otherwise the intent-enriched
/// query would never reach the cross-encoder. See issue #20.
///
/// This answers only "does this query want reranking", never "is a reranker
/// available": it is what gates the session build, so it must not need one.
fn reranking_wanted(has_intent: bool, query: &str, filters: &SearchFilters) -> bool {
    has_intent || !should_skip_reranking(query, filters)
}

fn should_skip_reranking(query: &str, filters: &SearchFilters) -> bool {
    let word_count = query.split_whitespace().count();
    filters.exact_paths.is_some()
        || filters.symbol_type.is_some()
        || is_path_weighted_query(query)
        || (matches!(classify_query(query), QueryType::Identifier) && word_count <= 2)
}

fn run_bm25_only(
    query: &str,
    filters: &SearchFilters,
    fetch_limit: usize,
    result_limit: usize,
    total_start: Instant,
    stores: &Arc<SearchStores>,
) -> Result<(Vec<SearchResult>, SearchTimings)> {
    let bm25_start = Instant::now();
    let metadata_store = stores
        .bm25_metadata
        .lock()
        .map_err(|_| anyhow::anyhow!("BM25 metadata store lock poisoned"))?;
    let results = search_bm25_with_stores_and_filters(
        &stores.bm25,
        &metadata_store,
        query,
        filters,
        fetch_limit,
    )?;
    let bm25_elapsed = bm25_start.elapsed();
    let aug_start = Instant::now();
    let indexed_files = stores.indexed_files()?;
    let results = augment_exact_match_candidates_with_store(
        &metadata_store,
        &indexed_files,
        query,
        results,
        RankingStage::Initial,
        filters,
    )?;
    let timings = SearchTimings {
        bm25: Some(bm25_elapsed),
        augmentation: Some(aug_start.elapsed()),
        total: Some(total_start.elapsed()),
        ..Default::default()
    };
    Ok((apply_filters(results, filters, result_limit), timings))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::retrieval::exact_matches::augment_exact_match_candidates;
    use crate::storage::bm25::{Bm25Document, Bm25Index};
    use crate::storage::metadata::MetadataStore;
    use crate::test_env::run_env_test;
    use crate::types::Language;
    use crate::types::{Chunk, SymbolType};
    use tempfile::tempdir;

    #[test]
    fn test_dimension_mismatch_and_inference() {
        run_env_test(
            "retrieval::search_service::tests::test_dimension_mismatch_and_inference_probe",
            &[
                ("EMBEDDING_MODEL_BASE_URL", Some("http://127.0.0.1:0")),
                ("EMBEDDING_MODEL_ID", Some("dummy-api-model")),
                ("EMBEDDING_MODEL_API_KEY", Some("dummy-key")),
            ],
        );
    }

    #[test]
    #[ignore = "driven by test_dimension_mismatch_and_inference"]
    fn test_dimension_mismatch_and_inference_probe() {
        crate::init_tls();
        let dir = tempdir().unwrap();
        let index_dir = dir.path();

        let metadata_path = index_dir.join("metadata.db");
        let store = MetadataStore::open(&metadata_path).unwrap();

        // 1. Test dimension mismatch (requires local model so provider_dim is Some(768))
        store
            .set_index_meta("model_name", "jina-embeddings-v5-text-nano-retrieval")
            .unwrap();
        store.set_index_meta("embedding_dim", "1024").unwrap(); // Mismatch: 1024 vs 768

        let config = VeraConfig::default();
        let filters = SearchFilters::default();

        // This attempts local provider creation first, then falls back to BM25 when possible.
        // In this synthetic test fixture the BM25 index is absent, so either path may surface.
        {
            let res = execute_search(
                index_dir,
                "test",
                None,
                &config,
                &filters,
                10,
                crate::config::InferenceBackend::OnnxJina(
                    crate::config::OnnxExecutionProvider::Cpu,
                ),
            );
            if let Err(err) = res {
                let err_msg = err.to_string();
                assert!(
                    err_msg.contains("tantivy")
                        || err_msg.contains("Failed to initialize local embedding provider")
                        || err_msg.contains("No such file")
                        || err_msg.contains("not found"),
                    "{}",
                    err_msg
                );
            }
        }

        // 2. Test metadata-dimension inference path (API provider returns None for expected_dim)
        // The dummy provider credentials are already set by the guard above.
        store
            .set_index_meta("model_name", "dummy-api-model")
            .unwrap();
        store.set_index_meta("embedding_dim", "123").unwrap();

        // Calling execute_search with is_local = false
        // It will pass the metadata check (model_name matches), skip mismatch check (expected_dim is None),
        // infer stored_dim = 123, and proceed to search.
        // Since the index is empty, it will return Ok([]) without making network calls.
        let res = execute_search(
            index_dir,
            "test",
            None,
            &config,
            &filters,
            10,
            crate::config::InferenceBackend::Api,
        );
        assert!(res.is_ok(), "Expected Ok but got {:?}", res);
    }

    #[test]
    fn model_metadata_mismatch_falls_back_to_bm25() {
        run_env_test(
            "retrieval::search_service::tests::model_metadata_mismatch_falls_back_to_bm25_probe",
            &[
                ("EMBEDDING_MODEL_BASE_URL", Some("http://127.0.0.1:0")),
                ("EMBEDDING_MODEL_ID", Some("active-api-model")),
                ("EMBEDDING_MODEL_API_KEY", Some("dummy-key")),
            ],
        );
    }

    #[test]
    #[ignore = "driven by model_metadata_mismatch_falls_back_to_bm25"]
    fn model_metadata_mismatch_falls_back_to_bm25_probe() {
        crate::init_tls();
        let dir = tempdir().unwrap();
        let index_dir = dir.path();

        let store = MetadataStore::open(&index_dir.join("metadata.db")).unwrap();
        store
            .insert_chunks(&[Chunk {
                id: "auth:0".to_string(),
                file_path: "src/auth.rs".to_string(),
                line_start: 1,
                line_end: 4,
                content: "pub fn authenticate_user() -> bool { true }".to_string(),
                language: Language::Rust,
                symbol_type: Some(SymbolType::Function),
                symbol_name: Some("authenticate_user".to_string()),
            }])
            .unwrap();
        store.set_index_meta("model_name", "indexed-model").unwrap();
        store.set_index_meta("embedding_dim", "64").unwrap();

        let bm25 = Bm25Index::open(&index_dir.join("bm25")).unwrap();
        bm25.insert_batch(&[Bm25Document {
            chunk_id: "auth:0",
            file_path: "src/auth.rs",
            content: "pub fn authenticate_user() -> bool { true }",
            symbol_name: Some("authenticate_user"),
            language: "rust",
        }])
        .unwrap();

        let mut config = VeraConfig::default();
        config.embedding.timeout_secs = 1;
        config.embedding.max_retries = 0;
        let filters = SearchFilters::default();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let context = rt.block_on(SearchContext::new(
            &config,
            crate::config::InferenceBackend::Api,
        ));

        let (results, timings) = rt
            .block_on(context.search(index_dir, "authenticate user", None, &config, &filters, 10))
            .unwrap();

        assert_eq!(results[0].file_path, "src/auth.rs");
        assert!(timings.bm25.is_some());
        assert!(timings.vector.is_none());
    }

    #[test]
    fn document_prefix_mismatch_falls_back_to_bm25() {
        run_env_test(
            "retrieval::search_service::tests::document_prefix_mismatch_falls_back_to_bm25_probe",
            &[
                ("EMBEDDING_MODEL_BASE_URL", Some("http://127.0.0.1:0")),
                ("EMBEDDING_MODEL_ID", Some("indexed-model")),
                ("EMBEDDING_MODEL_API_KEY", Some("dummy-key")),
            ],
        );
    }

    #[test]
    #[ignore = "driven by document_prefix_mismatch_falls_back_to_bm25"]
    fn document_prefix_mismatch_falls_back_to_bm25_probe() {
        crate::init_tls();
        let dir = tempdir().unwrap();
        let index_dir = dir.path();

        let store = MetadataStore::open(&index_dir.join("metadata.db")).unwrap();
        store
            .insert_chunks(&[Chunk {
                id: "auth:0".to_string(),
                file_path: "src/auth.rs".to_string(),
                line_start: 1,
                line_end: 4,
                content: "pub fn authenticate_user() -> bool { true }".to_string(),
                language: Language::Rust,
                symbol_type: Some(SymbolType::Function),
                symbol_name: Some("authenticate_user".to_string()),
            }])
            .unwrap();
        store.set_index_meta("model_name", "indexed-model").unwrap();
        store.set_index_meta("embedding_dim", "64").unwrap();
        // The index was built with a document prefix, but the active provider
        // configuration has none: the stored vectors are in another space.
        store
            .set_index_meta("document_prefix", "passage: ")
            .unwrap();

        let bm25 = Bm25Index::open(&index_dir.join("bm25")).unwrap();
        bm25.insert_batch(&[Bm25Document {
            chunk_id: "auth:0",
            file_path: "src/auth.rs",
            content: "pub fn authenticate_user() -> bool { true }",
            symbol_name: Some("authenticate_user"),
            language: "rust",
        }])
        .unwrap();

        let mut config = VeraConfig::default();
        config.embedding.timeout_secs = 1;
        config.embedding.max_retries = 0;
        let filters = SearchFilters::default();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let context = rt.block_on(SearchContext::new(
            &config,
            crate::config::InferenceBackend::Api,
        ));

        let (results, timings) = rt
            .block_on(context.search(index_dir, "authenticate user", None, &config, &filters, 10))
            .unwrap();

        assert_eq!(results[0].file_path, "src/auth.rs");
        assert!(timings.bm25.is_some());
        assert!(timings.vector.is_none());
    }

    #[test]
    fn bm25_only_search_fills_path_scoped_results_from_deeper_pool() {
        let dir = tempdir().unwrap();
        let index_dir = dir.path();
        let metadata_store = MetadataStore::open(&index_dir.join("metadata.db")).unwrap();
        let bm25 = Bm25Index::open(&index_dir.join("bm25")).unwrap();

        let mut chunks = Vec::new();
        for i in 0..160 {
            chunks.push(Chunk {
                id: format!("noise:{i}"),
                file_path: format!("other/dependency_injection_work_{i}.py"),
                line_start: 1,
                line_end: 4,
                content:
                    "def dependency_injection_work():\n    dependency injection work dependency injection work"
                        .to_string(),
                language: Language::Python,
                symbol_type: Some(SymbolType::Function),
                symbol_name: Some("dependency_injection_work".to_string()),
            });
        }
        chunks.push(Chunk {
            id: "fastapi:dependency".to_string(),
            file_path: "fastapi/dependencies/utils.py".to_string(),
            line_start: 42,
            line_end: 55,
            content: "def solve_dependencies():\n    \"\"\"Resolve dependency injection for request handlers.\"\"\"\n    return values"
                .to_string(),
            language: Language::Python,
            symbol_type: Some(SymbolType::Function),
            symbol_name: Some("solve_dependencies".to_string()),
        });

        metadata_store.insert_chunks(&chunks).unwrap();
        let lang_strings: Vec<String> = chunks.iter().map(|c| c.language.to_string()).collect();
        let docs: Vec<Bm25Document<'_>> = chunks
            .iter()
            .zip(lang_strings.iter())
            .map(|(chunk, language)| Bm25Document {
                chunk_id: &chunk.id,
                file_path: &chunk.file_path,
                content: &chunk.content,
                symbol_name: chunk.symbol_name.as_deref(),
                language,
            })
            .collect();
        bm25.insert_batch(&docs).unwrap();

        let filters = SearchFilters {
            path_glob: vec!["fastapi/**".to_string()],
            ..Default::default()
        };
        let rt = tokio::runtime::Runtime::new().unwrap();
        let context = SearchContext::bm25_only();

        let (results, timings) = rt
            .block_on(context.search(
                index_dir,
                "how does dependency injection work",
                None,
                &VeraConfig::default(),
                &filters,
                5,
            ))
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].file_path, "fastapi/dependencies/utils.py");
        assert!(timings.bm25.is_some());
        // The query above is one `reranking_wanted` accepts, so this pins the
        // invariant `bm25_only`'s placeholder backend rests on: `search` returns
        // on the BM25-only path before any reranker is resolved.
        assert_eq!(
            context.reranker_build_count(),
            0,
            "a context with no embedding provider must never construct a reranker"
        );
    }

    #[test]
    fn build_query_with_intent_formats_and_normalizes() {
        // No intent: raw query borrowed unchanged (this is what BM25 receives).
        let none = build_query_with_intent("test query", None);
        assert_eq!(none.as_ref(), "test query");
        assert!(matches!(none, std::borrow::Cow::Borrowed(_)));
        // Empty / whitespace-only intent collapses to no prefix (still borrowed).
        let empty = build_query_with_intent("test query", Some("   "));
        assert_eq!(empty.as_ref(), "test query");
        assert!(matches!(empty, std::borrow::Cow::Borrowed(_)));
        // Intent present: owned prefixed form with whitespace collapsed.
        let some = build_query_with_intent("test query", Some("find  auth\n handlers"));
        assert_eq!(some.as_ref(), "intent: find auth handlers | test query");
        assert!(matches!(some, std::borrow::Cow::Owned(_)));
    }

    #[test]
    fn reranking_runs_for_intent_searches_with_short_queries() {
        let filters = SearchFilters::default();
        // A short identifier query alone is skipped by the rerank heuristic.
        assert!(should_skip_reranking("authenticate", &filters));
        // Without intent that means reranking is off...
        assert!(!reranking_wanted(false, "authenticate", &filters));
        // ...but an intent forces the cross-encoder to run so it sees the
        // intent-enriched query (issue #20 regression guard).
        assert!(reranking_wanted(true, "authenticate", &filters));
        // Natural-language query without intent still reranks normally.
        assert!(reranking_wanted(false, "how does auth work", &filters));
    }

    /// The cross-encoder session must not be built for queries that skip
    /// reranking (issue #100), and must be built once, not per query, for those
    /// that need it.
    ///
    /// The result sets are identical either way, so this asserts construction
    /// directly via the build counter rather than any search output.
    #[test]
    fn reranker_is_built_only_for_queries_that_rerank() {
        run_env_test(
            "retrieval::search_service::tests::reranker_is_built_only_for_queries_that_rerank_probe",
            &[
                ("EMBEDDING_MODEL_BASE_URL", Some("http://127.0.0.1:0")),
                ("EMBEDDING_MODEL_ID", Some("dummy-api-model")),
                ("EMBEDDING_MODEL_API_KEY", Some("dummy-key")),
                ("RERANKER_MODEL_BASE_URL", Some("http://127.0.0.1:0")),
                ("RERANKER_MODEL_ID", Some("dummy-reranker-model")),
                ("RERANKER_MODEL_API_KEY", Some("dummy-key")),
            ],
        );
    }

    #[tokio::test]
    #[ignore = "driven by reranker_is_built_only_for_queries_that_rerank"]
    async fn reranker_is_built_only_for_queries_that_rerank_probe() {
        crate::init_tls();
        let mut config = VeraConfig::default();
        config.retrieval.reranking_enabled = true;
        let filters = SearchFilters::default();
        let context = SearchContext::new(&config, crate::config::InferenceBackend::Api).await;

        // Nothing is built up front, which is the whole point.
        assert_eq!(context.reranker_build_count(), 0);

        // Short identifier query: skipped by the heuristic, so no session.
        assert!(!reranking_wanted(false, "Bm25Index", &filters));
        assert!(
            context
                .reranker_for_query(&config, false, "Bm25Index", &filters)
                .await
                .is_none()
        );
        assert_eq!(
            context.reranker_build_count(),
            0,
            "a query that skips reranking must not construct the reranker"
        );

        // Natural-language query: needs the cross-encoder, so build it now.
        assert!(
            context
                .reranker_for_query(
                    &config,
                    false,
                    "how are embeddings batched during indexing",
                    &filters
                )
                .await
                .is_some()
        );
        assert_eq!(context.reranker_build_count(), 1);

        // A second reranking query reuses the cached session: laziness is per
        // context, so a long MCP session does not pay repeatedly.
        assert!(
            context
                .reranker_for_query(&config, false, "how does auth work", &filters)
                .await
                .is_some()
        );
        assert_eq!(context.reranker_build_count(), 1);
    }

    #[test]
    fn path_glob_filters_do_not_skip_reranking() {
        let filters = SearchFilters {
            path_glob: vec!["crates/vera-core/**".to_string()],
            ..Default::default()
        };

        assert!(!should_skip_reranking(
            "how does dependency injection work",
            &filters
        ));
    }

    #[test]
    fn rerank_candidate_depth_is_independent_of_fetch_depth() {
        assert_eq!(effective_rerank_candidates(20, 5), 20);
        assert_eq!(
            effective_rerank_candidates(4, 5),
            5,
            "reranking must cover enough candidates to return the requested result count"
        );

        // Vector candidates use query_params multiplier without inflation
        let nl_params =
            params_for_query_type(crate::retrieval::query_classifier::QueryType::NaturalLanguage);
        let vc = effective_vector_candidates(10, nl_params);
        assert!(vc >= 50); // at least the minimum from compute_vector_candidates
    }

    #[test]
    fn broad_nl_queries_overfetch_before_ranking() {
        let filters = SearchFilters::default();

        assert_eq!(compute_fetch_limit("Config", &filters, 20), 20);
        assert_eq!(
            compute_fetch_limit("file type detection and filtering", &filters, 20),
            160
        );
        assert_eq!(
            compute_fetch_limit(
                "how are HTTP errors handled and returned to clients",
                &filters,
                5
            ),
            145
        );
    }

    #[test]
    fn exact_identifier_queries_skip_reranking() {
        assert!(should_skip_reranking("Config", &SearchFilters::default()));
        assert!(should_skip_reranking(
            "src/config.ts",
            &SearchFilters::default()
        ));
        assert!(!should_skip_reranking(
            "how are HTTP errors handled",
            &SearchFilters::default()
        ));
    }

    #[test]
    fn exact_identifier_lookup_finds_matching_symbol() {
        let dir = tempdir().unwrap();
        let metadata_path = dir.path().join("metadata.db");
        let store = MetadataStore::open(&metadata_path).unwrap();
        store
            .insert_chunks(&[Chunk {
                id: "sink:0".to_string(),
                file_path: "crates/searcher/src/sink.rs".to_string(),
                line_start: 102,
                line_end: 223,
                content: "pub trait Sink {}".to_string(),
                language: Language::Rust,
                symbol_type: Some(SymbolType::Trait),
                symbol_name: Some("Sink".to_string()),
            }])
            .unwrap();

        let augmented = augment_exact_match_candidates(
            dir.path(),
            "Sink trait and its implementations",
            Vec::new(),
            RankingStage::Initial,
            &SearchFilters::default(),
        )
        .unwrap();

        assert!(
            augmented
                .iter()
                .any(|result| result.symbol_name.as_deref() == Some("Sink"))
        );
    }

    #[test]
    fn exact_identifier_prefers_public_type_definition() {
        let dir = tempdir().unwrap();
        let metadata_path = dir.path().join("metadata.db");
        let store = MetadataStore::open(&metadata_path).unwrap();
        store
            .insert_chunks(&[
                Chunk {
                    id: "config:0".to_string(),
                    file_path: "crates/core/search.rs".to_string(),
                    line_start: 19,
                    line_end: 25,
                    content: "struct Config {\n    search_zip: bool,\n}".to_string(),
                    language: Language::Rust,
                    symbol_type: Some(SymbolType::Struct),
                    symbol_name: Some("Config".to_string()),
                },
                Chunk {
                    id: "config:1".to_string(),
                    file_path: "crates/regex/src/config.rs".to_string(),
                    line_start: 25,
                    line_end: 43,
                    content: "pub(crate) struct Config {\n    pub(crate) multi_line: bool,\n}".to_string(),
                    language: Language::Rust,
                    symbol_type: Some(SymbolType::Struct),
                    symbol_name: Some("Config".to_string()),
                },
                Chunk {
                    id: "config:2".to_string(),
                    file_path: "crates/searcher/src/searcher/mod.rs".to_string(),
                    line_start: 151,
                    line_end: 185,
                    content: "pub struct Config {\n    line_term: LineTerminator,\n    multi_line: bool,\n}".to_string(),
                    language: Language::Rust,
                    symbol_type: Some(SymbolType::Struct),
                    symbol_name: Some("Config".to_string()),
                },
            ])
            .unwrap();

        let augmented = augment_exact_match_candidates(
            dir.path(),
            "Config",
            Vec::new(),
            RankingStage::Initial,
            &SearchFilters::default(),
        )
        .unwrap();

        assert_eq!(
            augmented[0].file_path,
            "crates/searcher/src/searcher/mod.rs"
        );
    }

    #[test]
    fn multi_query_exact_matches_are_promoted_after_fusion() {
        let dir = tempdir().unwrap();
        let metadata_path = dir.path().join("metadata.db");
        let store = MetadataStore::open(&metadata_path).unwrap();
        store
            .insert_chunks(&[
                Chunk {
                    id: "kimi:0".to_string(),
                    file_path: "backend/crates/omnigate-auth/src/kimi.rs".to_string(),
                    line_start: 265,
                    line_end: 275,
                    content: "pub fn persist_kimi_auth_record() {}".to_string(),
                    language: Language::Rust,
                    symbol_type: Some(SymbolType::Function),
                    symbol_name: Some("persist_kimi_auth_record".to_string()),
                },
                Chunk {
                    id: "factory:0".to_string(),
                    file_path: "backend/crates/omnigate-auth/src/factory.rs".to_string(),
                    line_start: 286,
                    line_end: 296,
                    content: "pub fn persist_factory_auth_record() {}".to_string(),
                    language: Language::Rust,
                    symbol_type: Some(SymbolType::Function),
                    symbol_name: Some("persist_factory_auth_record".to_string()),
                },
                Chunk {
                    id: "lib:0".to_string(),
                    file_path: "backend/crates/omnigate-auth/src/lib.rs".to_string(),
                    line_start: 10,
                    line_end: 40,
                    content: "pub use crate::kimi::persist_kimi_auth_record;".to_string(),
                    language: Language::Rust,
                    symbol_type: Some(SymbolType::Module),
                    symbol_name: Some("omnigate_auth".to_string()),
                },
            ])
            .unwrap();

        let fused = vec![
            SearchResult {
                file_path: "backend/crates/omnigate-auth/src/lib.rs".to_string(),
                line_start: 10,
                line_end: 40,
                content: "pub use crate::kimi::persist_kimi_auth_record;".to_string(),
                language: Language::Rust,
                score: 0.0,
                symbol_name: Some("omnigate_auth".to_string()),
                symbol_type: Some(SymbolType::Module),
            },
            SearchResult {
                file_path: "backend/crates/omnigate-auth/src/factory.rs".to_string(),
                line_start: 286,
                line_end: 296,
                content: "pub fn persist_factory_auth_record() {}".to_string(),
                language: Language::Rust,
                score: 0.0,
                symbol_name: Some("persist_factory_auth_record".to_string()),
                symbol_type: Some(SymbolType::Function),
            },
            SearchResult {
                file_path: "backend/crates/omnigate-auth/src/kimi.rs".to_string(),
                line_start: 265,
                line_end: 275,
                content: "pub fn persist_kimi_auth_record() {}".to_string(),
                language: Language::Rust,
                score: 0.0,
                symbol_name: Some("persist_kimi_auth_record".to_string()),
                symbol_type: Some(SymbolType::Function),
            },
        ];

        let queries = vec![
            "persist_kimi_auth_record".to_string(),
            "persist_factory_auth_record".to_string(),
        ];
        let augmented = augment_multi_query_exact_matches(
            dir.path(),
            &queries,
            fused,
            &SearchFilters::default(),
            5,
        )
        .unwrap();

        assert_eq!(
            augmented[0].symbol_name.as_deref(),
            Some("persist_kimi_auth_record")
        );
        assert_eq!(
            augmented[1].symbol_name.as_deref(),
            Some("persist_factory_auth_record")
        );
    }

    #[test]
    fn multi_query_exact_matches_interleave_across_queries() {
        let dir = tempdir().unwrap();
        let metadata_path = dir.path().join("metadata.db");
        let store = MetadataStore::open(&metadata_path).unwrap();

        let mut chunks: Vec<Chunk> = (0..5)
            .map(|i| Chunk {
                id: format!("common:{i}"),
                file_path: format!("src/common_{i}.rs"),
                line_start: 1,
                line_end: 10,
                content: "pub fn common_fn() {}".to_string(),
                language: Language::Rust,
                symbol_type: Some(SymbolType::Function),
                symbol_name: Some("common_fn".to_string()),
            })
            .collect();
        chunks.push(Chunk {
            id: "rare:0".to_string(),
            file_path: "src/rare.rs".to_string(),
            line_start: 1,
            line_end: 10,
            content: "pub fn rare_fn() {}".to_string(),
            language: Language::Rust,
            symbol_type: Some(SymbolType::Function),
            symbol_name: Some("rare_fn".to_string()),
        });
        store.insert_chunks(&chunks).unwrap();

        let augmented = augment_multi_query_exact_matches(
            dir.path(),
            &["common_fn".to_string(), "rare_fn".to_string()],
            Vec::new(),
            &SearchFilters::default(),
            3,
        )
        .unwrap();

        // The first query keeps the top slot, but the second query must
        // contribute instead of being crowded out by the first query's rows.
        assert_eq!(augmented.len(), 3);
        assert_eq!(augmented[0].symbol_name.as_deref(), Some("common_fn"));
        assert_eq!(augmented[1].symbol_name.as_deref(), Some("rare_fn"));
    }

    #[test]
    fn bare_filename_query_gets_exact_file_augmentation() {
        let dir = tempdir().unwrap();
        let metadata_path = dir.path().join("metadata.db");
        let store = MetadataStore::open(&metadata_path).unwrap();
        store
            .insert_chunks(&[
                Chunk {
                    id: "deep:0".to_string(),
                    file_path: "deep/nested/handler.py".to_string(),
                    line_start: 1,
                    line_end: 20,
                    content: "def handle(): pass".to_string(),
                    language: Language::Python,
                    symbol_type: Some(SymbolType::Function),
                    symbol_name: Some("handle".to_string()),
                },
                Chunk {
                    id: "shallow:0".to_string(),
                    file_path: "src/handler.py".to_string(),
                    line_start: 1,
                    line_end: 20,
                    content: "def handle(): pass".to_string(),
                    language: Language::Python,
                    symbol_type: Some(SymbolType::Function),
                    symbol_name: Some("handle".to_string()),
                },
            ])
            .unwrap();

        let augmented = augment_multi_query_exact_matches(
            dir.path(),
            &["handler.py".to_string()],
            Vec::new(),
            &SearchFilters::default(),
            5,
        )
        .unwrap();

        assert!(
            !augmented.is_empty(),
            "a bare filename query must inject exact file chunks"
        );
        assert_eq!(augmented[0].file_path, "src/handler.py");
    }
}