gobby-code 0.7.0

Fast Rust CLI for Gobby's code index — AST-aware search, symbol navigation, and dependency graph
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
//! FTS5 query sanitization and execution against SQLite.
//! Ports logic from src/gobby/code_index/storage.py and searcher.py.

use std::collections::HashSet;

use rusqlite::Connection;

use crate::models::{ContentSearchHit, SearchResult, Symbol};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedGraphSymbol {
    pub id: String,
    pub display_name: String,
}

#[derive(Debug, Clone, Copy, Default)]
struct SymbolFilters<'a> {
    kind: Option<&'a str>,
    language: Option<&'a str>,
    path: Option<&'a str>,
}

/// Escape LIKE wildcards (`%`, `_`) and the backslash escape char itself.
/// Must be paired with `ESCAPE '\'` in the SQL for SQLite to honor it.
fn escape_like(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '\\' | '%' | '_') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

/// Extract a SQL LIKE prefix from a glob pattern for index-assisted pre-filtering.
/// Returns the literal prefix before the first wildcard character, or None if empty.
fn glob_to_like_prefix(pattern: &str) -> Option<String> {
    let prefix: String = pattern
        .chars()
        .take_while(|c| !matches!(c, '*' | '?' | '['))
        .collect();
    if prefix.is_empty() {
        None
    } else {
        Some(format!("{}%", escape_like(&prefix)))
    }
}

fn push_symbol_filters(
    conditions: &mut Vec<String>,
    params: &mut Vec<Box<dyn rusqlite::types::ToSql>>,
    alias: &str,
    filters: SymbolFilters<'_>,
) {
    if let Some(k) = filters.kind {
        conditions.push(format!("{alias}.kind = ?"));
        params.push(Box::new(k.to_string()));
    }
    if let Some(lang) = filters.language {
        conditions.push(format!("{alias}.language = ?"));
        params.push(Box::new(lang.to_string()));
    }
    if let Some(like) = filters.path.and_then(glob_to_like_prefix) {
        conditions.push(format!("{alias}.file_path LIKE ?"));
        params.push(Box::new(like));
    }
}

fn append_unique_symbols(
    out: &mut Vec<Symbol>,
    seen: &mut HashSet<String>,
    symbols: Vec<Symbol>,
    limit: usize,
) {
    for symbol in symbols {
        if seen.insert(symbol.id.clone()) {
            out.push(symbol);
            if out.len() >= limit {
                return;
            }
        }
    }
}

fn query_symbols_by_name_predicate(
    conn: &Connection,
    project_id: &str,
    predicate: &str,
    predicate_values: Vec<String>,
    filters: SymbolFilters<'_>,
    limit: usize,
) -> Vec<Symbol> {
    let mut conditions = vec!["cs.project_id = ?".to_string(), predicate.to_string()];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![Box::new(project_id.to_string())];
    for value in predicate_values {
        params.push(Box::new(value));
    }
    push_symbol_filters(&mut conditions, &mut params, "cs", filters);
    params.push(Box::new(limit as i64));

    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT cs.* FROM code_symbols cs \
         JOIN code_indexed_files cf \
              ON cf.project_id = cs.project_id AND cf.file_path = cs.file_path \
         WHERE {where_clause} \
         ORDER BY cs.file_path, cs.line_start \
         LIMIT ?"
    );

    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    let mut stmt = match conn.prepare(&sql) {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };
    stmt.query_map(param_refs.as_slice(), Symbol::from_row)
        .ok()
        .map(|rows| rows.filter_map(|r| r.ok()).collect())
        .unwrap_or_default()
}

/// Sanitize user input for FTS5 queries.
/// Strips special characters and quotes each token for safe matching.
pub fn sanitize_fts_query(query: &str) -> String {
    let cleaned: String = query
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '_')
        .collect();
    let tokens: Vec<&str> = cleaned
        .split_whitespace()
        .filter(|t| !t.is_empty())
        .collect();
    if tokens.is_empty() {
        return String::new();
    }
    tokens
        .iter()
        .map(|t| format!("\"{t}\""))
        .collect::<Vec<_>>()
        .join(" ")
}

