bobbin-ai 0.25.2

Local-first context injection engine for AI coding agents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
//! Advanced query parser for bobbin search.
//!
//! Parses user queries into structured components: free-text terms, inline field
//! filters (repo:X, lang:Y), quoted phrases, and negation prefixes.
//!
//! Design: never error on bad syntax — treat unparseable input as literal search
//! terms. Modeled after GitHub/Sourcegraph query conventions.

use std::fmt;

/// A parsed search query with structured components extracted.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedQuery {
    /// Free-text search terms (everything that isn't a filter or phrase)
    pub terms: Vec<String>,
    /// Exact phrase matches (from quoted strings)
    pub phrases: Vec<String>,
    /// Inline field filters
    pub filters: Vec<Filter>,
    /// Terms to exclude from results (-word or NOT word)
    pub negated_terms: Vec<String>,
    /// Terms every result MUST contain (`+word` / `+"exact phrase"`), the
    /// documented mirror of `-word`. A required term is also a normal search
    /// term — `+` promises "this one has to be there", not "search only for
    /// this one" — so it appears in `terms`/`phrases` as well and drives
    /// retrieval; this list is what the post-filter enforces.
    pub required_terms: Vec<String>,
    /// The reconstructed free-text query (terms + phrases joined)
    pub text_query: String,
    /// Whether the query contains OR operators (signals multi-branch search)
    pub has_or: bool,
    /// OR-separated branches of the text query (only populated when has_or is true)
    pub or_branches: Vec<String>,
    /// Regex patterns extracted from /pattern/ syntax
    pub regex_patterns: Vec<String>,
}

/// An inline field filter extracted from the query.
#[derive(Debug, Clone, PartialEq)]
pub struct Filter {
    /// The filter field
    pub field: FilterField,
    /// The filter value(s) — comma-separated values are split
    pub values: Vec<String>,
    /// Whether this filter is negated (prefixed with -)
    pub negated: bool,
}

/// Known filter fields that can appear inline in queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FilterField {
    /// Filter by repository name
    Repo,
    /// Filter by programming language
    Lang,
    /// Filter by chunk type (function, struct, section, etc.)
    Type,
    /// Filter by file path (substring match)
    File,
    /// Filter by file path (alias for File)
    Path,
    /// Filter by named repo group
    Group,
    /// Filter by tag
    Tag,
}

impl FilterField {
    /// Parse a field name string into a FilterField.
    fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "repo" | "repository" => Some(Self::Repo),
            "lang" | "language" => Some(Self::Lang),
            "type" | "kind" => Some(Self::Type),
            "file" | "filename" => Some(Self::File),
            "path" | "filepath" => Some(Self::Path),
            "group" => Some(Self::Group),
            "tag" | "label" => Some(Self::Tag),
            _ => None,
        }
    }

    /// The canonical name for this field (used in SQL generation).
    pub fn canonical_name(&self) -> &'static str {
        match self {
            Self::Repo => "repo",
            Self::Lang => "lang",
            Self::Type => "type",
            Self::File => "file",
            Self::Path => "path",
            Self::Group => "group",
            Self::Tag => "tag",
        }
    }

    /// The LanceDB column name this field maps to.
    pub fn column_name(&self) -> &'static str {
        match self {
            Self::Repo => "repo",
            Self::Lang => "language",
            Self::Type => "chunk_type",
            Self::File | Self::Path => "file_path",
            Self::Group => "repo", // groups resolve to repo IN (...) — handled separately
            Self::Tag => "tags",
        }
    }
}

impl fmt::Display for FilterField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.canonical_name())
    }
}

