loregrep 0.6.0

Repository indexing library for AI coding assistants. Tree-sitter parsing, fast in-memory indexing, and tool APIs for LLM integration.
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
# Query Engine & Search System

## Overview
Advanced search and query engine providing fast, flexible pattern matching across code structures with support for complex filters, fuzzy matching, and semantic queries.

## Core Architecture

### Query Engine Components
```rust
pub struct QueryEngine {
    search_backends: HashMap<SearchBackend, Box<dyn SearchProvider>>,
    query_parser: QueryParser,
    result_ranker: ResultRanker,
    filter_engine: FilterEngine,
    cache: QueryCache,
    database: Arc<DatabaseManager>,
    config: QueryConfig,
}

pub struct QueryConfig {
    pub default_max_results: usize,
    pub fuzzy_threshold: f64,
    pub enable_caching: bool,
    pub cache_ttl_seconds: u64,
    pub parallel_search: bool,
    pub search_timeout_ms: u64,
}

pub enum SearchBackend {
    Exact,        // Direct string/regex matching
    Fuzzy,        // Levenshtein distance-based
    FullText,     // SQLite FTS
    Semantic,     // Future: vector-based similarity
}
```

## Query Parsing & Language

### Query Language
```rust
pub struct QueryParser {
    grammar: QueryGrammar,
    tokenizer: QueryTokenizer,
}

pub enum QueryExpression {
    // Basic patterns
    Exact(String),
    Regex(regex::Regex),
    Wildcard(String),
    Fuzzy { pattern: String, threshold: f64 },
    
    // Logical operators
    And(Box<QueryExpression>, Box<QueryExpression>),
    Or(Box<QueryExpression>, Box<QueryExpression>),
    Not(Box<QueryExpression>),
    
    // Filters
    Filter(FilterType, Box<QueryExpression>),
    
    // Scoped queries
    Scope(ScopeType, Box<QueryExpression>),
}

pub enum FilterType {
    Language(String),
    Visibility(Visibility),
    IsAsync(bool),
    IsMethod(bool),
    ParameterCount(RangeFilter),
    FileSize(RangeFilter),
    LastModified(TimeFilter),
    LineRange(u32, u32),
}

pub enum ScopeType {
    File(String),
    Directory(String),
    Repository,
    Function(String),
    Struct(String),
}

pub struct RangeFilter {
    pub min: Option<u32>,
    pub max: Option<u32>,
}

pub struct TimeFilter {
    pub after: Option<DateTime<Utc>>,
    pub before: Option<DateTime<Utc>>,
}
```

### Query Examples
```
# Basic searches
function_name
"exact function name"
/regex_pattern/
~fuzzy_name

# Filtered searches
function_name lang:rust
async_fn is:async
public_methods is:method visibility:public
recent_changes modified:>2024-01-01

# Complex queries
(auth* OR login*) AND lang:python
functions params:>2 AND params:<=5
structs in:src/models/ visibility:public

# Scoped searches
in:src/auth.rs validate*
struct:User method:*
file:main.rs function:main
```