/// FTS5 search across symbol names, signatures, docstrings, and summaries.
pub fn search_symbols_fts(
    conn: &Connection,
    query: &str,
    project_id: &str,
    kind: Option<&str>,
    language: Option<&str>,
    path: Option<&str>,
    limit: usize,
) -> Vec<Symbol> {
    let fts_query = sanitize_fts_query(query);
    if fts_query.is_empty() {
        return Vec::new();
    }

    let mut conditions = vec!["cs.project_id = ?".to_string()];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> =
        vec![Box::new(fts_query), Box::new(project_id.to_string())];
    let filters = SymbolFilters {
        kind,
        language,
        path,
    };
    push_symbol_filters(&mut conditions, &mut params, "cs", filters);
    params.push(Box::new(limit as i64));

    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT cs.* FROM code_symbols_fts fts \
         JOIN code_symbols cs ON cs.rowid = fts.rowid \
         JOIN code_indexed_files cf \
              ON cf.project_id = cs.project_id AND cf.file_path = cs.file_path \
         WHERE code_symbols_fts MATCH ? AND {where_clause} \
         ORDER BY rank LIMIT ?"
    );

    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    let mut stmt = match conn.prepare(&sql) {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };
    stmt.query_map(param_refs.as_slice(), Symbol::from_row)
        .ok()
        .map(|rows| rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
        .unwrap_or_default()
}

/// Fallback LIKE search on symbol names.
pub fn search_symbols_by_name(
    conn: &Connection,
    query: &str,
    project_id: &str,
    kind: Option<&str>,
    language: Option<&str>,
    path: Option<&str>,
    limit: usize,
) -> Vec<Symbol> {
    let escaped_query = escape_like(query);
    let pattern = format!("%{escaped_query}%");
    let mut conditions = vec![
        "cs.project_id = ?".to_string(),
        "(cs.name LIKE ? ESCAPE '\\' OR cs.qualified_name LIKE ? ESCAPE '\\')".to_string(),
    ];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![
        Box::new(project_id.to_string()),
        Box::new(pattern.clone()),
        Box::new(pattern),
    ];
    let filters = SymbolFilters {
        kind,
        language,
        path,
    };
    push_symbol_filters(&mut conditions, &mut params, "cs", filters);
    params.push(Box::new(limit as i64));

    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT cs.* FROM code_symbols cs \
         JOIN code_indexed_files cf \
              ON cf.project_id = cs.project_id AND cf.file_path = cs.file_path \
         WHERE {where_clause} \
         ORDER BY cs.name, cs.file_path, cs.line_start LIMIT ?"
    );

    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    let mut stmt = match conn.prepare(&sql) {
        Ok(s) => s,
        Err(_) => return Vec::new(),
    };
    stmt.query_map(param_refs.as_slice(), Symbol::from_row)
        .ok()
        .map(|rows| rows.filter_map(|r| r.ok()).collect())
        .unwrap_or_default()
}

pub fn search_symbols_exact_first(
    conn: &Connection,
    query: &str,
    project_id: &str,
    kind: Option<&str>,
    language: Option<&str>,
    path: Option<&str>,
    limit: usize,
) -> Vec<Symbol> {
    if query.trim().is_empty() || limit == 0 {
        return Vec::new();
    }

    let mut results = Vec::new();
    let mut seen = HashSet::new();
    let filters = SymbolFilters {
        kind,
        language,
        path,
    };

    let exact = query_symbols_by_name_predicate(
        conn,
        project_id,
        "(cs.name = ? OR cs.qualified_name = ?)",
        vec![query.to_string(), query.to_string()],
        filters,
        limit,
    );
    append_unique_symbols(&mut results, &mut seen, exact, limit);
    if results.len() >= limit {
        return results;
    }

    let ci_exact = query_symbols_by_name_predicate(
        conn,
        project_id,
        "(lower(cs.name) = lower(?) OR lower(cs.qualified_name) = lower(?))",
        vec![query.to_string(), query.to_string()],
        filters,
        limit,
    );
    append_unique_symbols(&mut results, &mut seen, ci_exact, limit);
    if results.len() >= limit {
        return results;
    }

    let prefix = format!("{}%", escape_like(query));
    let prefix_matches = query_symbols_by_name_predicate(
        conn,
        project_id,
        "(cs.name LIKE ? ESCAPE '\\' OR cs.qualified_name LIKE ? ESCAPE '\\')",
        vec![prefix.clone(), prefix],
        filters,
        limit,
    );
    append_unique_symbols(&mut results, &mut seen, prefix_matches, limit);
    if results.len() >= limit {
        return results;
    }

    let contains = search_symbols_by_name(conn, query, project_id, kind, language, path, limit);
    append_unique_symbols(&mut results, &mut seen, contains, limit);
    if results.len() >= limit {
        return results;
    }

    let fts = search_symbols_fts(conn, query, project_id, kind, language, path, limit);
    append_unique_symbols(&mut results, &mut seen, fts, limit);

    results
}

