magellan 3.3.0

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
//! In-memory symbol lookup index for O(1) lookups
//!
//! Provides O(1) lookup by FQN, name, and (file_path, name) pairs without
//! repeated database scans. Index is built on-demand and maintained incrementally.
//!
//! # Thread Safety
//!
//! **This module is NOT thread-safe.**
//!
//! Same constraints as `FileOps`:
//! - All methods require `&self` or `&mut self`
//! - No `Send` or `Sync` impls
//! - Must be accessed through single-threaded `CodeGraph`
//!
//! # Performance
//!
//! - Build time: ~50-100ms for 10k symbols (one-time)
//! - Lookup time: O(1) average case
//! - Memory: ~2MB for 10k symbols
//!
//! # Usage Pattern
//!
//! ```ignore
//! // Build on startup (via CodeGraph::open)
//! lookup.rebuild_from_backend(&backend)?;
//!
//! // O(1) lookup during indexing
//! if let Some(entry) = lookup.get_by_fqn("crate::module::function") {
//!     // Use entry.entity_id
//! }
//!
//! // Get all symbol facts for reference extraction (no O(n) scan)
//! let all_facts = lookup.get_all_symbol_facts();
//!
//! // Incremental updates during indexing
//! lookup.insert(entity_id, file_path, &symbol_fact);
//! lookup.remove(entity_id);
//! ```

use anyhow::Result;
use sqlitegraph::{GraphBackend, SnapshotId};
use std::collections::HashMap;
use std::path::PathBuf;

use crate::ingest::{SymbolFact, SymbolKind};

/// Entry in the symbol lookup index
#[derive(Debug, Clone)]
#[allow(
    dead_code,
    reason = "SymbolEntry data model: fields populated during index build, reserved for future query paths"
)]
pub struct SymbolEntry {
    /// Entity ID in the graph database
    pub entity_id: i64,
    /// File path where symbol is defined
    pub file_path: String,
    /// Simple symbol name
    pub name: Option<String>,
    /// Symbol kind enum
    pub kind: SymbolKind,
    /// Normalized kind string ("fn", "struct", "enum", etc.)
    pub kind_normalized: String,
    /// Fully-qualified name (e.g., "crate::module::function")
    pub fqn: Option<String>,
    /// Canonical FQN (resolved through type aliases)
    pub canonical_fqn: Option<String>,
    /// Display FQN (for user-friendly display)
    pub display_fqn: Option<String>,
    /// Stable symbol ID (SHA-256 hash, used for cross-file reference resolution)
    pub stable_symbol_id: Option<String>,
    /// Byte start position
    pub byte_start: i64,
    /// Byte end position
    pub byte_end: i64,
    /// Start line number (1-indexed)
    pub start_line: usize,
    /// Start column (0-indexed)
    pub start_col: usize,
    /// End line number (1-indexed)
    pub end_line: usize,
    /// End column (0-indexed)
    pub end_col: usize,
}

impl SymbolEntry {
    /// Create a SymbolEntry from a SymbolFact
    pub fn from_fact(entity_id: i64, file_path: &str, fact: &SymbolFact) -> Self {
        Self {
            entity_id,
            file_path: file_path.to_string(),
            name: fact.name.clone(),
            kind: fact.kind.clone(),
            kind_normalized: fact.kind_normalized.clone(),
            fqn: fact.fqn.clone(),
            canonical_fqn: fact.canonical_fqn.clone(),
            display_fqn: fact.display_fqn.clone(),
            stable_symbol_id: None, // Set separately when available
            byte_start: fact.byte_start as i64,
            byte_end: fact.byte_end as i64,
            start_line: fact.start_line,
            start_col: fact.start_col,
            end_line: fact.end_line,
            end_col: fact.end_col,
        }
    }

    /// Create a SymbolEntry from a SymbolFact with a known stable_symbol_id
    pub fn from_fact_with_symbol_id(
        entity_id: i64,
        file_path: &str,
        fact: &SymbolFact,
        stable_symbol_id: String,
    ) -> Self {
        let mut entry = Self::from_fact(entity_id, file_path, fact);
        entry.stable_symbol_id = Some(stable_symbol_id);
        entry
    }

    /// Convert this entry back to a SymbolFact
    pub fn to_symbol_fact(&self) -> SymbolFact {
        SymbolFact {
            file_path: std::path::PathBuf::from(&self.file_path),
            kind: self.kind.clone(),
            kind_normalized: self.kind_normalized.clone(),
            name: self.name.clone(),
            fqn: self.fqn.clone(),
            canonical_fqn: self.canonical_fqn.clone(),
            display_fqn: self.display_fqn.clone(),
            byte_start: self.byte_start as usize,
            byte_end: self.byte_end as usize,
            start_line: self.start_line,
            start_col: self.start_col,
            end_line: self.end_line,
            end_col: self.end_col,
        }
    }
}