### Parser Implementation
```rust
impl QueryParser {
    pub fn parse(&self, query: &str) -> Result<ParsedQuery> {
        let tokens = self.tokenizer.tokenize(query)?;
        let expression = self.parse_expression(&tokens)?;
        
        Ok(ParsedQuery {
            expression,
            original_query: query.to_string(),
            parsed_at: Utc::now(),
        })
    }
    
    fn parse_expression(&self, tokens: &[Token]) -> Result<QueryExpression> {
        let mut parser = ExpressionParser::new(tokens);
        parser.parse_or_expression()
    }
}

pub struct ParsedQuery {
    pub expression: QueryExpression,
    pub original_query: String,
    pub parsed_at: DateTime<Utc>,
}

pub struct ExpressionParser<'a> {
    tokens: &'a [Token],
    position: usize,
}

impl<'a> ExpressionParser<'a> {
    fn parse_or_expression(&mut self) -> Result<QueryExpression> {
        let left = self.parse_and_expression()?;
        
        if self.current_token_is(TokenType::Or) {
            self.advance();
            let right = self.parse_or_expression()?;
            Ok(QueryExpression::Or(Box::new(left), Box::new(right)))
        } else {
            Ok(left)
        }
    }
    
    fn parse_and_expression(&mut self) -> Result<QueryExpression> {
        let left = self.parse_not_expression()?;
        
        if self.current_token_is(TokenType::And) {
            self.advance();
            let right = self.parse_and_expression()?;
            Ok(QueryExpression::And(Box::new(left), Box::new(right)))
        } else {
            Ok(left)
        }
    }
    
    fn parse_primary_expression(&mut self) -> Result<QueryExpression> {
        match self.current_token()?.token_type {
            TokenType::String(ref s) => {
                self.advance();
                Ok(QueryExpression::Exact(s.clone()))
            }
            TokenType::Regex(ref pattern) => {
                self.advance();
                let regex = regex::Regex::new(pattern)?;
                Ok(QueryExpression::Regex(regex))
            }
            TokenType::Fuzzy(ref pattern) => {
                self.advance();
                Ok(QueryExpression::Fuzzy {
                    pattern: pattern.clone(),
                    threshold: 0.8,
                })
            }
            TokenType::Filter(ref filter_type, ref value) => {
                self.advance();
                let filter = self.parse_filter(filter_type, value)?;
                Ok(filter)
            }
            _ => Err(QueryError::UnexpectedToken(self.current_token()?.clone()))
        }
    }
}
```

## Search Providers

### Exact Search Provider
```rust
pub struct ExactSearchProvider {
    database: Arc<DatabaseManager>,
}

impl SearchProvider for ExactSearchProvider {
    fn search(&self, query: &QueryExpression, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        match query {
            QueryExpression::Exact(pattern) => {
                self.search_exact_pattern(pattern, options)
            }
            QueryExpression::Regex(regex) => {
                self.search_regex_pattern(regex, options)
            }
            _ => Err(SearchError::UnsupportedQuery),
        }
    }
}

impl ExactSearchProvider {
    fn search_exact_pattern(&self, pattern: &str, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        let mut results = Vec::new();
        
        // Search functions
        if options.search_functions {
            let functions = self.database.search_functions_exact(pattern, options.limit)?;
            for function in functions {
                results.push(SearchResult::Function(FunctionSearchResult {
                    function,
                    relevance_score: 1.0,
                    match_type: MatchType::Exact,
                }));
            }
        }
        
        // Search structs
        if options.search_structs {
            let structs = self.database.search_structs_exact(pattern, options.limit)?;
            for struct_def in structs {
                results.push(SearchResult::Struct(StructSearchResult {
                    struct_def,
                    relevance_score: 1.0,
                    match_type: MatchType::Exact,
                }));
            }
        }
        
        Ok(results)
    }
    
    fn search_regex_pattern(&self, regex: &regex::Regex, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        // Implementation for regex search using database LIKE queries
        // with post-filtering using regex
        Ok(vec![])
    }
}
```

### Fuzzy Search Provider
```rust
pub struct FuzzySearchProvider {
    database: Arc<DatabaseManager>,
    similarity_calculator: SimilarityCalculator,
}

impl SearchProvider for FuzzySearchProvider {
    fn search(&self, query: &QueryExpression, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        match query {
            QueryExpression::Fuzzy { pattern, threshold } => {
                self.search_fuzzy_pattern(pattern, *threshold, options)
            }
            _ => Err(SearchError::UnsupportedQuery),
        }
    }
}

impl FuzzySearchProvider {
    fn search_fuzzy_pattern(
        &self,
        pattern: &str,
        threshold: f64,
        options: &SearchOptions
    ) -> Result<Vec<SearchResult>> {
        let mut results = Vec::new();
        
        // Get all candidate names from database
        let candidates = self.database.get_all_names(options)?;
        
        // Calculate similarity scores
        for candidate in candidates {
            let similarity = self.similarity_calculator.calculate(pattern, &candidate.name);
            
            if similarity >= threshold {
                let result = SearchResult::from_candidate(candidate, similarity, MatchType::Fuzzy);
                results.push(result);
            }
        }
        
        // Sort by similarity score
        results.sort_by(|a, b| {
            b.relevance_score().partial_cmp(&a.relevance_score()).unwrap_or(std::cmp::Ordering::Equal)
        });
        
        Ok(results)
    }
}

pub struct SimilarityCalculator {
    algorithm: SimilarityAlgorithm,
}

pub enum SimilarityAlgorithm {
    Levenshtein,
    Jaro,
    JaroWinkler,
    Jaccard,
}

impl SimilarityCalculator {
    pub fn calculate(&self, pattern: &str, candidate: &str) -> f64 {
        match self.algorithm {
            SimilarityAlgorithm::Levenshtein => {
                let distance = levenshtein_distance(pattern, candidate);
                let max_len = pattern.len().max(candidate.len()) as f64;
                1.0 - (distance as f64 / max_len)
            }
            SimilarityAlgorithm::JaroWinkler => {
                jaro_winkler_similarity(pattern, candidate)
            }
            // Other algorithms...
        }
    }
}
```