fn exact_symbol_matches(
    conn: &Connection,
    project_id: &str,
    column: &str,
    input: &str,
    limit: usize,
) -> Vec<Symbol> {
    let sql = format!(
        "SELECT * FROM code_symbols \
         WHERE project_id = ?1 AND {column} = ?2 \
         ORDER BY file_path, line_start \
         LIMIT ?3"
    );
    let mut stmt = match conn.prepare(&sql) {
        Ok(stmt) => stmt,
        Err(_) => return Vec::new(),
    };
    stmt.query_map(
        rusqlite::params![project_id, input, limit as i64],
        Symbol::from_row,
    )
    .ok()
    .map(|rows| rows.filter_map(|row| row.ok()).collect())
    .unwrap_or_default()
}

fn suggestion_label(symbol: &Symbol) -> String {
    format!(
        "{} ({}:{})",
        symbol.qualified_name, symbol.file_path, symbol.line_start
    )
}

fn resolved_symbol(symbol: &Symbol) -> ResolvedGraphSymbol {
    ResolvedGraphSymbol {
        id: symbol.id.clone(),
        display_name: symbol.name.clone(),
    }
}

fn resolve_from_candidates(candidates: Vec<Symbol>) -> (Option<ResolvedGraphSymbol>, Vec<String>) {
    match candidates.len() {
        0 => (None, vec![]),
        1 => (Some(resolved_symbol(&candidates[0])), vec![]),
        _ => {
            let mut suggestions = Vec::new();
            let mut seen = HashSet::new();
            for symbol in &candidates {
                let label = suggestion_label(symbol);
                if seen.insert(label.clone()) {
                    suggestions.push(label);
                }
            }
            (None, suggestions)
        }
    }
}

/// Resolve user input to a canonical symbol id for graph queries.
///
/// Resolution is fail-closed: ambiguous matches return `None` with suggestions.
pub fn resolve_graph_symbol(
    conn: &Connection,
    input: &str,
    project_id: &str,
) -> (Option<ResolvedGraphSymbol>, Vec<String>) {
    let ids = exact_symbol_matches(conn, project_id, "id", input, 2);
    let (resolved, suggestions) = resolve_from_candidates(ids);
    if resolved.is_some() || !suggestions.is_empty() {
        return (resolved, suggestions);
    }

    let qualified = exact_symbol_matches(conn, project_id, "qualified_name", input, 6);
    let (resolved, suggestions) = resolve_from_candidates(qualified);
    if resolved.is_some() || !suggestions.is_empty() {
        return (resolved, suggestions);
    }

    let exact = exact_symbol_matches(conn, project_id, "name", input, 6);
    let (resolved, suggestions) = resolve_from_candidates(exact);
    if resolved.is_some() || !suggestions.is_empty() {
        return (resolved, suggestions);
    }

    let like_matches = search_symbols_by_name(conn, input, project_id, None, None, None, 6);
    let (resolved, suggestions) = resolve_from_candidates(like_matches);
    if resolved.is_some() || !suggestions.is_empty() {
        return (resolved, suggestions);
    }

    let fts_results = search_symbols_fts(conn, input, project_id, None, None, None, 6);
    resolve_from_candidates(fts_results)
}

