magellan 3.3.1

Deterministic codebase mapping tool for local development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Backend router for Magellan CLI
//!
//! Provides unified interface across different backend types (SQLite, Geometric, V3)
//! Automatically detects backend type from file extension and routes accordingly.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

use crate::graph::backend::Backend;
#[cfg(feature = "geometric-backend")]
use crate::graph::geometric_backend::{
    GeometricBackend, GeometricBackendStats, SymbolInfo as GeometricSymbolInfo,
};
use crate::graph::CodeGraph;
use crate::graph::SymbolNode;
use crate::ingest::SymbolKind;
use sqlitegraph::{GraphBackend, SnapshotId};

/// Unified symbol information across all backends
#[derive(Debug, Clone)]
pub struct UnifiedSymbolInfo {
    pub id: u64,
    pub name: String,
    pub fqn: String,
    pub kind: SymbolKind,
    pub file_path: String,
    pub byte_start: u64,
    pub byte_end: u64,
    pub start_line: u64,
    pub start_col: u64,
    pub end_line: u64,
    pub end_col: u64,
    /// Optional language for semantic enrichment
    pub language: Option<String>,
}

/// Backend types supported by Magellan
#[derive(Debug, PartialEq)]
pub enum BackendType {
    /// SQLite backend (default)
    SQLite,
    /// Geometric backend (spatial indexing)
    Geometric,
}

/// Unified backend interface
pub enum MagellanBackend {
    SQLite(CodeGraph),
    #[cfg(feature = "geometric-backend")]
    Geometric(GeometricBackend),
}

impl MagellanBackend {
    /// Detect backend type from file extension
    pub fn detect_type(db_path: &Path) -> BackendType {
        match db_path.extension().and_then(|e| e.to_str()) {
            #[cfg(feature = "geometric-backend")]
            Some("geo") => BackendType::Geometric,
            #[cfg(not(feature = "geometric-backend"))]
            Some("geo") => {
                // Fallback to SQLite if geometric backend is not available
                BackendType::SQLite
            }
            Some("db") | Some("sqlite") | Some("v3") | _ => BackendType::SQLite,
        }
    }

    /// Create a new database with automatic backend detection
    /// If the file already exists, this will return an error
    pub fn create(db_path: &Path) -> Result<Self> {
        match Self::detect_type(db_path) {
            #[cfg(feature = "geometric-backend")]
            BackendType::Geometric => {
                let backend = GeometricBackend::create(db_path)
                    .context("Failed to create geometric database")?;
                Ok(MagellanBackend::Geometric(backend))
            }
            #[cfg(not(feature = "geometric-backend"))]
            BackendType::Geometric => Err(anyhow::anyhow!(
                "Geometric backend requires 'geometric-backend' feature"
            )),
            BackendType::SQLite => {
                let graph = CodeGraph::open(db_path).context("Failed to create SQLite database")?;
                Ok(MagellanBackend::SQLite(graph))
            }
        }
    }

    /// Open or create a database with automatic backend detection
    /// If the file doesn't exist, it will be created
    pub fn open_or_create(db_path: &Path) -> Result<Self> {
        if db_path.exists() {
            Self::open(db_path)
        } else {
            Self::create(db_path)
        }
    }

    /// Open a database with automatic backend detection
    pub fn open(db_path: &Path) -> Result<Self> {
        match Self::detect_type(db_path) {
            #[cfg(feature = "geometric-backend")]
            BackendType::Geometric => {
                let backend =
                    GeometricBackend::open(db_path).context("Failed to open geometric database")?;
                Ok(MagellanBackend::Geometric(backend))
            }
            #[cfg(not(feature = "geometric-backend"))]
            BackendType::Geometric => Err(anyhow::anyhow!(
                "Geometric backend requires 'geometric-backend' feature"
            )),
            BackendType::SQLite => {
                let graph = CodeGraph::open(db_path).context("Failed to open SQLite database")?;
                Ok(MagellanBackend::SQLite(graph))
            }
        }
    }