### Full-Text Search Provider
```rust
pub struct FullTextSearchProvider {
    database: Arc<DatabaseManager>,
}

impl SearchProvider for FullTextSearchProvider {
    fn search(&self, query: &QueryExpression, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        match query {
            QueryExpression::Exact(pattern) => {
                self.search_fts(pattern, options)
            }
            _ => Err(SearchError::UnsupportedQuery),
        }
    }
}

impl FullTextSearchProvider {
    fn search_fts(&self, pattern: &str, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        // Use SQLite FTS for searching across function names, documentation, etc.
        let sql = r#"
            SELECT 
                f.id, f.name, f.qualified_name, f.doc_comment,
                files.relative_path,
                rank
            FROM functions_fts fts
            JOIN functions f ON fts.rowid = f.id
            JOIN files ON f.file_id = files.id
            WHERE functions_fts MATCH ?
            ORDER BY rank
            LIMIT ?
        "#;
        
        let results = self.database.execute_query(sql, &[pattern, &options.limit.to_string()])?;
        
        // Convert database results to SearchResult objects
        Ok(self.convert_to_search_results(results)?)
    }
}
```

## Result Ranking & Scoring

### Ranking Algorithm
```rust
pub struct ResultRanker {
    ranking_factors: Vec<RankingFactor>,
    weights: RankingWeights,
}

pub struct RankingWeights {
    pub exact_match: f64,
    pub name_similarity: f64,
    pub visibility: f64,
    pub recency: f64,
    pub usage_frequency: f64,
    pub file_importance: f64,
}

pub enum RankingFactor {
    MatchType(MatchType),
    NameSimilarity(f64),
    Visibility(Visibility),
    LastModified(DateTime<Utc>),
    UsageCount(u32),
    FileImportance(f64),
}

impl ResultRanker {
    pub fn rank_results(&self, results: &mut Vec<SearchResult>) {
        for result in results.iter_mut() {
            let score = self.calculate_score(result);
            result.set_relevance_score(score);
        }
        
        // Sort by relevance score (descending)
        results.sort_by(|a, b| {
            b.relevance_score().partial_cmp(&a.relevance_score()).unwrap_or(std::cmp::Ordering::Equal)
        });
    }
    
    fn calculate_score(&self, result: &SearchResult) -> f64 {
        let mut score = 0.0;
        
        // Match type bonus
        score += match result.match_type() {
            MatchType::Exact => self.weights.exact_match,
            MatchType::Prefix => self.weights.exact_match * 0.9,
            MatchType::Substring => self.weights.exact_match * 0.7,
            MatchType::Fuzzy => self.weights.name_similarity * result.base_similarity(),
            MatchType::Regex => self.weights.exact_match * 0.8,
        };
        
        // Visibility bonus (public items are more important)
        score += match result.visibility() {
            Visibility::Public => self.weights.visibility,
            Visibility::Protected => self.weights.visibility * 0.5,
            _ => 0.0,
        };
        
        // Recency bonus
        if let Some(last_modified) = result.last_modified() {
            let days_old = (Utc::now() - last_modified).num_days() as f64;
            let recency_factor = (-days_old / 365.0).exp(); // Exponential decay
            score += self.weights.recency * recency_factor;
        }
        
        // File importance (based on file size, number of functions, etc.)
        score += self.weights.file_importance * result.file_importance();
        
        score
    }
}
```