/// Parse a query string into structured components.
///
/// Extracts inline filters (repo:X, lang:Y), quoted phrases, and free-text terms.
/// Never errors — unparseable input is treated as literal search text.
///
/// # Examples
///
/// ```
/// use bobbin::search::query::parse;
///
/// let q = parse("repo:aegis lang:rust PostToolUse");
/// assert_eq!(q.terms, vec!["PostToolUse"]);
/// assert_eq!(q.filters.len(), 2);
/// assert_eq!(q.filters[0].field, bobbin::search::query::FilterField::Repo);
/// ```
pub fn parse(input: &str) -> ParsedQuery {
    let mut terms: Vec<String> = Vec::new();
    let mut phrases: Vec<String> = Vec::new();
    let mut filters: Vec<Filter> = Vec::new();
    let mut negated_terms: Vec<String> = Vec::new();
    let mut required_terms: Vec<String> = Vec::new();
    let mut regex_patterns: Vec<String> = Vec::new();
    let mut has_or = false;
    let mut next_negated = false; // set by NOT keyword

    let input = input.trim();
    if input.is_empty() {
        return ParsedQuery {
            terms,
            phrases,
            filters,
            negated_terms,
            required_terms,
            text_query: String::new(),
            has_or: false,
            or_branches: vec![],
            regex_patterns: vec![],
        };
    }

    let chars: Vec<char> = input.chars().collect();
    let len = chars.len();
    let mut i = 0;

    while i < len {
        // Skip whitespace
        if chars[i].is_whitespace() {
            i += 1;
            continue;
        }

        // Regex pattern: /pattern/
        if chars[i] == '/' {
            if let Some((pattern, end)) = parse_regex(&chars, i) {
                if !pattern.is_empty() {
                    regex_patterns.push(pattern);
                }
                i = end;
                continue;
            }
            // Not a valid regex — fall through to treat as literal
        }

        // Quoted phrase: "exact match"
        if chars[i] == '"' {
            if let Some((phrase, end)) = parse_quoted(&chars, i) {
                if !phrase.is_empty() {
                    if next_negated {
                        negated_terms.push(phrase);
                        next_negated = false;
                    } else {
                        phrases.push(phrase);
                    }
                }
                i = end;
                continue;
            }
            // Unmatched quote — fall through to treat as literal
        }

        // Check for negation prefix: -word (not a filter)
        if chars[i] == '-' && i + 1 < len && !chars[i + 1].is_whitespace() {
            // Try filter first: -repo:aegis
            if let Some((filter, end)) = parse_filter(&chars, i + 1, true) {
                filters.push(filter);
                i = end;
                continue;
            }
            // Not a filter — it's a negated term: -assembler
            let (word, end) = parse_word(&chars, i + 1);
            if !word.is_empty() {
                negated_terms.push(word);
            }
            i = end;
            continue;
        }

        // Required-term shorthand: +word / +"exact phrase" (the documented
        // mirror of -word). `+repo:aegis` is not a distinct meaning — a plain
        // positive filter already requires its value — so the `+` is dropped
        // and the filter taken as-is, rather than inventing a third semantics.
        if chars[i] == '+' && i + 1 < len && !chars[i + 1].is_whitespace() {
            if let Some((filter, end)) = parse_filter(&chars, i + 1, false) {
                filters.push(filter);
                i = end;
                continue;
            }
            if chars[i + 1] == '"' {
                if let Some((phrase, end)) = parse_quoted(&chars, i + 1) {
                    if !phrase.is_empty() {
                        required_terms.push(phrase.clone());
                        phrases.push(phrase);
                    }
                    i = end;
                    continue;
                }
                // Unmatched quote — fall through to the literal path below.
            }
            let (word, end) = parse_word(&chars, i + 1);
            if !word.is_empty() {
                // A bare "+" operator-ish token (`a + b`) is caught by the
                // whitespace guard above, so anything here is a real term.
                required_terms.push(word.clone());
                terms.push(word);
                i = end;
                continue;
            }
        }

        // Try to parse as field:value filter (non-negated)
        if let Some((filter, end)) = parse_filter(&chars, i, false) {
            filters.push(filter);
            i = end;
            continue;
        }

        // Regular word/token
        let (word, end) = parse_word(&chars, i);
        if !word.is_empty() {
            let upper = word.to_uppercase();
            if upper == "AND" {
                // AND is implicit — skip
            } else if upper == "OR" {
                has_or = true;
            } else if upper == "NOT" {
                // Next term is negated
                next_negated = true;
            } else if next_negated {
                negated_terms.push(word);
                next_negated = false;
            } else {
                terms.push(word);
            }
        }
        i = end;
    }

    // Build the text query from terms and phrases
    let mut text_parts: Vec<String> = Vec::new();
    for t in &terms {
        text_parts.push(t.clone());
    }
    for p in &phrases {
        text_parts.push(format!("\"{}\"", p));
    }
    let text_query = text_parts.join(" ");

    // Build OR branches if query contains OR operators
    // Re-parse the original input to split on OR boundaries
    let or_branches = if has_or {
        build_or_branches(input, &filters)
    } else {
        vec![]
    };

    ParsedQuery {
        terms,
        phrases,
        filters,
        negated_terms,
        required_terms,
        text_query,
        has_or,
        or_branches,
        regex_patterns,
    }
}