    /// Find a symbol by its fully qualified name
    pub fn find_symbol_by_fqn(&self, fqn: &str) -> Result<Option<UnifiedSymbolInfo>> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => {
                // For numeric ID lookup (FQN is just the ID as string)
                if let Ok(id) = fqn.parse::<u64>() {
                    if let Some(info) = backend.find_symbol_by_id_info(id) {
                        return Ok(Some(Self::convert_geometric_symbol(&info)));
                    }
                }
                // Otherwise try FQN lookup
                if let Some(info) = backend.find_symbol_by_fqn_info(fqn) {
                    Ok(Some(Self::convert_geometric_symbol(&info)))
                } else {
                    Ok(None)
                }
            }
            MagellanBackend::SQLite(graph) => {
                // Try to parse as numeric ID first
                if let Ok(id) = fqn.parse::<i64>() {
                    let snapshot = SnapshotId::current();
                    if let Ok(node) = graph.backend().get_node(snapshot, id) {
                        if node.kind == "Symbol" {
                            if let Ok(symbol_node) = serde_json::from_value::<SymbolNode>(node.data)
                            {
                                return Ok(Some(Self::convert_symbol_node(&symbol_node, id)));
                            }
                        }
                    }
                }
                // Otherwise search by FQN
                let symbols = Self::get_all_sqlite_symbols(graph)?;
                for (entity_id, symbol) in symbols {
                    if symbol.fqn.as_deref() == Some(fqn) {
                        return Ok(Some(Self::convert_symbol_node(&symbol, entity_id)));
                    }
                }
                Ok(None)
            }
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(graph) => {
                // Try to parse as numeric ID first
                if let Ok(id) = fqn.parse::<i64>() {
                    let snapshot = SnapshotId::current();
                    if let Ok(node) = graph.backend().get_node(snapshot, id) {
                        if node.kind == "Symbol" {
                            if let Ok(symbol_node) = serde_json::from_value::<SymbolNode>(node.data)
                            {
                                return Ok(Some(Self::convert_symbol_node(&symbol_node, id)));
                            }
                        }
                    }
                }
                // Otherwise search by FQN
                let symbols = Self::get_all_sqlite_symbols(graph)?;
                for (entity_id, symbol) in symbols {
                    if symbol.fqn.as_deref() == Some(fqn) {
                        return Ok(Some(Self::convert_symbol_node(&symbol, entity_id)));
                    }
                }
                Ok(None)
            }
        }
    }

    /// Find a symbol by its numeric ID
    pub fn find_symbol_by_id(&self, id: u64) -> Option<UnifiedSymbolInfo> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => backend
                .find_symbol_by_id_info(id)
                .map(|info| Self::convert_geometric_symbol(&info)),
            MagellanBackend::SQLite(graph) => {
                let snapshot = SnapshotId::current();
                graph
                    .backend()
                    .get_node(snapshot, id as i64)
                    .ok()
                    .and_then(|node| {
                        if node.kind == "Symbol" {
                            serde_json::from_value::<SymbolNode>(node.data)
                                .ok()
                                .map(|symbol| Self::convert_symbol_node(&symbol, id as i64))
                        } else {
                            None
                        }
                    })
            }
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(graph) => {
                let snapshot = SnapshotId::current();
                graph
                    .backend()
                    .get_node(snapshot, id as i64)
                    .ok()
                    .and_then(|node| {
                        if node.kind == "Symbol" {
                            serde_json::from_value::<SymbolNode>(node.data)
                                .ok()
                                .map(|symbol| Self::convert_symbol_node(&symbol, id as i64))
                        } else {
                            None
                        }
                    })
            }
        }
    }

    /// Find symbols by name (simple name, not FQN)
    pub fn find_symbols_by_name(&self, name: &str) -> Result<Vec<UnifiedSymbolInfo>> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => {
                let symbols = backend.find_symbols_by_name_info(name);
                let results: Vec<UnifiedSymbolInfo> = symbols
                    .into_iter()
                    .map(|info| Self::convert_geometric_symbol(&info))
                    .collect();
                Ok(results)
            }
            MagellanBackend::SQLite(graph) => {
                let symbols = Self::get_all_sqlite_symbols(graph)?;
                let results: Vec<UnifiedSymbolInfo> = symbols
                    .into_iter()
                    .filter(|(_, symbol)| symbol.name.as_deref() == Some(name))
                    .map(|(entity_id, symbol)| Self::convert_symbol_node(&symbol, entity_id))
                    .collect();
                Ok(results)
            }
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(graph) => {
                let symbols = Self::get_all_sqlite_symbols(graph)?;
                let results: Vec<UnifiedSymbolInfo> = symbols
                    .into_iter()
                    .filter(|(_, symbol)| symbol.name.as_deref() == Some(name))
                    .map(|(entity_id, symbol)| Self::convert_symbol_node(&symbol, entity_id))
                    .collect();
                Ok(results)
            }
        }
    }

    /// Get database statistics
    pub fn get_stats(&self) -> Result<BackendStats> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => {
                let stats = backend.get_stats()?;
                Ok(BackendStats {
                    node_count: stats.node_count,
                    symbol_count: stats.symbol_count,
                    file_count: stats.file_count,
                    cfg_block_count: stats.cfg_block_count,
                })
            }
            MagellanBackend::SQLite(graph) => {
                let symbol_count = graph.count_symbols().unwrap_or(0);
                let file_count = graph.count_files().unwrap_or(0);
                let cfg_block_count = 0;
                Ok(BackendStats {
                    node_count: symbol_count,
                    symbol_count,
                    file_count,
                    cfg_block_count,
                })
            }
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(graph) => {
                let symbol_count = graph.count_symbols().unwrap_or(0);
                let file_count = graph.count_files().unwrap_or(0);
                let cfg_block_count = 0;
                Ok(BackendStats {
                    node_count: symbol_count,
                    symbol_count,
                    file_count,
                    cfg_block_count,
                })
            }
        }
    }

    /// Convert geometric symbol info to unified format
    #[cfg(feature = "geometric-backend")]
    fn convert_geometric_symbol(info: &GeometricSymbolInfo) -> UnifiedSymbolInfo {
        use crate::ingest::Language;
        let language_str = Some(info.language.as_str().to_string());
        UnifiedSymbolInfo {
            id: info.id,
            name: info.name.clone(),
            fqn: info.fqn.clone(),
            kind: info.kind.clone(),
            file_path: info.file_path.clone(),
            byte_start: info.byte_start,
            byte_end: info.byte_end,
            start_line: info.start_line as u64,
            start_col: info.start_col as u64,
            end_line: info.end_line as u64,
            end_col: info.end_col as u64,
            language: language_str,
        }
    }

    /// Convert SymbolNode to unified format
    fn convert_symbol_node(node: &SymbolNode, entity_id: i64) -> UnifiedSymbolInfo {
        UnifiedSymbolInfo {
            id: entity_id as u64,
            name: node.name.clone().unwrap_or_default(),
            fqn: node.fqn.clone().unwrap_or_default(),
            kind: SymbolKind::from_str(&node.kind).unwrap_or(SymbolKind::Unknown),
            file_path: String::new(), // Will be populated from node data if available
            byte_start: node.byte_start as u64,
            byte_end: node.byte_end as u64,
            start_line: node.start_line as u64,
            start_col: node.start_col as u64,
            end_line: node.end_line as u64,
            end_col: node.end_col as u64,
            language: None,
        }
    }

    /// Helper to get all symbols from SQLite backend
    fn get_all_sqlite_symbols(graph: &CodeGraph) -> Result<Vec<(i64, SymbolNode)>> {
        let backend = graph.backend();
        let entity_ids = backend.entity_ids()?;
        let snapshot = SnapshotId::current();
        let mut symbols = Vec::new();

        for entity_id in entity_ids {
            if let Ok(node) = backend.get_node(snapshot, entity_id) {
                if node.kind == "Symbol" {
                    if let Ok(symbol_node) = serde_json::from_value::<SymbolNode>(node.data) {
                        symbols.push((entity_id, symbol_node));
                    }
                }
            }
        }

        Ok(symbols)
    }

    /// Export database to JSON format
    pub fn export_json(&self) -> Result<String> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => backend.export_json(),
            MagellanBackend::SQLite(_graph) => Err(anyhow::anyhow!(
                "export_json not implemented for SQLite backend"
            )),
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(_graph) => Err(anyhow::anyhow!(
                "export_json not implemented for SQLite backend"
            )),
        }
    }

    /// Export database to JSON Lines format
    pub fn export_jsonl(&self) -> Result<String> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => backend.export_jsonl(),
            MagellanBackend::SQLite(_graph) => Err(anyhow::anyhow!(
                "export_jsonl not implemented for SQLite backend"
            )),
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(_graph) => Err(anyhow::anyhow!(
                "export_jsonl not implemented for SQLite backend"
            )),
        }
    }

    /// Export database to CSV format
    pub fn export_csv(&self) -> Result<String> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => backend.export_csv(),
            MagellanBackend::SQLite(_graph) => Err(anyhow::anyhow!(
                "export_csv not implemented for SQLite backend"
            )),
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(_graph) => Err(anyhow::anyhow!(
                "export_csv not implemented for SQLite backend"
            )),
        }
    }

    /// Get symbols in a specific file
    pub fn symbols_in_file(&self, file_path: &str) -> Result<Vec<UnifiedSymbolInfo>> {
        #[cfg(feature = "geometric-backend")]
        match self {
            MagellanBackend::Geometric(backend) => {
                let symbols = backend.symbols_in_file(file_path)?;
                Ok(symbols
                    .into_iter()
                    .map(|info| Self::convert_geometric_symbol(&info))
                    .collect())
            }
            MagellanBackend::SQLite(_graph) => {
                let _ = file_path;
                Ok(Vec::new())
            }
        }
        #[cfg(not(feature = "geometric-backend"))]
        match self {
            MagellanBackend::SQLite(_graph) => {
                let _ = file_path;
                Ok(Vec::new())
            }
        }
    }

    /// Get code chunks for a file
    pub fn get_code_chunks(
        &self,
        file_path: &str,
    ) -> Result<Vec<crate::generation::schema::CodeChunk>> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.get_code_chunks(file_path),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => _graph.get_code_chunks(file_path),
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(graph) => graph.get_code_chunks(file_path),
        }
    }

    /// Get code chunks for a specific symbol in a file
    pub fn get_code_chunks_for_symbol(
        &self,
        file_path: &str,
        symbol_name: &str,
    ) -> Result<Vec<crate::generation::schema::CodeChunk>> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => {
                backend.get_code_chunks_for_symbol(file_path, symbol_name)
            }
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                _graph.get_code_chunks_for_symbol(file_path, symbol_name)
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(graph) => {
                graph.get_code_chunks_for_symbol(file_path, symbol_name)
            }
        }
    }

    /// Get a code chunk by exact byte span
    pub fn get_code_chunk_by_span(
        &self,
        file_path: &str,
        byte_start: usize,
        byte_end: usize,
    ) -> Result<Option<crate::generation::schema::CodeChunk>> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => {
                backend.get_code_chunk_by_span(file_path, byte_start, byte_end)
            }
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                _graph.get_code_chunk_by_span(file_path, byte_start, byte_end)
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(graph) => {
                graph.get_code_chunk_by_span(file_path, byte_start, byte_end)
            }
        }
    }

    /// Start an execution log entry
    pub fn start_execution(
        &self,
        execution_id: &str,
        tool_version: &str,
        args: &[String],
        root: Option<&str>,
        db_path: &str,
    ) -> Result<()> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => {
                backend.start_execution(execution_id, tool_version, args, root, db_path)
            }
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(graph) => {
                graph.execution_log().start_execution(
                    execution_id,
                    tool_version,
                    args,
                    root,
                    db_path,
                )?;
                Ok(())
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(graph) => {
                graph.execution_log().start_execution(
                    execution_id,
                    tool_version,
                    args,
                    root,
                    db_path,
                )?;
                Ok(())
            }
        }
    }

    /// Finish an execution log entry
    pub fn finish_execution(
        &self,
        execution_id: &str,
        outcome: &str,
        error_message: Option<&str>,
        files_indexed: i64,
        symbols_indexed: i64,
        references_indexed: i64,
    ) -> Result<()> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.finish_execution(
                execution_id,
                outcome,
                error_message,
                files_indexed,
                symbols_indexed,
                references_indexed,
            ),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(graph) => {
                graph.execution_log().finish_execution(
                    execution_id,
                    outcome,
                    error_message,
                    files_indexed as usize,
                    symbols_indexed as usize,
                    references_indexed as usize,
                )?;
                Ok(())
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(graph) => {
                graph.execution_log().finish_execution(
                    execution_id,
                    outcome,
                    error_message,
                    files_indexed as usize,
                    symbols_indexed as usize,
                    references_indexed as usize,
                )?;
                Ok(())
            }
        }
    }

    /// Get outgoing calls (callees) for a symbol by name and path
    ///
    /// Returns CallFact structs with full metadata for all calls from the symbol
    pub fn calls_from_symbol(
        &self,
        path: &str,
        name: &str,
    ) -> Result<Vec<crate::references::CallFact>> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => {
                Ok(backend.calls_from_symbol_as_facts(path, name))
            }
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                // SQLite requires mutable access - for now, return empty

                let _ = (path, name); // Explicitly mark as used for API compatibility
                Ok(Vec::new())
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => {
                let _ = (path, name); // Explicitly mark as used for API compatibility
                Ok(Vec::new())
            }
        }
    }

    /// Get incoming calls (callers) for a symbol by name and path
    ///
    /// Returns CallFact structs with full metadata for all calls to the symbol
    pub fn callers_of_symbol(
        &self,
        path: &str,
        name: &str,
    ) -> Result<Vec<crate::references::CallFact>> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => {
                Ok(backend.callers_of_symbol_as_facts(path, name))
            }
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                // SQLite requires mutable access - for now, return empty

                let _ = (path, name); // Explicitly mark as used for API compatibility
                Ok(Vec::new())
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => {
                let _ = (path, name); // Explicitly mark as used for API compatibility
                Ok(Vec::new())
            }
        }
    }

    /// Find symbol ID by name and file path
    ///
    /// This is used by the refs command to resolve a symbol name + path to a symbol ID
    pub fn find_symbol_id_by_name_and_path(&self, path: &str, name: &str) -> Option<u64> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => {
                backend.find_symbol_id_by_name_and_path(name, path)
            }
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                let _ = (path, name);
                None
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => {
                let _ = (path, name);
                None
            }
        }
    }

    /// Forward reachability from a symbol
    ///
    /// Returns all symbol IDs reachable from the given start symbol via call edges.
    pub fn reachable_from(&self, start_id: u64) -> Vec<u64> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.reachable_from(start_id),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                let _ = start_id;
                Vec::new()
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => {
                let _ = start_id;
                Vec::new()
            }
        }
    }

    /// Reverse reachability from a symbol
    ///
    /// Returns all symbol IDs that can reach the given start symbol via call edges.
    pub fn reverse_reachable_from(&self, start_id: u64) -> Vec<u64> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.reverse_reachable_from(start_id),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                let _ = start_id;
                Vec::new()
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => {
                let _ = start_id;
                Vec::new()
            }
        }
    }

    /// Find dead code from entry points
    ///
    /// Returns all symbol IDs not reachable from any of the given entry points.
    pub fn dead_code_from_entries(&self, entry_ids: &[u64]) -> Vec<u64> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.dead_code_from_entries(entry_ids),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => {
                let _ = entry_ids;
                Vec::new()
            }
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => {
                let _ = entry_ids;
                Vec::new()
            }
        }
    }

    /// Get all symbol IDs
    pub fn get_all_symbol_ids(&self) -> Vec<u64> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.get_all_symbol_ids(),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => Vec::new(),
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => Vec::new(),
        }
    }

    /// Find cycles (mutually recursive SCCs) in the call graph
    pub fn find_cycles(&self) -> Vec<Vec<u64>> {
        match self {
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::Geometric(backend) => backend.find_call_graph_cycles(),
            #[cfg(feature = "geometric-backend")]
            MagellanBackend::SQLite(_graph) => Vec::new(),
            #[cfg(not(feature = "geometric-backend"))]
            MagellanBackend::SQLite(_graph) => Vec::new(),
        }
    }

    /// Get all strongly connected components
    #[cfg(feature = "geometric-backend")]
    pub fn get_sccs(&self) -> crate::graph::geometric_calls::SccResult {
        match self {
            MagellanBackend::Geometric(backend) => backend.get_strongly_connected_components(),
            MagellanBackend::SQLite(_graph) => {
                let scc = crate::graph::geometric_calls::SccResult {
                    components: Vec::new(),
                    node_to_component: std::collections::HashMap::new(),
                };
                scc
            }
        }
    }

    /// Condense the call graph (collapse SCCs into supernodes)
    #[cfg(feature = "geometric-backend")]
    pub fn condense_graph(&self) -> crate::graph::geometric_calls::CondensationDag {
        match self {
            MagellanBackend::Geometric(backend) => backend.condense_call_graph(),
            MagellanBackend::SQLite(_graph) => {
                let dag = crate::graph::geometric_calls::CondensationDag {
                    supernodes: Vec::new(),
                    node_to_supernode: std::collections::HashMap::new(),
                    edges: Vec::new(),
                };
                dag
            }
        }
    }

    /// Enumerate paths in the call graph
    #[cfg(feature = "geometric-backend")]
    pub fn enumerate_paths(
        &self,
        start_id: u64,
        end_id: Option<u64>,
        max_depth: usize,
        max_paths: usize,
    ) -> crate::graph::geometric_backend::PathEnumerationResult {
        match self {
            MagellanBackend::Geometric(backend) => {
                backend.enumerate_paths(start_id, end_id, max_depth, max_paths)
            }
            MagellanBackend::SQLite(_graph) => {
                crate::graph::geometric_backend::PathEnumerationResult {
                    paths: Vec::new(),
                    total_enumerated: 0,
                    bounded_hit: false,
                }
            }
        }
    }

    /// Backward slice (what affects this symbol)
    pub fn backward_slice(&self, symbol_id: u64) -> Vec<u64> {
        self.reverse_reachable_from(symbol_id)
    }

    /// Forward slice (what this symbol affects)
    pub fn forward_slice(&self, symbol_id: u64) -> Vec<u64> {
        self.reachable_from(symbol_id)
    }
}