## Filter Engine

### Advanced Filtering
```rust
pub struct FilterEngine {
    filter_processors: HashMap<FilterType, Box<dyn FilterProcessor>>,
}

pub trait FilterProcessor: Send + Sync {
    fn apply_filter(&self, results: &[SearchResult], filter_value: &str) -> Result<Vec<SearchResult>>;
}

pub struct LanguageFilter;

impl FilterProcessor for LanguageFilter {
    fn apply_filter(&self, results: &[SearchResult], language: &str) -> Result<Vec<SearchResult>> {
        Ok(results
            .iter()
            .filter(|result| result.file_language().as_deref() == Some(language))
            .cloned()
            .collect())
    }
}

pub struct VisibilityFilter;

impl FilterProcessor for VisibilityFilter {
    fn apply_filter(&self, results: &[SearchResult], visibility: &str) -> Result<Vec<SearchResult>> {
        let target_visibility = Visibility::from_str(visibility)?;
        Ok(results
            .iter()
            .filter(|result| result.visibility() == target_visibility)
            .cloned()
            .collect())
    }
}

pub struct ParameterCountFilter;

impl FilterProcessor for ParameterCountFilter {
    fn apply_filter(&self, results: &[SearchResult], range: &str) -> Result<Vec<SearchResult>> {
        let range_filter = RangeFilter::parse(range)?;
        
        Ok(results
            .iter()
            .filter(|result| {
                if let Some(param_count) = result.parameter_count() {
                    range_filter.contains(param_count)
                } else {
                    false
                }
            })
            .cloned()
            .collect())
    }
}

impl RangeFilter {
    pub fn parse(range_str: &str) -> Result<Self> {
        // Parse ranges like ">5", "<=10", "3..7", "5"
        if range_str.starts_with(">=") {
            Ok(RangeFilter {
                min: Some(range_str[2..].parse()?),
                max: None,
            })
        } else if range_str.starts_with('>') {
            Ok(RangeFilter {
                min: Some(range_str[1..].parse::<u32>()? + 1),
                max: None,
            })
        } else if range_str.starts_with("<=") {
            Ok(RangeFilter {
                min: None,
                max: Some(range_str[2..].parse()?),
            })
        } else if range_str.starts_with('<') {
            Ok(RangeFilter {
                min: None,
                max: Some(range_str[1..].parse::<u32>()? - 1),
            })
        } else if range_str.contains("..") {
            let parts: Vec<&str> = range_str.split("..").collect();
            Ok(RangeFilter {
                min: Some(parts[0].parse()?),
                max: Some(parts[1].parse()?),
            })
        } else {
            let value = range_str.parse()?;
            Ok(RangeFilter {
                min: Some(value),
                max: Some(value),
            })
        }
    }
    
    pub fn contains(&self, value: u32) -> bool {
        if let Some(min) = self.min {
            if value < min {
                return false;
            }
        }
        if let Some(max) = self.max {
            if value > max {
                return false;
            }
        }
        true
    }
}
```

## Search Results

