Skip to main content

reference_query/search/
mod.rs

1//! Search — the staged ranking pipeline.
2//!
3//! Layers 1–3 (exact/prefix, abbreviation-aware fuzzy, path) over the index,
4//! scored by an additive, `--explain`-able scorer. Layers 4–5 (live scan,
5//! opportunistic extraction) and true streaming/early-exit arrive in phase 2;
6//! for now the candidate set is gathered once and ranked.
7
8mod score;
9
10pub use score::{Boosts, Feature, Scored, confidence, match_positions, match_quality, path_stem};
11
12use std::collections::{HashMap, HashSet};
13use std::path::Path;
14use std::time::{Instant, SystemTime, UNIX_EPOCH};
15
16use crate::store::{Store, SymbolRow};
17
18/// Per-layer cap on candidates pulled from the store before ranking. Exact and
19/// prefix matches are guaranteed in full (see `Store::search_candidates`); this
20/// only bounds the broad first-char-anchor and trigram-fuzzy recall layers.
21/// Scoring is linear and cheap, so this sits well under the latency budget.
22const CANDIDATE_LIMIT: usize = 8000;
23
24/// Sentinel repository id for live-scan (Layer 4) results — distinct from any
25/// real row id, and treated as "the current repo" so the boost applies.
26const LIVE_REPO_ID: i64 = -1;
27
28/// Boost for a symbol whose file you're actively changing on this branch.
29const BRANCH_FILE_BOOST: f64 = 180.0;
30/// Smaller boost for a symbol in a directory you're changing (a neighbor).
31const BRANCH_DIR_BOOST: f64 = 60.0;
32
33/// Files you're working on this branch — those that differ from the trunk —
34/// plus the directories holding them. Symbols in those files (or their
35/// directory neighbors) get a branch boost. Empty on the trunk / outside git.
36#[derive(Debug, Default, Clone)]
37pub struct ActiveFiles {
38    files: HashSet<String>,
39    dirs: HashSet<String>,
40}
41
42impl ActiveFiles {
43    /// Build from a list of repo-relative paths changed on the branch.
44    pub fn new<I: IntoIterator<Item = String>>(paths: I) -> Self {
45        let files: HashSet<String> = paths.into_iter().collect();
46        let dirs = files
47            .iter()
48            .filter_map(|f| parent_dir(f))
49            .map(str::to_string)
50            .collect();
51        ActiveFiles { files, dirs }
52    }
53
54    fn is_empty(&self) -> bool {
55        self.files.is_empty()
56    }
57
58    /// The branch boost for a candidate's file: full if the file itself is
59    /// changing, smaller if a sibling in the same directory is.
60    fn boost(&self, path: &str) -> f64 {
61        if self.files.contains(path) {
62            BRANCH_FILE_BOOST
63        } else if parent_dir(path).is_some_and(|d| self.dirs.contains(d)) {
64            BRANCH_DIR_BOOST
65        } else {
66            0.0
67        }
68    }
69}
70
71/// The directory portion of a repo-relative path (`app/models/user.rb` →
72/// `app/models`), or `None` for a top-level file.
73fn parent_dir(path: &str) -> Option<&str> {
74    path.rfind('/').map(|i| &path[..i])
75}
76
77/// A ranked search result. Serializes for `--json` / `--ndjson`.
78#[derive(Debug, Clone, PartialEq, serde::Serialize)]
79pub struct Hit {
80    pub name: String,
81    pub kind: String,
82    pub language: String,
83    pub file: String,
84    pub line: i64,
85    /// 1-based last line of the definition — read `line..=end_line` for the whole
86    /// span. Omitted in JSON when unknown (a row indexed before end-line tracking).
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub end_line: Option<i64>,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub parent: Option<String>,
91    /// Access level (`public`/`crate`/`private`/`protected`) when the language
92    /// expresses one. Omitted when unknown.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub visibility: Option<String>,
95    #[serde(rename = "repo")]
96    pub repo_identity: String,
97    /// Raw additive score — the ranking key and the `--explain` breakdown source.
98    /// Not serialized: JSON exposes the normalized `confidence` instead.
99    #[serde(skip)]
100    pub score: f64,
101    /// Normalized match confidence in [0,1], filled before output (see
102    /// [`score::confidence`]). This is what JSON carries in place of the raw score.
103    pub confidence: f64,
104    /// The scoring features, serialized as their names in descending weight order
105    /// (the raw values are low-signal unnormalized; `--explain` shows them in text).
106    #[serde(serialize_with = "serialize_feature_names")]
107    pub features: Vec<Feature>,
108    /// The definition's source line (trimmed) — filled for displayed results in
109    /// machine-readable output. Omitted when unread (matching `--symbols`).
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub signature: Option<String>,
112    /// The full definition source (`line..=end_line`), filled only by `--show`.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub body: Option<String>,
115}
116
117/// Serialize a hit's features as a name list, strongest first — the values are
118/// unnormalized and low-signal, so the ordered names are the useful part.
119fn serialize_feature_names<S: serde::Serializer>(
120    features: &[Feature],
121    s: S,
122) -> Result<S::Ok, S::Error> {
123    use serde::Serialize;
124    let mut sorted: Vec<&Feature> = features.iter().collect();
125    sorted.sort_by(|a, b| b.value.total_cmp(&a.value));
126    let names: Vec<&str> = sorted.iter().map(|f| f.name).collect();
127    names.serialize(s)
128}
129
130/// Search the index for `query`, returning up to `limit` ranked hits.
131/// `current_repo_id` (if any) boosts results from the repository you're in;
132/// `only_repo` (if any) restricts results to that repository, so a search inside
133/// a repo answers about *that* repo rather than leaking others you've indexed;
134/// `active` boosts files you're changing on the current branch.
135pub fn search(
136    store: &Store,
137    query: &str,
138    current_repo_id: Option<i64>,
139    only_repo: Option<i64>,
140    active: &ActiveFiles,
141    limit: usize,
142) -> crate::store::Result<Vec<Hit>> {
143    // Recall keys off the leaf name only — a `Foo::Bar` qualifier targets the
144    // parent during scoring, and the store indexes `name`, not `parent`. A
145    // wildcard query then keys off its literal chars (the store indexes literal
146    // trigrams); the glob matches precisely during scoring.
147    let (leaf, _) = score::parse_qualified(query);
148    let stripped;
149    let recall = if score::has_wildcard(leaf) {
150        stripped = score::strip_wildcards(leaf);
151        stripped.as_str()
152    } else {
153        leaf
154    };
155    let trace_on = crate::trace::enabled();
156    let t = std::time::Instant::now();
157    let candidates = store.search_candidates(recall, CANDIDATE_LIMIT, score::has_wildcard(leaf))?;
158    let n_candidates = candidates.len();
159    let t_recall = t.elapsed();
160    let t = std::time::Instant::now();
161    let now = now_unix();
162    let learned = learned_boosts(store, query, now)?;
163
164    let mut hits: Vec<Hit> = candidates
165        .into_iter()
166        .filter_map(|c| {
167            // Repo scope: outside `--all-repos`, a search inside a repo returns
168            // only that repo's definitions — never another indexed repo's.
169            if only_repo.is_some_and(|r| r != c.repository_id) {
170                return None;
171            }
172            // learned is empty for most queries — skip the per-candidate
173            // String clones the key would cost
174            let learned_boost = if learned.is_empty() {
175                0.0
176            } else {
177                let key = (c.repository_id, c.file.clone(), c.name.clone());
178                learned.get(&key).copied().unwrap_or(0.0)
179            };
180            let boosts = Boosts {
181                learned: learned_boost,
182                // prefer whichever recency signal is more recent: a recent edit
183                // (mtime, stored in nanoseconds — convert to seconds) or a
184                // recent commit (git_ts, seconds)
185                recency: recency_boost(c.git_ts.max(c.mtime.map(|n| n / 1_000_000_000)), now),
186                branch: if active.is_empty() {
187                    0.0
188                } else {
189                    active.boost(&c.file)
190                },
191            };
192            rank_one(query, c, current_repo_id, boosts)
193        })
194        .collect();
195    let n_hits = hits.len();
196    let t_score = t.elapsed();
197
198    let t = std::time::Instant::now();
199    sort_and_truncate(&mut hits, limit);
200    if trace_on {
201        crate::trace!(
202            "search {query:?}: recall {n_candidates} cand in {} ms, score→{n_hits} hits in {} ms, sort {} ms",
203            t_recall.as_millis(),
204            t_score.as_millis(),
205            t.elapsed().as_millis(),
206        );
207    }
208    Ok(hits)
209}
210
211/// Symbols in recently-modified files rank higher. ~14-day half-life and no
212/// floor, so files untouched for a while contribute nothing.
213fn recency_boost(mtime: Option<i64>, now: i64) -> f64 {
214    let Some(mtime) = mtime else {
215        return 0.0;
216    };
217    let age_days = (now - mtime).max(0) as f64 / 86_400.0;
218    let boost = 120.0 * 0.5_f64.powf(age_days / 14.0);
219    if boost < 1.0 { 0.0 } else { boost }
220}
221
222/// Decay-weighted learned boosts for a query, keyed by `(repo, file, name)`.
223fn learned_boosts(
224    store: &Store,
225    query: &str,
226    now: i64,
227) -> crate::store::Result<HashMap<(i64, String, String), f64>> {
228    let q = query.to_ascii_lowercase();
229    let mut map: HashMap<(i64, String, String), f64> = HashMap::new();
230    for s in store.selections_for(&q)? {
231        // several stored queries can match (e.g. "han" and "handler"); keep the
232        // strongest boost for each candidate
233        let boost = learned_boost(s.selections, s.last_selected_at, now);
234        let entry = map.entry((s.repository_id, s.file, s.name)).or_insert(0.0);
235        *entry = entry.max(boost);
236    }
237    Ok(map)
238}
239
240/// Turn a selection count + recency into a ranking boost. Evidence ramps over
241/// ~5 selections; recency decays with a ~30-day half-life, floored so old picks
242/// still count for something.
243fn learned_boost(selections: i64, last_selected_at: i64, now: i64) -> f64 {
244    if selections <= 0 {
245        return 0.0;
246    }
247    let strength = (selections.min(5) as f64) / 5.0;
248    let age_days = (now - last_selected_at).max(0) as f64 / 86_400.0;
249    let recency = 0.5_f64.powf(age_days / 30.0).max(0.25);
250    260.0 * strength * recency
251}
252
253fn now_unix() -> i64 {
254    SystemTime::now()
255        .duration_since(UNIX_EPOCH)
256        .map(|d| d.as_secs() as i64)
257        .unwrap_or(0)
258}
259
260/// Layer 4: scan `root` live (no index required) and return ranked hits.
261/// Results are treated as the current repo, so the current-repo boost applies.
262/// `skip` names already-indexed files to ignore, and `deadline` bounds the scan
263/// — both empty/`None` for an unbounded scan of a never-indexed directory. When
264/// `prefilter` is set, only files containing the query (substring) are parsed —
265/// fast for exact/prefix/substring queries, but blind to fuzzy abbreviations, so
266/// callers retry with `prefilter = false` if a filtered scan finds nothing.
267pub fn live_search(
268    root: &Path,
269    query: &str,
270    limit: usize,
271    skip: &HashSet<String>,
272    deadline: Option<Instant>,
273    prefilter: bool,
274) -> Vec<Hit> {
275    let needle = prefilter.then_some(query.as_bytes());
276    let identity = crate::index::detect_identity(root).to_string();
277    let mut hits: Vec<Hit> = crate::index::scan(root, skip, deadline, needle)
278        .into_iter()
279        .flat_map(|fs| fs.symbols)
280        .filter_map(|s| {
281            let row = SymbolRow {
282                name: s.name,
283                kind: s.kind.as_str().to_string(),
284                language: s.language,
285                file: s.file,
286                line: s.line as i64,
287                end_line: Some(s.end_line as i64),
288                parent: s.parent,
289                repository_id: LIVE_REPO_ID,
290                repo_identity: identity.clone(),
291                mtime: None,
292                git_ts: None,
293                visibility: s.visibility.map(str::to_string),
294            };
295            rank_one(query, row, Some(LIVE_REPO_ID), Boosts::default())
296        })
297        .collect();
298    sort_and_truncate(&mut hits, limit);
299    hits
300}
301
302/// Merge two ranked lists, de-duplicating by location and name (keeping the
303/// higher score), then re-rank and truncate. Used to blend index and live-scan
304/// results.
305pub fn merge(a: Vec<Hit>, b: Vec<Hit>, limit: usize) -> Vec<Hit> {
306    use std::collections::HashMap;
307    let mut by_key: HashMap<(String, i64, String), Hit> = HashMap::new();
308    for hit in a.into_iter().chain(b) {
309        let key = (hit.file.clone(), hit.line, hit.name.clone());
310        match by_key.get(&key) {
311            Some(existing) if existing.score >= hit.score => {}
312            _ => {
313                by_key.insert(key, hit);
314            }
315        }
316    }
317    let mut hits: Vec<Hit> = by_key.into_values().collect();
318    sort_and_truncate(&mut hits, limit);
319    hits
320}
321
322/// Scope gate for a qualified query (`Foo::Bar#baz`). When the user names an
323/// enclosing scope and at least one result actually sits in it, drop the rest —
324/// a `baz` outside `Foo::Bar` is noise next to the one inside it, the same way
325/// the relevance gate drops fuzzy near-matches beside an exact hit. When
326/// *nothing* matches the scope, the list is left untouched: the scope was a
327/// hint, and the definition may simply live somewhere we didn't expect, so a
328/// `baz` elsewhere still surfaces rather than returning empty.
329///
330/// An in-scope result is one the scorer gave the `parent` feature — i.e. its
331/// recorded parent ends with the qualifier's scope chain.
332pub fn apply_scope_gate(query: &str, hits: &mut Vec<Hit>) {
333    if score::parse_qualified(query).1.is_none() {
334        return; // unqualified query — nothing to gate on
335    }
336    let in_scope = |h: &Hit| h.features.iter().any(|f| f.name == "parent");
337    if hits.iter().any(in_scope) {
338        hits.retain(in_scope);
339    }
340}
341
342/// Highest score first; ties broken toward shorter (more specific) names.
343fn sort_and_truncate(hits: &mut Vec<Hit>, limit: usize) {
344    hits.sort_by(|a, b| {
345        b.score
346            .partial_cmp(&a.score)
347            .unwrap_or(std::cmp::Ordering::Equal)
348            .then_with(|| a.name.len().cmp(&b.name.len()))
349            .then_with(|| a.name.cmp(&b.name))
350    });
351    hits.truncate(limit);
352}
353
354fn rank_one(
355    query: &str,
356    c: SymbolRow,
357    current_repo_id: Option<i64>,
358    boosts: Boosts,
359) -> Option<Hit> {
360    let scored = score::score(query, &c, current_repo_id, boosts)?;
361    Some(Hit {
362        name: c.name,
363        kind: c.kind,
364        language: c.language,
365        file: c.file,
366        line: c.line,
367        end_line: c.end_line,
368        parent: c.parent,
369        visibility: c.visibility,
370        repo_identity: c.repo_identity,
371        score: scored.total,
372        confidence: 0.0, // filled from the final result set before output
373        features: scored.features,
374        signature: None,
375        body: None,
376    })
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use crate::core::{Kind, Symbol};
383
384    fn sym(name: &str, kind: Kind) -> Symbol {
385        Symbol {
386            name: name.into(),
387            kind,
388            language: "ruby".into(),
389            file: "app/x.rb".into(),
390            line: 1,
391            end_line: 1,
392            parent: None,
393            visibility: None,
394        }
395    }
396
397    fn store_with(symbols: &[Symbol]) -> Store {
398        let mut store = Store::open_in_memory().unwrap();
399        let repo = store
400            .upsert_repository(&crate::core::RepoIdentity::local("/tmp/x"), None)
401            .unwrap();
402        store
403            .replace_file_symbols(repo, "app/x.rb", "ruby", None, "h", symbols)
404            .unwrap();
405        store
406    }
407
408    fn names(hits: &[Hit]) -> Vec<&str> {
409        hits.iter().map(|h| h.name.as_str()).collect()
410    }
411
412    /// Two repos, each with its own symbol, so scoping can be exercised.
413    fn store_two_repos() -> (Store, i64, i64) {
414        let mut store = Store::open_in_memory().unwrap();
415        let a = store
416            .upsert_repository(&crate::core::RepoIdentity::local("/tmp/a"), None)
417            .unwrap();
418        let b = store
419            .upsert_repository(&crate::core::RepoIdentity::local("/tmp/b"), None)
420            .unwrap();
421        store
422            .replace_file_symbols(a, "a.rb", "ruby", None, "h", &[sym("Widget", Kind::Class)])
423            .unwrap();
424        store
425            .replace_file_symbols(b, "b.rb", "ruby", None, "h", &[sym("Widget", Kind::Class)])
426            .unwrap();
427        (store, a, b)
428    }
429
430    #[test]
431    fn only_repo_scopes_results_to_that_repo() {
432        let (store, a, b) = store_two_repos();
433        // scoped to repo A: only A's Widget, never B's
434        let hits = search(
435            &store,
436            "Widget",
437            Some(a),
438            Some(a),
439            &ActiveFiles::default(),
440            10,
441        )
442        .unwrap();
443        assert_eq!(hits.len(), 1);
444        assert_eq!(hits[0].repo_identity, "local:/tmp/a");
445        // no scope (--all-repos): both repos' Widgets surface
446        let all = search(&store, "Widget", Some(a), None, &ActiveFiles::default(), 10).unwrap();
447        assert_eq!(all.len(), 2);
448        let _ = b;
449    }
450
451    #[test]
452    fn scoped_search_reports_no_match_rather_than_leaking_another_repo() {
453        let (store, a, _b) = store_two_repos();
454        // "Gadget" exists in neither; scoped to A it's simply absent (not B's)
455        let hits = search(
456            &store,
457            "Gadget",
458            Some(a),
459            Some(a),
460            &ActiveFiles::default(),
461            10,
462        )
463        .unwrap();
464        assert!(hits.is_empty());
465    }
466
467    #[test]
468    fn ranks_exact_match_first() {
469        let store = store_with(&[
470            sym("Users", Kind::Class),
471            sym("User", Kind::Class),
472            sym("UserMailer", Kind::Class),
473        ]);
474        let hits = search(&store, "user", None, None, &ActiveFiles::default(), 10).unwrap();
475        assert_eq!(hits[0].name, "User");
476    }
477
478    #[test]
479    fn abbreviation_finds_the_intended_symbol() {
480        let store = store_with(&[
481            sym("RefundProcessor", Kind::Class),
482            sym("Refund", Kind::Class),
483            sym("Payment", Kind::Class),
484        ]);
485        let hits = search(
486            &store,
487            "refundproc",
488            None,
489            None,
490            &ActiveFiles::default(),
491            10,
492        )
493        .unwrap();
494        assert_eq!(hits[0].name, "RefundProcessor");
495        assert!(!names(&hits).contains(&"Payment"));
496    }
497
498    #[test]
499    fn short_fuzzy_query_still_resolves() {
500        let store = store_with(&[sym("User", Kind::Class), sym("Account", Kind::Class)]);
501        let hits = search(&store, "usr", None, None, &ActiveFiles::default(), 10).unwrap();
502        assert_eq!(hits[0].name, "User");
503    }
504
505    #[test]
506    fn no_match_returns_empty() {
507        let store = store_with(&[sym("User", Kind::Class)]);
508        let hits = search(&store, "zzzzz", None, None, &ActiveFiles::default(), 10).unwrap();
509        assert!(hits.is_empty());
510    }
511
512    #[test]
513    fn merge_dedups_by_location_keeping_higher_score() {
514        let mk = |name: &str, score: f64| Hit {
515            name: name.into(),
516            kind: "class".into(),
517            language: "ruby".into(),
518            file: "a.rb".into(),
519            line: 1,
520            end_line: Some(1),
521            parent: None,
522            visibility: None,
523            repo_identity: "r".into(),
524            score,
525            confidence: 0.0,
526            features: vec![],
527            signature: None,
528            body: None,
529        };
530        let from_index = vec![mk("User", 100.0)];
531        let from_live = vec![mk("User", 500.0), mk("Account", 200.0)];
532        let merged = merge(from_index, from_live, 10);
533        assert_eq!(merged.len(), 2, "the duplicate User is collapsed");
534        assert_eq!(merged[0].name, "User");
535        assert_eq!(merged[0].score, 500.0, "the higher-scored duplicate wins");
536    }
537
538    #[test]
539    fn active_files_boosts_the_file_and_its_neighbors() {
540        let active = ActiveFiles::new(["app/services/refund.rb".to_string()]);
541        // the changed file itself: full boost
542        assert_eq!(active.boost("app/services/refund.rb"), BRANCH_FILE_BOOST);
543        // a sibling in the same directory: neighbor boost
544        assert_eq!(active.boost("app/services/charge.rb"), BRANCH_DIR_BOOST);
545        // unrelated directory: nothing
546        assert_eq!(active.boost("app/models/user.rb"), 0.0);
547    }
548
549    fn nested(name: &str, kind: Kind, parent: &str) -> Symbol {
550        Symbol {
551            parent: Some(parent.into()),
552            ..sym(name, kind)
553        }
554    }
555
556    #[test]
557    fn qualified_query_ranks_the_definition_in_the_named_scope() {
558        let store = store_with(&[
559            nested("Config", Kind::Class, "Baz"),
560            nested("Config", Kind::Class, "Foo"),
561            nested("Config", Kind::Class, "Qux"),
562        ]);
563        // `Foo::Config` should surface the Config nested under Foo first
564        let hits = search(
565            &store,
566            "Foo::Config",
567            None,
568            None,
569            &ActiveFiles::default(),
570            10,
571        )
572        .unwrap();
573        assert_eq!(hits[0].parent.as_deref(), Some("Foo"));
574        assert!(hits[0].features.iter().any(|f| f.name == "parent"));
575    }
576
577    #[test]
578    fn qualifier_resolves_modules_and_methods_too() {
579        let store = store_with(&[
580            nested("perform", Kind::Method, "Bar::Worker"),
581            nested("perform", Kind::Method, "Other::Worker"),
582            nested("Worker", Kind::Module, "Bar"),
583        ]);
584        // a method qualified by its full scope chain
585        let m = search(
586            &store,
587            "Bar::Worker#perform",
588            None,
589            None,
590            &ActiveFiles::default(),
591            10,
592        )
593        .unwrap();
594        assert_eq!(m[0].kind, "method");
595        assert_eq!(m[0].parent.as_deref(), Some("Bar::Worker"));
596        // a module qualified by its enclosing scope
597        let w = search(
598            &store,
599            "Bar::Worker",
600            None,
601            None,
602            &ActiveFiles::default(),
603            10,
604        )
605        .unwrap();
606        assert_eq!(w[0].name, "Worker");
607        assert_eq!(w[0].parent.as_deref(), Some("Bar"));
608    }
609
610    fn hit(name: &str, in_scope: bool) -> Hit {
611        Hit {
612            name: name.into(),
613            kind: "method".into(),
614            language: "ruby".into(),
615            file: "a.rb".into(),
616            line: 1,
617            end_line: Some(1),
618            parent: None,
619            visibility: None,
620            repo_identity: "r".into(),
621            score: 1.0,
622            confidence: 0.0,
623            features: if in_scope {
624                vec![Feature {
625                    name: "parent",
626                    value: 180.0,
627                }]
628            } else {
629                vec![]
630            },
631            signature: None,
632            body: None,
633        }
634    }
635
636    #[test]
637    fn scope_gate_keeps_only_in_scope_results_when_some_match() {
638        let mut hits = vec![hit("baz", true), hit("baz", false), hit("baz", false)];
639        apply_scope_gate("Foo::Bar#baz", &mut hits);
640        assert_eq!(hits.len(), 1, "out-of-scope baz methods are dropped");
641        assert!(hits[0].features.iter().any(|f| f.name == "parent"));
642    }
643
644    #[test]
645    fn scope_gate_falls_back_when_nothing_matches_the_scope() {
646        // no result is in `Foo::Bar`, so a `baz` defined elsewhere still surfaces
647        let mut hits = vec![hit("baz", false), hit("baz", false)];
648        apply_scope_gate("Foo::Bar#baz", &mut hits);
649        assert_eq!(hits.len(), 2, "fall back rather than return empty");
650    }
651
652    #[test]
653    fn scope_gate_is_a_noop_for_an_unqualified_query() {
654        let mut hits = vec![hit("baz", true), hit("baz", false)];
655        apply_scope_gate("baz", &mut hits);
656        assert_eq!(hits.len(), 2, "no qualifier — nothing to gate on");
657    }
658
659    #[test]
660    fn branch_boost_lifts_an_active_file() {
661        let store = store_with(&[sym("User", Kind::Class)]); // lives in app/x.rb
662        let active = ActiveFiles::new(["app/x.rb".to_string()]);
663        let hits = search(&store, "user", None, None, &active, 10).unwrap();
664        assert!(hits[0].features.iter().any(|f| f.name == "branch"));
665    }
666}