/// Apply the content-level parts of a parsed query that the store cannot
/// express as SQL: required terms (`+word`), negated terms (`-word` / `NOT`),
/// and regex patterns (`/pattern/`).
///
/// Shared by the HTTP handler and the `bobbin search` CLI so the two agree by
/// construction. They did not before: the CLI never called the parser at all,
/// so the same query answered differently over HTTP and on the command line.
///
/// A regex that does not compile is skipped rather than failing the query —
/// the parser's standing rule is to never error on bad syntax.
pub fn retain_matching<T>(
    results: &mut Vec<T>,
    parsed: &ParsedQuery,
    content_of: impl Fn(&T) -> &str,
) {
    if !parsed.required_terms.is_empty() {
        let required: Vec<String> = parsed
            .required_terms
            .iter()
            .map(|t| t.to_lowercase())
            .collect();
        results.retain(|r| {
            let haystack = content_of(r).to_lowercase();
            required.iter().all(|t| haystack.contains(t))
        });
    }

    if !parsed.negated_terms.is_empty() {
        let negated: Vec<String> = parsed
            .negated_terms
            .iter()
            .map(|t| t.to_lowercase())
            .collect();
        results.retain(|r| {
            let haystack = content_of(r).to_lowercase();
            !negated.iter().any(|t| haystack.contains(t))
        });
    }

    if !parsed.regex_patterns.is_empty() {
        let compiled: Vec<regex::Regex> = parsed
            .regex_patterns
            .iter()
            .filter_map(|p| regex::Regex::new(p).ok())
            .collect();
        if !compiled.is_empty() {
            results.retain(|r| {
                let haystack = content_of(r);
                compiled.iter().all(|re| re.is_match(haystack))
            });
        }
    }
}

/// Split a query into OR-separated branches, stripping filters from each.
/// e.g. "redis OR memcached repo:aegis" → ["redis", "memcached"]
fn build_or_branches(input: &str, _filters: &[Filter]) -> Vec<String> {
    // Split on " OR " (case-insensitive), then strip filters/AND/NOT from each branch
    let mut branches = Vec::new();
    let parts: Vec<&str> = split_on_or(input);

    for part in parts {
        let sub = parse(part);
        if !sub.text_query.is_empty() {
            branches.push(sub.text_query);
        }
    }
    branches
}

/// Split input on " OR " boundaries (case-insensitive).
fn split_on_or(input: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut last = 0;
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i + 4 <= len {
        // Check for " OR " (with surrounding spaces)
        if bytes[i] == b' '
            && (bytes[i + 1] == b'O' || bytes[i + 1] == b'o')
            && (bytes[i + 2] == b'R' || bytes[i + 2] == b'r')
            && bytes[i + 3] == b' '
        {
            let part = &input[last..i];
            if !part.trim().is_empty() {
                parts.push(part.trim());
            }
            last = i + 4;
            i = last;
        } else {
            i += 1;
        }
    }
    // Last segment
    let remaining = &input[last..];
    if !remaining.trim().is_empty() {
        parts.push(remaining.trim());
    }
    parts
}