### Result Types
```rust
#[derive(Debug, Clone)]
pub enum SearchResult {
    Function(FunctionSearchResult),
    Struct(StructSearchResult),
    Import(ImportSearchResult),
    Export(ExportSearchResult),
    File(FileSearchResult),
}

#[derive(Debug, Clone)]
pub struct FunctionSearchResult {
    pub function: FunctionSignature,
    pub file_path: String,
    pub relevance_score: f64,
    pub match_type: MatchType,
    pub match_context: MatchContext,
}

#[derive(Debug, Clone)]
pub struct StructSearchResult {
    pub struct_def: StructSignature,
    pub file_path: String,
    pub relevance_score: f64,
    pub match_type: MatchType,
    pub match_context: MatchContext,
}

#[derive(Debug, Clone)]
pub struct MatchContext {
    pub matched_field: MatchedField,
    pub snippet: Option<String>,
    pub line_number: u32,
}

#[derive(Debug, Clone)]
pub enum MatchedField {
    Name,
    QualifiedName,
    Documentation,
    Parameter,
    ReturnType,
    FieldName,
    FieldType,
}

#[derive(Debug, Clone)]
pub enum MatchType {
    Exact,
    Prefix,
    Substring,
    Fuzzy,
    Regex,
}

impl SearchResult {
    pub fn relevance_score(&self) -> f64 {
        match self {
            SearchResult::Function(f) => f.relevance_score,
            SearchResult::Struct(s) => s.relevance_score,
            SearchResult::Import(i) => i.relevance_score,
            SearchResult::Export(e) => e.relevance_score,
            SearchResult::File(f) => f.relevance_score,
        }
    }
    
    pub fn file_path(&self) -> &str {
        match self {
            SearchResult::Function(f) => &f.file_path,
            SearchResult::Struct(s) => &s.file_path,
            SearchResult::Import(i) => &i.file_path,
            SearchResult::Export(e) => &e.file_path,
            SearchResult::File(f) => &f.file_path,
        }
    }
    
    pub fn name(&self) -> &str {
        match self {
            SearchResult::Function(f) => &f.function.name,
            SearchResult::Struct(s) => &s.struct_def.name,
            SearchResult::Import(i) => &i.import.imported_name,
            SearchResult::Export(e) => &e.export.exported_name,
            SearchResult::File(f) => &f.file_name,
        }
    }
}
```

## Query Cache

### Caching System
```rust
pub struct QueryCache {
    cache: Arc<Mutex<HashMap<String, CachedResult>>>,
    max_size: usize,
    ttl: Duration,
}

pub struct CachedResult {
    pub results: Vec<SearchResult>,
    pub created_at: Instant,
    pub hit_count: u32,
}

impl QueryCache {
    pub fn get(&self, query_hash: &str) -> Option<Vec<SearchResult>> {
        let mut cache = self.cache.lock().unwrap();
        
        if let Some(cached) = cache.get_mut(query_hash) {
            if cached.created_at.elapsed() < self.ttl {
                cached.hit_count += 1;
                return Some(cached.results.clone());
            } else {
                // Remove expired entry
                cache.remove(query_hash);
            }
        }
        
        None
    }
    
    pub fn insert(&self, query_hash: String, results: Vec<SearchResult>) {
        let mut cache = self.cache.lock().unwrap();
        
        // Evict least recently used entries if cache is full
        if cache.len() >= self.max_size {
            self.evict_lru(&mut cache);
        }
        
        cache.insert(query_hash, CachedResult {
            results,
            created_at: Instant::now(),
            hit_count: 0,
        });
    }
    
    fn evict_lru(&self, cache: &mut HashMap<String, CachedResult>) {
        // Find entry with lowest hit count and oldest creation time
        let mut oldest_key = None;
        let mut oldest_score = f64::MAX;
        
        for (key, cached) in cache.iter() {
            let age_score = cached.created_at.elapsed().as_secs() as f64;
            let hit_score = 1.0 / (cached.hit_count as f64 + 1.0);
            let score = age_score + hit_score * 100.0; // Bias towards evicting low-hit entries
            
            if score < oldest_score {
                oldest_score = score;
                oldest_key = Some(key.clone());
            }
        }
        
        if let Some(key) = oldest_key {
            cache.remove(&key);
        }
    }
}

impl QueryEngine {
    fn calculate_query_hash(query: &ParsedQuery, options: &SearchOptions) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        
        let mut hasher = DefaultHasher::new();
        query.original_query.hash(&mut hasher);
        options.hash(&mut hasher);
        
        format!("{:x}", hasher.finish())
    }
}
```

## Performance Optimization