/// Count matching symbols (FTS5 with LIKE fallback).
pub fn count_text(
    conn: &Connection,
    query: &str,
    project_id: &str,
    language: Option<&str>,
    path: Option<&str>,
) -> usize {
    let fts_query = sanitize_fts_query(query);
    if fts_query.is_empty() {
        return 0;
    }

    let mut conditions = vec!["cs.project_id = ?".to_string()];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![
        Box::new(fts_query.clone()),
        Box::new(project_id.to_string()),
    ];
    push_symbol_filters(
        &mut conditions,
        &mut params,
        "cs",
        SymbolFilters {
            kind: None,
            language,
            path,
        },
    );
    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT COUNT(*) FROM code_symbols_fts fts \
         JOIN code_symbols cs ON cs.rowid = fts.rowid \
         JOIN code_indexed_files cf \
              ON cf.project_id = cs.project_id AND cf.file_path = cs.file_path \
         WHERE code_symbols_fts MATCH ? AND {where_clause}"
    );
    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();

    let count: Option<usize> = conn
        .query_row(&sql, param_refs.as_slice(), |row| row.get(0))
        .ok();

    if let Some(n) = count {
        if n > 0 {
            return n;
        }
    }

    // Fallback to LIKE count
    let escaped_query = escape_like(query);
    let pattern = format!("%{escaped_query}%");
    let mut conditions = vec![
        "cs.project_id = ?".to_string(),
        "(cs.name LIKE ? ESCAPE '\\' OR cs.qualified_name LIKE ? ESCAPE '\\')".to_string(),
    ];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![
        Box::new(project_id.to_string()),
        Box::new(pattern.clone()),
        Box::new(pattern),
    ];
    push_symbol_filters(
        &mut conditions,
        &mut params,
        "cs",
        SymbolFilters {
            kind: None,
            language,
            path,
        },
    );
    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT COUNT(*) FROM code_symbols cs \
         JOIN code_indexed_files cf \
              ON cf.project_id = cs.project_id AND cf.file_path = cs.file_path \
         WHERE {where_clause}"
    );
    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    conn.query_row(&sql, param_refs.as_slice(), |row| row.get(0))
        .unwrap_or(0)
}

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

    fn setup_conn() -> Connection {
        let conn = Connection::open_in_memory().expect("open sqlite");
        conn.execute_batch(
            "CREATE TABLE code_symbols (
                id TEXT PRIMARY KEY,
                project_id TEXT NOT NULL,
                file_path TEXT NOT NULL,
                name TEXT NOT NULL,
                qualified_name TEXT NOT NULL,
                kind TEXT NOT NULL,
                language TEXT NOT NULL,
                byte_start INTEGER NOT NULL,
                byte_end INTEGER NOT NULL,
                line_start INTEGER NOT NULL,
                line_end INTEGER NOT NULL,
                signature TEXT,
                docstring TEXT,
                parent_symbol_id TEXT,
                content_hash TEXT,
                summary TEXT,
                created_at TEXT,
                updated_at TEXT
            );
            CREATE TABLE code_indexed_files (
                project_id TEXT NOT NULL,
                file_path TEXT NOT NULL
            );
            CREATE VIRTUAL TABLE code_symbols_fts USING fts5(name, signature, docstring, summary);",
        )
        .expect("create schema");
        conn
    }

    fn insert_symbol(
        conn: &Connection,
        id: &str,
        file_path: &str,
        name: &str,
        qualified_name: &str,
        summary: Option<&str>,
    ) {
        insert_symbol_with(
            conn,
            id,
            file_path,
            name,
            qualified_name,
            "function",
            "python",
            summary,
        );
    }

    fn insert_symbol_with(
        conn: &Connection,
        id: &str,
        file_path: &str,
        name: &str,
        qualified_name: &str,
        kind: &str,
        language: &str,
        summary: Option<&str>,
    ) {
        conn.execute(
            "INSERT INTO code_symbols (
                id, project_id, file_path, name, qualified_name, kind, language,
                byte_start, byte_end, line_start, line_end, signature, docstring,
                parent_symbol_id, content_hash, summary, created_at, updated_at
            ) VALUES (
                ?1, 'proj', ?2, ?3, ?4, ?5, ?6,
                0, 10, 1, 1, '', '', NULL, '', ?7, '', ''
            )",
            rusqlite::params![id, file_path, name, qualified_name, kind, language, summary],
        )
        .expect("insert symbol");
        let rowid = conn.last_insert_rowid();
        conn.execute(
            "INSERT INTO code_indexed_files (project_id, file_path) VALUES ('proj', ?1)",
            rusqlite::params![file_path],
        )
        .expect("insert indexed file");
        conn.execute(
            "INSERT INTO code_symbols_fts(rowid, name, signature, docstring, summary)
             VALUES (?1, ?2, '', '', ?3)",
            rusqlite::params![rowid, name, summary.unwrap_or_default()],
        )
        .expect("insert fts row");
    }

    #[test]
    fn resolve_graph_symbol_by_exact_name() {
        let conn = setup_conn();
        insert_symbol(&conn, "sym-1", "src/main.py", "foo", "foo", Some("helper"));

        let (resolved, suggestions) = resolve_graph_symbol(&conn, "foo", "proj");

        assert!(suggestions.is_empty());
        assert_eq!(
            resolved,
            Some(ResolvedGraphSymbol {
                id: "sym-1".to_string(),
                display_name: "foo".to_string(),
            })
        );
    }

    #[test]
    fn resolve_graph_symbol_uses_like_fallback() {
        let conn = setup_conn();
        insert_symbol(
            &conn,
            "sym-1",
            "src/mailer.py",
            "render_email",
            "render_email",
            Some("helper"),
        );

        let (resolved, suggestions) = resolve_graph_symbol(&conn, "render", "proj");

        assert!(suggestions.is_empty());
        assert_eq!(resolved.map(|symbol| symbol.id), Some("sym-1".to_string()));
    }

    #[test]
    fn resolve_graph_symbol_uses_fts_fallback() {
        let conn = setup_conn();
        insert_symbol(
            &conn,
            "sym-1",
            "src/mailer.py",
            "send_email",
            "send_email",
            Some("mailer helper"),
        );

        let (resolved, suggestions) = resolve_graph_symbol(&conn, "mailer helper", "proj");

        assert!(suggestions.is_empty());
        assert_eq!(resolved.map(|symbol| symbol.id), Some("sym-1".to_string()));
    }

    #[test]
    fn resolve_graph_symbol_is_fail_closed_on_ambiguity() {
        let conn = setup_conn();
        insert_symbol(&conn, "sym-1", "src/a.py", "foo", "foo", Some("a"));
        insert_symbol(&conn, "sym-2", "src/b.py", "foo", "foo", Some("b"));

        let (resolved, suggestions) = resolve_graph_symbol(&conn, "foo", "proj");

        assert!(resolved.is_none());
        assert_eq!(suggestions.len(), 2);
    }

    #[test]
    fn search_symbols_exact_first_prioritizes_exact_name() {
        let conn = setup_conn();
        insert_symbol(
            &conn,
            "sym-1",
            "src/outline_helpers.py",
            "outline_helper",
            "outline_helper",
            None,
        );
        insert_symbol(
            &conn,
            "sym-2",
            "src/commands.py",
            "outline",
            "outline",
            None,
        );

        let results = search_symbols_exact_first(&conn, "outline", "proj", None, None, None, 10);

        assert_eq!(results[0].id, "sym-2");
    }

    #[test]
    fn search_symbols_exact_first_respects_kind_language_and_path() {
        let conn = setup_conn();
        insert_symbol_with(
            &conn,
            "sym-1",
            "src/commands.py",
            "outline",
            "outline",
            "function",
            "python",
            None,
        );
        insert_symbol_with(
            &conn,
            "sym-2",
            "src/commands.rs",
            "outline",
            "outline",
            "function",
            "rust",
            None,
        );

        let results = search_symbols_exact_first(
            &conn,
            "outline",
            "proj",
            Some("function"),
            Some("rust"),
            Some("src/**/*.rs"),
            10,
        );

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id, "sym-2");
    }
}