/// Convert parsed filters into SQL WHERE clause fragments for LanceDB.
///
/// Returns a list of SQL conditions that should be ANDed together.
/// Group filters are excluded (handled separately via group resolution).
///
/// # Examples
///
/// - `repo:aegis` → `repo = 'aegis'`
/// - `lang:rust,go` → `language IN ('rust', 'go')`
/// - `-repo:test` → `repo != 'test'`
/// - `file:*.rs` → `file_path LIKE '%.rs'`
/// - `path:src/cli` → `file_path LIKE '%src/cli%'`
pub fn filters_to_sql(filters: &[Filter]) -> Vec<String> {
    let mut clauses = Vec::new();

    for filter in filters {
        // Group filters are handled separately via group resolution
        if filter.field == FilterField::Group {
            continue;
        }

        let col = filter.field.column_name();
        let sql = if filter.values.len() == 1 {
            let val = &filter.values[0];
            let escaped = val.replace('\'', "''");

            // Check for glob wildcards in value
            if val.contains('*') || val.contains('?') {
                // Convert glob to SQL LIKE pattern
                let like_pattern = escaped.replace('*', "%").replace('?', "_");
                if filter.negated {
                    format!("{} NOT LIKE '{}'", col, like_pattern)
                } else {
                    format!("{} LIKE '{}'", col, like_pattern)
                }
            } else if filter.field == FilterField::File || filter.field == FilterField::Path {
                // Path/file filters do substring matching by default
                if filter.negated {
                    format!("{} NOT LIKE '%{}%'", col, escaped)
                } else {
                    format!("{} LIKE '%{}%'", col, escaped)
                }
            } else if filter.negated {
                format!("{} != '{}'", col, escaped)
            } else {
                format!("{} = '{}'", col, escaped)
            }
        } else {
            // Multiple values: IN/NOT IN
            let vals: Vec<String> = filter
                .values
                .iter()
                .map(|v| format!("'{}'", v.replace('\'', "''")))
                .collect();
            if filter.negated {
                format!("{} NOT IN ({})", col, vals.join(", "))
            } else {
                format!("{} IN ({})", col, vals.join(", "))
            }
        };

        clauses.push(sql);
    }

    clauses
}

/// Extract group filter names from parsed filters.
/// Returns group names for resolution against configured groups.
pub fn extract_group_filters(filters: &[Filter]) -> Vec<String> {
    filters
        .iter()
        .filter(|f| f.field == FilterField::Group && !f.negated)
        .flat_map(|f| f.values.clone())
        .collect()
}

/// Parse a quoted string starting at position `start` (which should be `"`).
/// Returns the content between quotes and the position after the closing quote.
fn parse_quoted(chars: &[char], start: usize) -> Option<(String, usize)> {
    if start >= chars.len() || chars[start] != '"' {
        return None;
    }
    let mut i = start + 1;
    let mut content = String::new();
    while i < chars.len() {
        if chars[i] == '"' {
            return Some((content, i + 1));
        }
        if chars[i] == '\\' && i + 1 < chars.len() {
            // Escaped character
            content.push(chars[i + 1]);
            i += 2;
        } else {
            content.push(chars[i]);
            i += 1;
        }
    }
    // No closing quote found — return content anyway (graceful degradation)
    Some((content, i))
}

/// Parse a regex pattern enclosed in `/pattern/` starting at position `start`.
/// Returns the pattern content and the position after the closing `/`.
/// Requires the closing `/` to be followed by whitespace or end of input
/// (to avoid matching path-like strings such as `src/cli/hook.rs`).
fn parse_regex(chars: &[char], start: usize) -> Option<(String, usize)> {
    if start >= chars.len() || chars[start] != '/' {
        return None;
    }
    let mut i = start + 1;
    let mut content = String::new();
    while i < chars.len() {
        if chars[i] == '/' {
            // Closing slash must be at end of input or followed by whitespace
            let next = i + 1;
            if next >= chars.len() || chars[next].is_whitespace() {
                if content.is_empty() {
                    return None; // empty pattern `//` is not valid
                }
                return Some((content, next));
            }
            // Slash followed by non-whitespace — not a regex delimiter
            return None;
        }
        if chars[i] == '\\' && i + 1 < chars.len() && chars[i + 1] == '/' {
            // Only \/ is an escape inside regex (literal slash)
            content.push('/');
            i += 2;
        } else {
            content.push(chars[i]);
            i += 1;
        }
    }
    // No closing slash found — not a regex
    None
}