### Parallel Search
```rust
impl QueryEngine {
    pub async fn search_parallel(&self, query: &ParsedQuery, options: &SearchOptions) -> Result<Vec<SearchResult>> {
        let query_hash = Self::calculate_query_hash(query, options);
        
        // Check cache first
        if let Some(cached_results) = self.cache.get(&query_hash) {
            return Ok(cached_results);
        }
        
        // Execute searches in parallel across different backends
        let mut search_tasks = Vec::new();
        
        for (backend, provider) in &self.search_backends {
            if self.should_use_backend(backend, &query.expression) {
                let provider = provider.clone();
                let query_expr = query.expression.clone();
                let search_options = options.clone();
                
                let task = tokio::spawn(async move {
                    provider.search(&query_expr, &search_options).await
                });
                
                search_tasks.push(task);
            }
        }
        
        // Collect results from all backends
        let mut all_results = Vec::new();
        for task in search_tasks {
            match task.await? {
                Ok(mut results) => all_results.append(&mut results),
                Err(e) => eprintln!("Search backend error: {}", e),
            }
        }
        
        // Remove duplicates and rank results
        let mut deduplicated = self.deduplicate_results(all_results);
        self.result_ranker.rank_results(&mut deduplicated);
        
        // Apply limit
        deduplicated.truncate(options.limit);
        
        // Cache results
        self.cache.insert(query_hash, deduplicated.clone());
        
        Ok(deduplicated)
    }
    
    fn deduplicate_results(&self, results: Vec<SearchResult>) -> Vec<SearchResult> {
        let mut seen = HashSet::new();
        let mut deduplicated = Vec::new();
        
        for result in results {
            let key = self.result_key(&result);
            if !seen.contains(&key) {
                seen.insert(key);
                deduplicated.push(result);
            }
        }
        
        deduplicated
    }
    
    fn result_key(&self, result: &SearchResult) -> String {
        format!("{}:{}:{}", 
            result.result_type(),
            result.file_path(),
            result.name()
        )
    }
}
```

## Error Handling

### Query Errors
```rust
#[derive(Debug, thiserror::Error)]
pub enum QueryError {
    #[error("Invalid query syntax: {0}")]
    InvalidSyntax(String),
    
    #[error("Unsupported query expression")]
    UnsupportedExpression,
    
    #[error("Regex compilation error: {0}")]
    RegexError(#[from] regex::Error),
    
    #[error("Filter parsing error: {0}")]
    FilterError(String),
    
    #[error("Search timeout")]
    Timeout,
    
    #[error("Database error: {0}")]
    DatabaseError(String),
    
    #[error("Cache error: {0}")]
    CacheError(String),
}

#[derive(Debug, thiserror::Error)]
pub enum SearchError {
    #[error("Unsupported query type for this backend")]
    UnsupportedQuery,
    
    #[error("Backend unavailable: {0}")]
    BackendUnavailable(String),
    
    #[error("Search index corrupted")]
    IndexCorrupted,
    
    #[error("Resource limit exceeded")]
    ResourceLimitExceeded,
}
```

## Configuration

### Query Engine Configuration
```toml
[query_engine]
default_max_results = 50
fuzzy_threshold = 0.7
enable_caching = true
cache_ttl_seconds = 300
parallel_search = true
search_timeout_ms = 5000

[search_backends]
exact = { enabled = true, priority = 1 }
fuzzy = { enabled = true, priority = 2, threshold = 0.7 }
full_text = { enabled = true, priority = 3 }
semantic = { enabled = false, priority = 4 }

[ranking]
exact_match_weight = 10.0
name_similarity_weight = 5.0
visibility_weight = 2.0
recency_weight = 1.0
usage_frequency_weight = 3.0
file_importance_weight = 1.5

[cache]
max_size = 1000
eviction_policy = "lru"
cleanup_interval_seconds = 60
```

## Testing

### Unit Tests
- Query parsing accuracy
- Search result ranking
- Filter application
- Cache behavior

### Performance Tests
- Large dataset search performance
- Parallel search efficiency
- Memory usage under load
- Cache hit rate optimization

### Integration Tests
- End-to-end search workflows
- Multiple backend coordination
- Complex query evaluation
- Error recovery scenarios