llmgrep 3.4.3

Smart grep over Magellan code maps with schema-aligned JSON output
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
//! Backend abstraction for SQLite and Geometric storage.
//!
//! The Backend trait provides a unified interface for code graph queries
//! across different storage backends. This enables runtime backend detection
//! and zero breaking changes to existing functionality.

use crate::error::LlmError;
use crate::output::{
    CallSearchResponse, DocsSearchResponse, FactsSearchResponse, ImplementsSearchResponse,
    ReferenceSearchResponse, SearchResponse,
};
use crate::query::{DocsSearchOptions, FactsSearchOptions, SearchOptions};
use std::path::Path;

// Backend implementation modules
#[cfg(feature = "geometric-backend")]
pub mod geometric;
#[cfg(feature = "geometric-backend")]
pub mod magellan_adapter; // Contract-aware Magellan adapter layer
pub mod schema_check;
pub mod sqlite;

#[cfg(feature = "geometric-backend")]
pub use geometric::GeometricBackend;
#[cfg(feature = "geometric-backend")]
pub use magellan_adapter::{
    apply_path_filter, lookup_symbol_by_path_and_name, normalize_path_for_query, paths_equivalent,
    SymbolLookupResult,
};
pub use sqlite::SqliteBackend;

/// Backend trait for abstracting over SQLite and Geometric storage.
///
/// All backend implementations must provide these core operations:
/// - Symbol search with filtering and scoring
/// - Reference search (incoming edges)
/// - Call search (outgoing edges)
/// - AST tree queries
/// - AST node search by kind
///
/// Note: This trait does not require Send or Sync because:
/// - rusqlite::Connection is not Sync
///
/// Each backend instance should be used from a single thread or externally synchronized.
pub trait BackendTrait {
    /// Search for symbols matching the given options.
    ///
    /// Returns a tuple of (response, partial_results_flag, paths_bounded_flag).
    /// - partial_results: true if candidates limit was hit
    /// - paths_bounded: true if path enumeration hit bounds
    fn search_symbols(
        &self,
        options: SearchOptions,
    ) -> Result<(SearchResponse, bool, bool), LlmError>;

    /// Search for references (incoming edges) to symbols.
    fn search_references(
        &self,
        options: SearchOptions,
    ) -> Result<(ReferenceSearchResponse, bool), LlmError>;

    /// Search for function calls (outgoing edges) from symbols.
    fn search_calls(&self, options: SearchOptions) -> Result<(CallSearchResponse, bool), LlmError>;

    /// Search for type-trait implementation relationships.
    fn search_implements(
        &self,
        options: SearchOptions,
    ) -> Result<(ImplementsSearchResponse, bool), LlmError>;

    fn search_docs(&self, options: DocsSearchOptions) -> Result<DocsSearchResponse, LlmError>;

    fn search_facts(&self, options: FactsSearchOptions) -> Result<FactsSearchResponse, LlmError>;

    /// Query AST nodes for a file.
    ///
    /// # Arguments
    /// * `file` - Path to the source file
    /// * `position` - Optional byte offset to query node at specific position
    /// * `limit` - Maximum number of AST nodes to return (for large files)
    fn ast(
        &self,
        file: &Path,
        position: Option<usize>,
        limit: usize,
    ) -> Result<serde_json::Value, LlmError>;

    /// Find AST nodes by kind.
    ///
    /// # Arguments
    /// * `kind` - AST node kind (e.g., "function_item", "if_expression")
    fn find_ast(&self, kind: &str) -> Result<serde_json::Value, LlmError>;

    /// Get FQN completions for a prefix.
    ///
    /// This method provides prefix-based autocomplete for fully qualified names.
    ///
    /// # Arguments
    /// * `prefix` - Prefix string to match (e.g., "std::collections")
    /// * `limit` - Maximum number of completions to return
    fn complete(&self, prefix: &str, limit: usize) -> Result<Vec<String>, LlmError>;

    /// Lookup symbol by exact fully-qualified name.
    ///
    /// This method provides symbol resolution by FQN.
    ///
    /// # Arguments
    /// * `fqn` - Fully-qualified name to lookup (e.g., "std::collections::HashMap::new")
    /// * `db_path` - Database path for error reporting
    ///
    /// # Returns
    /// * `Ok(SymbolMatch)` - Full symbol details if found
    /// * `Err(LlmError::SymbolNotFound)` - If FQN does not exist in database
    fn lookup(&self, fqn: &str, db_path: &str) -> Result<crate::output::SymbolMatch, LlmError>;

    /// Search for symbols by label.
    ///
    /// This method provides purpose-based label search using Magellan's label system.
    /// Labels group symbols by purpose category (e.g., "test", "entry_point", "public_api").
    ///
    /// # Arguments
    /// * `label` - Label name to search for (e.g., "test", "entry_point")
    /// * `limit` - Maximum number of symbols to return
    /// * `db_path` - Database path for error reporting
    ///
    /// # Returns
    /// * `Ok((SearchResponse, partial, paths_bounded))` - Search results and metadata
    fn search_by_label(
        &self,
        label: &str,
        limit: usize,
        db_path: &str,
    ) -> Result<(SearchResponse, bool, bool), LlmError>;