/// Try to parse a field:value filter starting at position `start`.
/// Returns the Filter and position after the value, or None if not a filter.
fn parse_filter(chars: &[char], start: usize, negated: bool) -> Option<(Filter, usize)> {
    // Look for field_name: pattern
    let mut i = start;
    let mut field_name = String::new();

    // Read the field name (letters, digits, underscores)
    while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
        field_name.push(chars[i]);
        i += 1;
    }

    // Must be followed by ':'
    if i >= chars.len() || chars[i] != ':' || field_name.is_empty() {
        return None;
    }

    // Must be a known filter field
    let field = FilterField::from_str(&field_name)?;

    // Skip the ':'
    i += 1;

    // Parse the value — could be quoted or bare
    if i >= chars.len() || chars[i].is_whitespace() {
        // field: with no value — not a filter
        return None;
    }

    let (value, end) = if chars[i] == '"' {
        // Quoted value: field:"value with spaces"
        match parse_quoted(chars, i) {
            Some((v, end)) => (v, end),
            None => return None,
        }
    } else {
        // Bare value: field:value (terminated by whitespace)
        parse_word(chars, i)
    };

    if value.is_empty() {
        return None;
    }

    // Split comma-separated values: lang:rust,go → ["rust", "go"]
    let values: Vec<String> = value
        .split(',')
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
        .collect();

    if values.is_empty() {
        return None;
    }

    let actual_start = if negated { start - 1 } else { start };
    let _ = actual_start; // We only need `end` for the caller

    Some((
        Filter {
            field,
            values,
            negated,
        },
        end,
    ))
}