/// Count matching content chunks (FTS5 with LIKE fallback).
pub fn count_content(
    conn: &Connection,
    query: &str,
    project_id: &str,
    language: Option<&str>,
    path: Option<&str>,
) -> usize {
    if query.trim().is_empty() {
        return 0;
    }

    let safe_query = query.replace('"', "\"\"");
    let fts_match = format!("\"{safe_query}\"");

    let mut conditions = vec!["c.project_id = ?".to_string()];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> =
        vec![Box::new(fts_match), Box::new(project_id.to_string())];
    if let Some(lang) = language {
        conditions.push("c.language = ?".to_string());
        params.push(Box::new(lang.to_string()));
    }
    if let Some(like) = path.and_then(glob_to_like_prefix) {
        conditions.push("c.file_path LIKE ?".to_string());
        params.push(Box::new(like));
    }
    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT COUNT(*) FROM code_content_fts fts \
         JOIN code_content_chunks c ON c.rowid = fts.rowid \
         JOIN code_indexed_files cf \
              ON cf.project_id = c.project_id AND cf.file_path = c.file_path \
         WHERE code_content_fts MATCH ? AND {where_clause}"
    );
    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();

    let count: Option<usize> = conn
        .query_row(&sql, param_refs.as_slice(), |row| row.get(0))
        .ok();

    if let Some(n) = count {
        if n > 0 {
            return n;
        }
    }

    // Fallback to LIKE count
    let escaped_query = escape_like(query);
    let like_query = format!("%{escaped_query}%");
    let mut conditions = vec![
        "c.project_id = ?".to_string(),
        "c.content LIKE ? ESCAPE '\\'".to_string(),
    ];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> =
        vec![Box::new(project_id.to_string()), Box::new(like_query)];
    if let Some(lang) = language {
        conditions.push("c.language = ?".to_string());
        params.push(Box::new(lang.to_string()));
    }
    if let Some(like) = path.and_then(glob_to_like_prefix) {
        conditions.push("c.file_path LIKE ?".to_string());
        params.push(Box::new(like));
    }
    let where_clause = conditions.join(" AND ");
    let sql = format!(
        "SELECT COUNT(*) FROM code_content_chunks c \
         JOIN code_indexed_files cf \
              ON cf.project_id = c.project_id AND cf.file_path = c.file_path \
         WHERE {where_clause}"
    );
    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    conn.query_row(&sql, param_refs.as_slice(), |row| row.get(0))
        .unwrap_or(0)
}