    /// Get code chunks for a specific symbol.
    ///
    /// This method provides pre-extracted code snippets for a symbol,
    /// avoiding expensive file I/O. Chunks are created during Magellan indexing.
    ///
    /// # Arguments
    /// * `file_path` - Path to the source file
    /// * `symbol_name` - Name of the symbol
    ///
    /// # Returns
    /// * `Ok(Vec<CodeChunk>)` - List of chunks for the symbol
    /// * `Err(LlmError::ChunksNotAvailable)` - If chunking was not performed
    #[cfg(feature = "geometric-backend")]
    fn get_chunks_for_symbol(
        &self,
        file_path: &str,
        symbol_name: &str,
    ) -> Result<Vec<crate::backend::magellan_adapter::CodeChunk>, LlmError>;
}

/// Runtime backend dispatcher.
///
/// Wraps either SqliteBackend or GeometricBackend and delegates Backend trait methods
/// to the appropriate implementation based on database format detection.
#[derive(Debug)]
pub enum Backend {
    /// SQLite storage backend (traditional, always available)
    Sqlite(SqliteBackend),
    /// Geometric storage backend (spatial/CGF optimized, requires geometric-backend feature)
    #[cfg(feature = "geometric-backend")]
    Geometric(GeometricBackend),
}

/// Check if a database file path has the geometric backend extension.
fn is_geometric_extension(path: &std::path::Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| e == "geo")
        .unwrap_or(false)
}

impl Backend {
    /// Detect backend format from database file and open appropriate backend.
    ///
    /// Checks file extension and header magic bytes to distinguish between:
    /// - Geometric backend: ".geo" extension
    /// - SQLite backend: "SQLite format 3\0" header
    ///
    /// # Arguments
    /// * `db_path` - Path to the database file
    ///
    /// # Returns
    /// * `Ok(Backend)` - Appropriate backend variant based on file detection
    /// * `Err(LlmError::BackendDetectionFailed)` - Detection failed
    pub fn detect_and_open(db_path: &Path) -> Result<Self, LlmError> {
        use std::fs::File;
        use std::io::Read;

        // Check if file exists
        if !db_path.exists() {
            return Err(LlmError::DatabaseNotFound {
                path: db_path.display().to_string(),
            });
        }

        // First check file extension for geometric backend
        #[cfg(feature = "geometric-backend")]
        {
            if is_geometric_extension(db_path) {
                return GeometricBackend::open(db_path).map(Backend::Geometric);
            }
        }

        #[cfg(not(feature = "geometric-backend"))]
        {
            if is_geometric_extension(db_path) {
                return Err(LlmError::BackendDetectionFailed {
                    path: db_path.display().to_string(),
                    reason: "Geometric backend (.geo files) requires 'geometric-backend' feature"
                        .to_string(),
                });
            }
        }

        // Read first 16 bytes to detect format
        let mut file = File::open(db_path).map_err(|e| LlmError::BackendDetectionFailed {
            path: db_path.display().to_string(),
            reason: format!("Cannot open file: {}", e),
        })?;

        let mut header = [0u8; 16];
        file.read_exact(&mut header)
            .map_err(|e| LlmError::BackendDetectionFailed {
                path: db_path.display().to_string(),
                reason: format!("Cannot read file header: {}", e),
            })?;

        // Check for SQLite format: "SQLite format 3\0"
        let is_sqlite = &header[0..16] == b"SQLite format 3\0";

        if is_sqlite {
            SqliteBackend::open(db_path).map(Backend::Sqlite)
        } else {
            // Unknown format, try SQLite as fallback (may fail with better error)
            SqliteBackend::open(db_path).map(Backend::Sqlite)
        }
    }