/// In-memory symbol lookup index
///
/// Provides O(1) lookups for:
/// - FQN -> SymbolEntry (primary resolution)
/// - Simple name -> Vec<entity_id> (fallback matching)
/// - entity_id -> stable_symbol_id (for reference resolution)
pub struct SymbolLookup {
    /// FQN -> SymbolEntry
    /// Used for primary symbol resolution
    /// Key is FQN if present, otherwise simple name
    fqn_index: HashMap<String, SymbolEntry>,

    /// Simple name -> [entity_id]
    /// Used for fallback matching when FQN doesn't match exactly
    /// E.g., "render" -> [id1, id2] for Widget::render and Page::render
    name_index: HashMap<String, Vec<i64>>,

    /// entity_id -> FQN key
    /// Used for reverse lookup during removal
    id_to_fqn: HashMap<i64, String>,

    /// entity_id -> stable_symbol_id (SHA-256 hash)
    /// Used for cross-file reference resolution
    id_to_symbol_id: HashMap<i64, String>,

    /// Total symbols in index
    count: usize,
}

impl SymbolLookup {
    /// Create empty SymbolLookup
    pub fn new() -> Self {
        Self {
            fqn_index: HashMap::new(),
            name_index: HashMap::new(),
            id_to_fqn: HashMap::new(),
            id_to_symbol_id: HashMap::new(),
            count: 0,
        }
    }

    /// Get number of symbols in index
    #[allow(dead_code, reason = "used in module tests")]
    pub fn len(&self) -> usize {
        self.count
    }

    /// Check if index is empty
    #[allow(dead_code, reason = "used in module tests")]
    pub fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Clear all entries from the index
    pub fn clear(&mut self) {
        self.fqn_index.clear();
        self.name_index.clear();
        self.id_to_fqn.clear();
        self.id_to_symbol_id.clear();
        self.count = 0;
    }

    /// Insert a symbol into the index
    ///
    /// # Arguments
    /// * `entity_id` - Graph database entity ID
    /// * `file_path` - File path where symbol is defined
    /// * `fact` - Symbol fact from parser
    pub fn insert(&mut self, entity_id: i64, file_path: &str, fact: &SymbolFact) {
        // Build the key: prefer FQN, fall back to name
        let key = fact
            .fqn
            .as_ref()
            .or(fact.name.as_ref())
            .cloned()
            .unwrap_or_default();

        if key.is_empty() {
            return;
        }

        let entry = SymbolEntry::from_fact(entity_id, file_path, fact);

        // Update FQN index
        self.fqn_index.insert(key.clone(), entry);

        // Update name index (for fallback matching)
        if let Some(ref name) = fact.name {
            self.name_index
                .entry(name.clone())
                .or_default()
                .push(entity_id);
        }

        // Update reverse lookup
        self.id_to_fqn.insert(entity_id, key);

        self.count += 1;
    }

    /// Insert a symbol with a known stable_symbol_id
    ///
    /// Use this when the stable_symbol_id is already computed (e.g., during rebuild_from_backend)
    pub fn insert_with_symbol_id(
        &mut self,
        entity_id: i64,
        file_path: &str,
        fact: &SymbolFact,
        stable_symbol_id: String,
    ) {
        // Build the key: prefer FQN, fall back to name
        let key = fact
            .fqn
            .as_ref()
            .or(fact.name.as_ref())
            .cloned()
            .unwrap_or_default();

        if key.is_empty() {
            return;
        }

        let entry = SymbolEntry::from_fact_with_symbol_id(
            entity_id,
            file_path,
            fact,
            stable_symbol_id.clone(),
        );

        // Update FQN index
        self.fqn_index.insert(key.clone(), entry);

        // Update name index (for fallback matching)
        if let Some(ref name) = fact.name {
            self.name_index
                .entry(name.clone())
                .or_default()
                .push(entity_id);
        }

        // Update reverse lookup
        self.id_to_fqn.insert(entity_id, key);

        // Track stable symbol_id for cross-file reference resolution
        self.id_to_symbol_id.insert(entity_id, stable_symbol_id);

        self.count += 1;
    }

    /// Remove a symbol from the index by entity_id
    ///
    /// # Arguments
    /// * `entity_id` - Graph database entity ID to remove
    pub fn remove(&mut self, entity_id: i64) {
        // Also remove stable_symbol_id mapping
        self.id_to_symbol_id.remove(&entity_id);

        // Get the FQN key for this entity
        if let Some(key) = self.id_to_fqn.remove(&entity_id) {
            // Get the entry to find the name
            if let Some(entry) = self.fqn_index.get(&key) {
                // Remove from name index
                if let Some(ref name) = entry.name {
                    if let Some(ids) = self.name_index.get_mut(name) {
                        ids.retain(|&id| id != entity_id);
                        if ids.is_empty() {
                            self.name_index.remove(name);
                        }
                    }
                }
            }

            // Remove from FQN index
            self.fqn_index.remove(&key);
            self.count = self.count.saturating_sub(1);
        }
    }