/// Statistics for any backend
#[derive(Debug, Clone)]
pub struct BackendStats {
    pub node_count: usize,
    pub symbol_count: usize,
    pub file_count: usize,
    pub cfg_block_count: usize,
}

/// Find a symbol by name across all files (backend-agnostic)
pub fn find_symbol_by_name(db_path: &Path, name: &str) -> Result<Option<UnifiedSymbolInfo>> {
    let backend = MagellanBackend::open(db_path)?;
    backend.find_symbol_by_fqn(name)
}

/// Find symbols in a specific file (backend-agnostic)
pub fn find_symbols_in_file(db_path: &Path, file_path: &str) -> Result<Vec<UnifiedSymbolInfo>> {
    let backend = MagellanBackend::open(db_path)?;
    backend.symbols_in_file(file_path)
}

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

    #[test]
    fn test_backend_detection() {
        // .geo files are detected as Geometric when feature is enabled, otherwise SQLite fallback
        #[cfg(feature = "geometric-backend")]
        assert!(matches!(
            MagellanBackend::detect_type(Path::new("test.geo")),
            BackendType::Geometric
        ));
        #[cfg(not(feature = "geometric-backend"))]
        assert!(matches!(
            MagellanBackend::detect_type(Path::new("test.geo")),
            BackendType::SQLite
        ));
        assert!(matches!(
            MagellanBackend::detect_type(Path::new("test.db")),
            BackendType::SQLite
        ));
        assert!(matches!(
            MagellanBackend::detect_type(Path::new("test.sqlite")),
            BackendType::SQLite
        ));
        assert!(matches!(
            MagellanBackend::detect_type(Path::new("test.db")),
            BackendType::SQLite
        ));
    }
}