/// Parse a bare word (non-whitespace token) starting at position `start`.
/// Returns the word and the position after it.
fn parse_word(chars: &[char], start: usize) -> (String, usize) {
    let mut i = start;
    let mut word = String::new();
    while i < chars.len() && !chars[i].is_whitespace() {
        word.push(chars[i]);
        i += 1;
    }
    (word, i)
}

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

    #[test]
    fn test_plain_text() {
        let q = parse("context assembler");
        assert_eq!(q.terms, vec!["context", "assembler"]);
        assert!(q.filters.is_empty());
        assert!(q.phrases.is_empty());
        assert_eq!(q.text_query, "context assembler");
    }

    #[test]
    fn test_quoted_phrase() {
        let q = parse("\"error handling\" in rust");
        assert_eq!(q.terms, vec!["in", "rust"]);
        assert_eq!(q.phrases, vec!["error handling"]);
        assert_eq!(q.text_query, "in rust \"error handling\"");
    }

    #[test]
    fn test_single_filter() {
        let q = parse("repo:aegis PostToolUse");
        assert_eq!(q.terms, vec!["PostToolUse"]);
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].field, FilterField::Repo);
        assert_eq!(q.filters[0].values, vec!["aegis"]);
        assert!(!q.filters[0].negated);
        assert_eq!(q.text_query, "PostToolUse");
    }

    #[test]
    fn test_multiple_filters() {
        let q = parse("repo:aegis lang:rust type:function search");
        assert_eq!(q.terms, vec!["search"]);
        assert_eq!(q.filters.len(), 3);
        assert_eq!(q.filters[0].field, FilterField::Repo);
        assert_eq!(q.filters[1].field, FilterField::Lang);
        assert_eq!(q.filters[2].field, FilterField::Type);
    }

    #[test]
    fn test_negated_filter() {
        let q = parse("-repo:aegis search query");
        assert_eq!(q.terms, vec!["search", "query"]);
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].field, FilterField::Repo);
        assert_eq!(q.filters[0].values, vec!["aegis"]);
        assert!(q.filters[0].negated);
    }

    #[test]
    fn test_multi_value_filter() {
        let q = parse("lang:rust,go search");
        assert_eq!(q.terms, vec!["search"]);
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].values, vec!["rust", "go"]);
    }

    #[test]
    fn test_quoted_filter_value() {
        let q = parse("file:\"src/cli/hook.rs\" search");
        assert_eq!(q.terms, vec!["search"]);
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].field, FilterField::File);
        assert_eq!(q.filters[0].values, vec!["src/cli/hook.rs"]);
    }

    #[test]
    fn test_unknown_field_is_literal() {
        let q = parse("http:server search");
        assert_eq!(q.terms, vec!["http:server", "search"]);
        assert!(q.filters.is_empty());
    }

    #[test]
    fn test_and_is_implicit() {
        let q = parse("context AND assembler");
        assert_eq!(q.terms, vec!["context", "assembler"]);
        assert!(q.filters.is_empty());
        assert!(!q.has_or);
        assert_eq!(q.text_query, "context assembler");
    }

    #[test]
    fn test_or_sets_flag_and_branches() {
        let q = parse("redis OR memcached");
        assert_eq!(q.terms, vec!["redis", "memcached"]);
        assert!(q.has_or);
        assert_eq!(q.or_branches, vec!["redis", "memcached"]);
    }

    #[test]
    fn test_or_with_multiple_branches() {
        let q = parse("redis OR memcached OR etcd");
        assert!(q.has_or);
        assert_eq!(q.or_branches, vec!["redis", "memcached", "etcd"]);
    }

    #[test]
    fn test_or_preserves_filters() {
        let q = parse("redis OR memcached repo:aegis");
        assert!(q.has_or);
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].field, FilterField::Repo);
        // Branches should strip filters
        assert_eq!(q.or_branches, vec!["redis", "memcached"]);
    }

    #[test]
    fn test_negated_term_dash_prefix() {
        let q = parse("context -assembler");
        assert_eq!(q.terms, vec!["context"]);
        assert_eq!(q.negated_terms, vec!["assembler"]);
        assert_eq!(q.text_query, "context");
    }

    #[test]
    fn test_negated_term_not_keyword() {
        let q = parse("context NOT assembler");
        assert_eq!(q.terms, vec!["context"]);
        assert_eq!(q.negated_terms, vec!["assembler"]);
    }

    #[test]
    fn test_and_not_combination() {
        let q = parse("context AND NOT assembler");
        assert_eq!(q.terms, vec!["context"]);
        assert_eq!(q.negated_terms, vec!["assembler"]);
    }

    #[test]
    fn test_negated_phrase() {
        let q = parse("search NOT \"error handling\"");
        assert_eq!(q.terms, vec!["search"]);
        assert_eq!(q.negated_terms, vec!["error handling"]);
        assert!(q.phrases.is_empty()); // negated phrase is NOT a search phrase
    }

    #[test]
    fn test_plus_prefix_is_a_required_term() {
        // `+context -assembler` is the documented shorthand pair: must have
        // context, must not have assembler. The `+` is an operator, not part
        // of the term — it used to be kept literally, so `+context` searched
        // the FTS index for the string "+context" and matched nothing.
        let q = parse("+context -assembler");
        assert_eq!(q.terms, vec!["context"]);
        assert_eq!(q.required_terms, vec!["context"]);
        assert_eq!(q.negated_terms, vec!["assembler"]);
        // A required term still drives retrieval, so it must reach the query.
        assert_eq!(q.text_query, "context");
    }

    #[test]
    fn test_plus_prefixed_phrase_is_required() {
        let q = parse("+\"error handling\" retries");
        assert_eq!(q.phrases, vec!["error handling"]);
        assert_eq!(q.required_terms, vec!["error handling"]);
        assert_eq!(q.terms, vec!["retries"]);
    }

    #[test]
    fn test_plus_prefixed_filter_is_just_the_filter() {
        // A positive filter already requires its value; `+` adds nothing and
        // must not leak into the field name.
        let q = parse("+repo:aegis context");
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].field, FilterField::Repo);
        assert_eq!(q.filters[0].values, vec!["aegis"]);
        assert!(!q.filters[0].negated);
        assert!(q.required_terms.is_empty());
    }

    #[test]
    fn test_plain_query_has_no_required_terms() {
        let q = parse("context assembler");
        assert!(q.required_terms.is_empty());
    }

    #[test]
    fn test_retain_matching_enforces_required_negated_and_regex() {
        let docs = || {
            vec![
                "fn context_assembler() {}".to_string(),
                "fn context_only() {}".to_string(),
                "fn unrelated() {}".to_string(),
            ]
        };

        // Required keeps only what contains the term.
        let mut v = docs();
        retain_matching(&mut v, &parse("+context"), |s| s.as_str());
        assert_eq!(v.len(), 2);

        // Required and negated compose.
        let mut v = docs();
        retain_matching(&mut v, &parse("+context -assembler"), |s| s.as_str());
        assert_eq!(v, vec!["fn context_only() {}".to_string()]);

        // Regex narrows further.
        let mut v = docs();
        retain_matching(&mut v, &parse("+context /_only/"), |s| s.as_str());
        assert_eq!(v, vec!["fn context_only() {}".to_string()]);

        // A query with none of the three is a no-op, not an empty result.
        let mut v = docs();
        retain_matching(&mut v, &parse("context"), |s| s.as_str());
        assert_eq!(v.len(), 3);
    }

    #[test]
    fn test_empty_query() {
        let q = parse("");
        assert!(q.terms.is_empty());
        assert!(q.filters.is_empty());
        assert!(q.phrases.is_empty());
        assert_eq!(q.text_query, "");
    }

    #[test]
    fn test_whitespace_only() {
        let q = parse("   ");
        assert!(q.terms.is_empty());
    }

    #[test]
    fn test_filter_aliases() {
        let q1 = parse("language:rust");
        assert_eq!(q1.filters[0].field, FilterField::Lang);

        let q2 = parse("repository:aegis");
        assert_eq!(q2.filters[0].field, FilterField::Repo);

        let q3 = parse("filepath:src/main.rs");
        assert_eq!(q3.filters[0].field, FilterField::Path);

        let q4 = parse("label:reviewed");
        assert_eq!(q4.filters[0].field, FilterField::Tag);
    }

    #[test]
    fn test_filter_no_value_is_literal() {
        // "repo:" with nothing after it is treated as literal text
        let q = parse("repo: search");
        // "repo:" becomes a word because the value parse finds whitespace
        assert!(q.filters.is_empty());
    }

    #[test]
    fn test_complex_query() {
        let q = parse("repo:aegis lang:rust -type:section \"error handling\" PostToolUse");
        assert_eq!(q.terms, vec!["PostToolUse"]);
        assert_eq!(q.phrases, vec!["error handling"]);
        assert_eq!(q.filters.len(), 3);
        assert_eq!(q.filters[0].field, FilterField::Repo);
        assert!(!q.filters[0].negated);
        assert_eq!(q.filters[1].field, FilterField::Lang);
        assert_eq!(q.filters[2].field, FilterField::Type);
        assert!(q.filters[2].negated);
    }

    #[test]
    fn test_unmatched_quote_graceful() {
        // Unmatched quote should not crash — treat rest as phrase
        let q = parse("search \"unfinished");
        assert_eq!(q.terms, vec!["search"]);
        assert_eq!(q.phrases, vec!["unfinished"]);
    }

    #[test]
    fn test_path_filter_with_glob() {
        let q = parse("file:*.rs search");
        assert_eq!(q.filters.len(), 1);
        assert_eq!(q.filters[0].field, FilterField::File);
        assert_eq!(q.filters[0].values, vec!["*.rs"]);
    }

    #[test]
    fn test_column_names() {
        assert_eq!(FilterField::Repo.column_name(), "repo");
        assert_eq!(FilterField::Lang.column_name(), "language");
        assert_eq!(FilterField::Type.column_name(), "chunk_type");
        assert_eq!(FilterField::File.column_name(), "file_path");
        assert_eq!(FilterField::Path.column_name(), "file_path");
    }

    #[test]
    fn test_case_insensitive_field_names() {
        let q1 = parse("Repo:aegis");
        assert_eq!(q1.filters.len(), 1);
        assert_eq!(q1.filters[0].field, FilterField::Repo);

        let q2 = parse("LANG:rust");
        assert_eq!(q2.filters.len(), 1);
        assert_eq!(q2.filters[0].field, FilterField::Lang);
    }

    // -- filters_to_sql tests --

    #[test]
    fn test_sql_simple_eq() {
        let q = parse("repo:aegis");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["repo = 'aegis'"]);
    }

    #[test]
    fn test_sql_negated() {
        let q = parse("-repo:aegis");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["repo != 'aegis'"]);
    }

    #[test]
    fn test_sql_multi_value_in() {
        let q = parse("lang:rust,go");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["language IN ('rust', 'go')"]);
    }

    #[test]
    fn test_sql_negated_multi_value() {
        let q = parse("-lang:rust,go");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["language NOT IN ('rust', 'go')"]);
    }

    #[test]
    fn test_sql_glob_wildcard() {
        let q = parse("file:*.rs");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["file_path LIKE '%.rs'"]);
    }

    #[test]
    fn test_sql_path_substring() {
        let q = parse("path:src/cli");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["file_path LIKE '%src/cli%'"]);
    }

    #[test]
    fn test_sql_group_excluded() {
        let q = parse("group:infra search");
        let sql = filters_to_sql(&q.filters);
        // Group filters are handled separately — not in SQL
        assert!(sql.is_empty());
    }

    #[test]
    fn test_sql_multiple_filters() {
        let q = parse("repo:aegis lang:rust -type:section");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql.len(), 3);
        assert_eq!(sql[0], "repo = 'aegis'");
        assert_eq!(sql[1], "language = 'rust'");
        assert_eq!(sql[2], "chunk_type != 'section'");
    }

    #[test]
    fn test_sql_escapes_quotes() {
        let q = parse("repo:o'brien");
        let sql = filters_to_sql(&q.filters);
        assert_eq!(sql, vec!["repo = 'o''brien'"]);
    }

    #[test]
    fn test_extract_group_filters() {
        let q = parse("group:infra group:apps search");
        let groups = extract_group_filters(&q.filters);
        assert_eq!(groups, vec!["infra", "apps"]);
    }

    // -- regex pattern tests --

    #[test]
    fn test_regex_pattern_basic() {
        let q = parse("/fn\\s+\\w+/");
        assert!(q.terms.is_empty());
        assert_eq!(q.regex_patterns, vec!["fn\\s+\\w+"]);
    }

    #[test]
    fn test_regex_pattern_with_terms() {
        let q = parse("search /TODO/ repo:aegis");
        assert_eq!(q.terms, vec!["search"]);
        assert_eq!(q.regex_patterns, vec!["TODO"]);
        assert_eq!(q.filters.len(), 1);
    }

    #[test]
    fn test_regex_multiple_patterns() {
        let q = parse("/error/ /warning/");
        assert_eq!(q.regex_patterns, vec!["error", "warning"]);
    }

    #[test]
    fn test_regex_not_matched_for_paths() {
        // src/cli/hook.rs should NOT be parsed as regex
        let q = parse("file:src/cli/hook.rs search");
        assert!(q.regex_patterns.is_empty());
        assert_eq!(q.filters.len(), 1);
    }

    #[test]
    fn test_regex_unclosed_is_literal() {
        // /unclosed should be treated as a literal term
        let q = parse("/unclosed search");
        assert!(q.regex_patterns.is_empty());
        assert_eq!(q.terms, vec!["/unclosed", "search"]);
    }

    #[test]
    fn test_regex_empty_pattern_rejected() {
        // // should not be parsed as regex
        let q = parse("// search");
        assert!(q.regex_patterns.is_empty());
    }

    #[test]
    fn test_extract_group_filters_negated_excluded() {
        let q = parse("-group:infra search");
        let groups = extract_group_filters(&q.filters);
        assert!(groups.is_empty());
    }
}