    /// Look up a symbol by FQN
    ///
    /// # Returns
    /// Reference to SymbolEntry if found, None if not in index
    #[allow(dead_code, reason = "used in module tests")]
    pub fn get_by_fqn(&self, fqn: &str) -> Option<&SymbolEntry> {
        self.fqn_index.get(fqn)
    }

    /// Look up entity IDs by simple name (for fallback matching)
    ///
    /// # Returns
    /// Slice of entity_ids matching this name, empty if none found
    #[allow(dead_code, reason = "used in module tests")]
    pub fn get_ids_by_name(&self, name: &str) -> &[i64] {
        self.name_index
            .get(name)
            .map(|v| v.as_slice())
            .unwrap_or(&[])
    }

    /// Build FQN -> entity_id map with current file preference
    ///
    /// This replicates the logic from `src/graph/calls.rs:index_calls`:
    /// - Current file symbols take precedence for duplicate FQNs
    /// - Returns HashMap suitable for passing to CallOps::index_calls
    pub fn fqn_to_id_with_current_file(&self, current_file: &str) -> HashMap<String, (i64, bool)> {
        let mut result: HashMap<String, (i64, bool)> = HashMap::new();

        for (fqn, entry) in &self.fqn_index {
            let is_current_file = entry.file_path == current_file;

            // Prefer current file symbols for duplicates
            match result.get(fqn) {
                Some((_, existing_is_current)) if *existing_is_current || !is_current_file => {}
                _ => {
                    result.insert(fqn.clone(), (entry.entity_id, is_current_file));
                }
            }
        }

        result
    }

    /// Return all symbol facts from the in-memory index.
    ///
    /// This is O(N) where N = number of symbols (not all entities).
    /// Use this instead of scanning the database to build symbol facts for reference extraction.
    pub fn all_symbol_facts(&self) -> Vec<SymbolFact> {
        self.fqn_index
            .values()
            .map(|e| e.to_symbol_fact())
            .collect()
    }

    /// Build symbol_id -> entity_id map from the in-memory index.
    ///
    /// This replaces the O(N) database scan in index_references.
    pub fn symbol_id_to_id(&self) -> HashMap<String, i64> {
        let mut result = HashMap::with_capacity(self.id_to_symbol_id.len());
        for (entity_id, symbol_id) in &self.id_to_symbol_id {
            result.insert(symbol_id.clone(), *entity_id);
        }
        result
    }

    /// Build display_fqn -> [entity_id] groups from the in-memory index.
    ///
    /// This replaces the O(N) database scan for ambiguity grouping.
    pub fn display_fqn_groups(&self) -> HashMap<String, Vec<i64>> {
        let mut result: HashMap<String, Vec<i64>> = HashMap::new();
        for entry in self.fqn_index.values() {
            if let Some(ref display_fqn) = entry.display_fqn {
                if !display_fqn.is_empty() {
                    result
                        .entry(display_fqn.clone())
                        .or_default()
                        .push(entry.entity_id);
                }
            }
        }
        result
    }

    /// Build FQN -> entity_id map from the in-memory index.
    ///
    /// This replaces the O(N) database scan for FQN-based symbol resolution.
    pub fn fqn_to_id(&self) -> HashMap<String, i64> {
        let mut result = HashMap::with_capacity(self.fqn_index.len());
        for (fqn, entry) in &self.fqn_index {
            result.insert(fqn.clone(), entry.entity_id);
        }
        result
    }

    /// Return the entity_id -> stable_symbol_id map.
    pub fn entity_to_symbol_id(&self) -> &HashMap<i64, String> {
        &self.id_to_symbol_id
    }