/// Full-text search for symbols: FTS5 with LIKE fallback.
pub fn search_text(
    conn: &Connection,
    query: &str,
    project_id: &str,
    language: Option<&str>,
    path: Option<&str>,
    limit: usize,
) -> Vec<SearchResult> {
    let mut results = search_symbols_fts(conn, query, project_id, None, language, path, limit);
    if results.is_empty() {
        results = search_symbols_by_name(conn, query, project_id, None, language, path, limit);
    }
    results.into_iter().map(|s| s.to_brief()).collect()
}

/// Full-text search across file content chunks.
pub fn search_content(
    conn: &Connection,
    query: &str,
    project_id: &str,
    language: Option<&str>,
    path: Option<&str>,
    limit: usize,
) -> Vec<ContentSearchHit> {
    if query.trim().is_empty() {
        return Vec::new();
    }

    let safe_query = query.replace('"', "\"\"");
    let fts_match = format!("\"{safe_query}\"");

    // Try FTS5 first
    let mut conditions = vec!["c.project_id = ?".to_string()];
    let mut params: Vec<Box<dyn rusqlite::types::ToSql>> =
        vec![Box::new(fts_match), Box::new(project_id.to_string())];
    if let Some(lang) = language {
        conditions.push("c.language = ?".to_string());
        params.push(Box::new(lang.to_string()));
    }
    if let Some(like) = path.and_then(glob_to_like_prefix) {
        conditions.push("c.file_path LIKE ?".to_string());
        params.push(Box::new(like));
    }
    params.push(Box::new(limit as i64));
    let where_clause = conditions.join(" AND ");

    let sql = format!(
        "SELECT c.file_path, c.line_start, c.line_end, c.language, \
         snippet(code_content_fts, 0, '>>>', '<<<', '...', 40) as snippet \
         FROM code_content_fts fts \
         JOIN code_content_chunks c ON c.rowid = fts.rowid \
         JOIN code_indexed_files cf \
              ON cf.project_id = c.project_id AND cf.file_path = c.file_path \
         WHERE code_content_fts MATCH ? AND {where_clause} \
         ORDER BY rank LIMIT ?"
    );

    let param_refs: Vec<&dyn rusqlite::types::ToSql> = params.iter().map(|p| p.as_ref()).collect();
    let fts_result: Result<Vec<ContentSearchHit>, rusqlite::Error> = (|| {
        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(param_refs.as_slice(), |row| {
            Ok(ContentSearchHit {
                file_path: row.get("file_path")?,
                line_start: row.get::<_, i64>("line_start")? as usize,
                line_end: row.get::<_, i64>("line_end")? as usize,
                snippet: row.get("snippet")?,
                language: row.get("language")?,
            })
        })?;
        Ok(rows.filter_map(|r| r.ok()).collect())
    })();

    match fts_result {
        Ok(hits) if !hits.is_empty() => hits,
        _ => {
            // Fallback to LIKE search
            let escaped_query = escape_like(query);
            let like_query = format!("%{escaped_query}%");
            let mut conditions = vec![
                "c.project_id = ?".to_string(),
                "c.content LIKE ? ESCAPE '\\'".to_string(),
            ];
            let mut params: Vec<Box<dyn rusqlite::types::ToSql>> = vec![
                Box::new(query.to_string()),
                Box::new(project_id.to_string()),
                Box::new(like_query),
            ];
            if let Some(lang) = language {
                conditions.push("c.language = ?".to_string());
                params.push(Box::new(lang.to_string()));
            }
            if let Some(like) = path.and_then(glob_to_like_prefix) {
                conditions.push("c.file_path LIKE ?".to_string());
                params.push(Box::new(like));
            }
            params.push(Box::new(limit as i64));
            let where_clause = conditions.join(" AND ");
            let sql = format!(
                "SELECT c.file_path, c.line_start, c.line_end, c.language, \
                 substr(c.content, max(1, instr(c.content, ?) - 60), 120) as snippet \
                 FROM code_content_chunks c \
                 JOIN code_indexed_files cf \
                      ON cf.project_id = c.project_id AND cf.file_path = c.file_path \
                 WHERE {where_clause} LIMIT ?"
            );
            let param_refs: Vec<&dyn rusqlite::types::ToSql> =
                params.iter().map(|p| p.as_ref()).collect();
            let mut stmt = match conn.prepare(&sql) {
                Ok(s) => s,
                Err(_) => return Vec::new(),
            };
            stmt.query_map(param_refs.as_slice(), |row| {
                Ok(ContentSearchHit {
                    file_path: row.get("file_path")?,
                    line_start: row.get::<_, i64>("line_start")? as usize,
                    line_end: row.get::<_, i64>("line_end")? as usize,
                    snippet: row.get("snippet")?,
                    language: row.get("language")?,
                })
            })
            .ok()
            .map(|rows| rows.filter_map(|r| r.ok()).collect())
            .unwrap_or_default()
        }
    }
}

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

    fn setup_conn() -> Connection {
        let conn = Connection::open_in_memory().expect("open sqlite");
        conn.execute_batch(
            "CREATE TABLE code_content_chunks (
                id TEXT PRIMARY KEY,
                project_id TEXT NOT NULL,
                file_path TEXT NOT NULL,
                chunk_index INTEGER NOT NULL,
                line_start INTEGER NOT NULL,
                line_end INTEGER NOT NULL,
                content TEXT NOT NULL,
                language TEXT,
                created_at TEXT
            );
            CREATE TABLE code_indexed_files (
                project_id TEXT NOT NULL,
                file_path TEXT NOT NULL
            );
            CREATE VIRTUAL TABLE code_content_fts USING fts5(
                content, file_path, language,
                content='code_content_chunks', content_rowid='rowid'
            );",
        )
        .expect("create schema");
        conn
    }

    fn insert_chunk(conn: &Connection, file_path: &str, language: &str, content: &str) {
        conn.execute(
            "INSERT INTO code_content_chunks (
                id, project_id, file_path, chunk_index, line_start, line_end,
                content, language, created_at
             ) VALUES ('chunk-1', 'proj', ?1, 0, 1, 10, ?2, ?3, '')",
            rusqlite::params![file_path, content, language],
        )
        .expect("insert chunk");
        let rowid = conn.last_insert_rowid();
        conn.execute(
            "INSERT INTO code_content_fts(rowid, content, file_path, language)
             VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![rowid, content, file_path, language],
        )
        .expect("insert fts row");
    }

    #[test]
    fn search_content_excludes_orphan_chunks() {
        let conn = setup_conn();
        insert_chunk(&conn, "src/missing.rs", "rust", "pub fn outline() {}");

        let results = search_content(&conn, "outline", "proj", None, None, 10);

        assert!(results.is_empty());
    }

    #[test]
    fn search_content_returns_chunks_with_indexed_file_row() {
        let conn = setup_conn();
        insert_chunk(&conn, "src/lib.rs", "rust", "pub fn outline() {}");
        conn.execute(
            "INSERT INTO code_indexed_files (project_id, file_path) VALUES ('proj', 'src/lib.rs')",
            [],
        )
        .expect("insert indexed file");

        let results = search_content(&conn, "outline", "proj", Some("rust"), None, 10);

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].file_path, "src/lib.rs");
    }
}