    /// Delegate search_symbols to inner backend.
    pub fn search_symbols(
        &self,
        options: SearchOptions,
    ) -> Result<(SearchResponse, bool, bool), LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_symbols(options),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_symbols(options),
        }
    }

    /// Delegate search_references to inner backend.
    pub fn search_references(
        &self,
        options: SearchOptions,
    ) -> Result<(ReferenceSearchResponse, bool), LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_references(options),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_references(options),
        }
    }

    /// Delegate search_calls to inner backend.
    pub fn search_calls(
        &self,
        options: SearchOptions,
    ) -> Result<(CallSearchResponse, bool), LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_calls(options),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_calls(options),
        }
    }

    /// Delegate search_implements to inner backend.
    pub fn search_implements(
        &self,
        options: SearchOptions,
    ) -> Result<(ImplementsSearchResponse, bool), LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_implements(options),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_implements(options),
        }
    }

    pub fn search_docs(
        &self,
        options: DocsSearchOptions,
    ) -> Result<DocsSearchResponse, LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_docs(options),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_docs(options),
        }
    }

    pub fn search_facts(
        &self,
        options: FactsSearchOptions,
    ) -> Result<FactsSearchResponse, LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_facts(options),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_facts(options),
        }
    }

    /// Delegate ast to inner backend.
    pub fn ast(
        &self,
        file: &Path,
        position: Option<usize>,
        limit: usize,
    ) -> Result<serde_json::Value, LlmError> {
        match self {
            Backend::Sqlite(b) => b.ast(file, position, limit),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.ast(file, position, limit),
        }
    }

    /// Delegate find_ast to inner backend.
    pub fn find_ast(&self, kind: &str) -> Result<serde_json::Value, LlmError> {
        match self {
            Backend::Sqlite(b) => b.find_ast(kind),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.find_ast(kind),
        }
    }

    /// Get FQN completions for a prefix.
    pub fn complete(&self, prefix: &str, limit: usize) -> Result<Vec<String>, LlmError> {
        match self {
            Backend::Sqlite(b) => b.complete(prefix, limit),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.complete(prefix, limit),
        }
    }

    /// Lookup symbol by exact FQN.
    pub fn lookup(&self, fqn: &str, db_path: &str) -> Result<crate::output::SymbolMatch, LlmError> {
        match self {
            Backend::Sqlite(b) => b.lookup(fqn, db_path),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.lookup(fqn, db_path),
        }
    }

    /// Search for symbols by label.
    pub fn search_by_label(
        &self,
        label: &str,
        limit: usize,
        db_path: &str,
    ) -> Result<(SearchResponse, bool, bool), LlmError> {
        match self {
            Backend::Sqlite(b) => b.search_by_label(label, limit, db_path),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.search_by_label(label, limit, db_path),
        }
    }

    /// Get code chunks for a specific symbol.
    ///
    /// This method provides pre-extracted code snippets for a symbol.
    /// Geometric backend supports chunks from .geo files.
    /// SQLite backend returns ChunksNotAvailable error.
    #[cfg(feature = "geometric-backend")]
    pub fn get_chunks_for_symbol(
        &self,
        file_path: &str,
        symbol_name: &str,
    ) -> Result<Vec<crate::backend::magellan_adapter::CodeChunk>, LlmError> {
        match self {
            Backend::Sqlite(_) => Err(LlmError::ChunksNotAvailable {
                backend: "SQLite".to_string(),
                message:
                    "SQLite backend does not support chunk retrieval. Use Geometric (.geo) backend."
                        .to_string(),
            }),
            #[cfg(feature = "geometric-backend")]
            Backend::Geometric(b) => b.get_chunks_for_symbol(file_path, symbol_name),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[cfg(feature = "geometric-backend")]
    fn create_test_geo_db() -> (tempfile::TempDir, std::path::PathBuf) {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let geo_path = temp_dir.path().join("test.geo");

        // Create a valid geometric database using Magellan's API
        // We need to use magellan directly since GeometricBackend::inner is private
        let _backend = magellan::graph::geometric_backend::GeometricBackend::create(&geo_path)
            .expect("Failed to create test geo database");

        (temp_dir, geo_path)
    }

    #[test]
    #[cfg(feature = "geometric-backend")]
    fn test_detect_and_open_geometric_backend() {
        // Layer 1: Test geometric backend detection by extension
        let (_temp_dir, geo_path) = create_test_geo_db();

        let result = Backend::detect_and_open(&geo_path);

        // Layer 1: Should succeed
        assert!(
            result.is_ok(),
            "Layer 1: Should detect and open .geo file: {:?}",
            result.err()
        );

        // Layer 2: Should be Geometric variant
        match result.unwrap() {
            Backend::Geometric(_) => {
                // Success - correct backend type
            }
            _ => panic!("Layer 2: Expected Geometric backend variant"),
        }
    }

    #[test]
    fn test_detect_and_open_sqlite_backend() {
        // Layer 1: Test SQLite backend detection by header
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"SQLite format 3\0").unwrap();

        let result = Backend::detect_and_open(temp_file.path());

        // Layer 1: Should succeed (even if open fails later due to invalid SQLite)
        // We just want to verify detection works
        // The actual opening may fail for an invalid SQLite file

        // Layer 2: For a valid SQLite header, should attempt SQLite
        // Note: This may fail to open due to invalid SQLite content, but detection should work
        if result.is_ok() {
            let backend = result.unwrap();
            assert!(
                matches!(backend, Backend::Sqlite(_)),
                "Layer 2: Expected Sqlite backend variant for SQLite header"
            );
        }
    }

    #[test]
    fn test_detect_and_open_nonexistent_file() {
        // Layer 1: Test error handling for non-existent file
        let fake_path = Path::new("/nonexistent/path/code.geo");

        let result = Backend::detect_and_open(fake_path);

        // Layer 1: Should fail
        assert!(
            result.is_err(),
            "Layer 1: Should fail for non-existent file"
        );

        // Layer 2: Should be DatabaseNotFound error
        match result {
            Err(LlmError::DatabaseNotFound { .. }) => {
                // Success - correct error type
            }
            _ => panic!("Layer 2: Expected DatabaseNotFound error"),
        }
    }
}