    /// Rebuild index from backend database
    ///
    /// Scans all Symbol nodes and rebuilds all indexes.
    /// Call this on CodeGraph::open() or after bulk changes.
    ///
    /// # Arguments
    /// * `backend` - Graph backend to scan
    ///
    /// # Returns
    /// Number of symbols indexed
    pub fn rebuild_from_backend(&mut self, backend: &dyn GraphBackend) -> Result<usize> {
        self.clear();

        let entity_ids = backend.entity_ids()?;
        let snapshot = SnapshotId::current();

        for entity_id in entity_ids {
            if let Ok(node) = backend.get_node(snapshot, entity_id) {
                if node.kind != "Symbol" {
                    continue;
                }

                // Extract file path
                let file_path = node.file_path.clone().unwrap_or_default();

                // Parse SymbolNode from JSON data
                if let Ok(symbol_node) =
                    serde_json::from_value::<crate::graph::schema::SymbolNode>(node.data.clone())
                {
                    // Convert SymbolNode to SymbolFact for insertion
                    let fact = SymbolFact {
                        file_path: std::path::PathBuf::from(&file_path),
                        kind: match symbol_node.kind_normalized.as_deref() {
                            Some("fn") => crate::ingest::SymbolKind::Function,
                            Some("method") => crate::ingest::SymbolKind::Method,
                            Some("struct") => crate::ingest::SymbolKind::Class,
                            Some("enum") => crate::ingest::SymbolKind::Enum,
                            Some("trait") => crate::ingest::SymbolKind::Interface,
                            Some("mod") => crate::ingest::SymbolKind::Module,
                            _ => crate::ingest::SymbolKind::Unknown,
                        },
                        kind_normalized: symbol_node
                            .kind_normalized
                            .clone()
                            .unwrap_or_else(|| symbol_node.kind.clone()),
                        name: symbol_node.name,
                        fqn: symbol_node.fqn,
                        canonical_fqn: symbol_node.canonical_fqn,
                        display_fqn: symbol_node.display_fqn,
                        byte_start: symbol_node.byte_start,
                        byte_end: symbol_node.byte_end,
                        start_line: symbol_node.start_line,
                        start_col: symbol_node.start_col,
                        end_line: symbol_node.end_line,
                        end_col: symbol_node.end_col,
                    };

                    // Extract stable symbol_id if present, use insert_with_symbol_id
                    if let Some(stable_symbol_id) = symbol_node.symbol_id {
                        self.insert_with_symbol_id(entity_id, &file_path, &fact, stable_symbol_id);
                    } else {
                        self.insert(entity_id, &file_path, &fact);
                    }
                }
            }
        }

        Ok(self.count)
    }
}

impl Default for SymbolLookup {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ingest::SymbolKind;
    use std::path::PathBuf;

    fn make_fact(name: &str, fqn: &str) -> SymbolFact {
        SymbolFact {
            file_path: PathBuf::from("test.rs"),
            kind: SymbolKind::Function,
            kind_normalized: "fn".to_string(),
            name: Some(name.to_string()),
            fqn: Some(fqn.to_string()),
            canonical_fqn: None,
            display_fqn: None,
            byte_start: 0,
            byte_end: 10,
            start_line: 1,
            start_col: 0,
            end_line: 1,
            end_col: 10,
        }
    }

    #[test]
    fn test_insert_and_lookup() {
        let mut lookup = SymbolLookup::new();
        let fact = make_fact("main", "crate::main");
        lookup.insert(1, "test.rs", &fact);

        assert_eq!(lookup.len(), 1);
        assert!(lookup.get_by_fqn("crate::main").is_some());
        assert_eq!(lookup.get_by_fqn("crate::main").unwrap().entity_id, 1);
    }

    #[test]
    fn test_remove() {
        let mut lookup = SymbolLookup::new();
        let fact = make_fact("main", "crate::main");
        lookup.insert(1, "test.rs", &fact);
        assert_eq!(lookup.len(), 1);

        lookup.remove(1);
        assert_eq!(lookup.len(), 0);
        assert!(lookup.get_by_fqn("crate::main").is_none());
    }

    #[test]
    fn test_name_index() {
        let mut lookup = SymbolLookup::new();

        // Insert two symbols with same name but different FQNs
        let fact1 = make_fact("render", "Widget::render");
        let fact2 = make_fact("render", "Page::render");
        lookup.insert(1, "widget.rs", &fact1);
        lookup.insert(2, "page.rs", &fact2);

        // Should find both by name
        let ids = lookup.get_ids_by_name("render");
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&1));
        assert!(ids.contains(&2));
    }

    #[test]
    fn test_fqn_to_id_with_current_file() {
        let mut lookup = SymbolLookup::new();

        // Insert symbols with DIFFERENT FQNs (realistic scenario)
        let fact1 = make_fact("func", "crate::module::func");
        lookup.insert(1, "src/module.rs", &fact1);

        let fact2 = make_fact("helper", "crate::other::helper");
        lookup.insert(2, "src/other.rs", &fact2);

        // When called with current file, both symbols should be in the map
        let map = lookup.fqn_to_id_with_current_file("src/module.rs");

        // Current file symbol should have is_current_file = true
        assert_eq!(map.get("crate::module::func"), Some(&(1, true)));

        // Other file symbol should have is_current_file = false
        assert_eq!(map.get("crate::other::helper"), Some(&(2, false)));
    }

    #[test]
    fn test_clear() {
        let mut lookup = SymbolLookup::new();
        let fact = make_fact("main", "crate::main");
        lookup.insert(1, "test.rs", &fact);

        lookup.clear();
        assert!(lookup.is_empty());
        assert!(lookup.fqn_index.is_empty());
        assert!(lookup.name_index.is_empty());
    }
}