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
//! Symbol lookup and query methods for MagellanIntegration.
use crate::error::{Result, SpliceError};
use std::path::Path;
use super::types::*;
use super::MagellanIntegration;
use super::{normalize_lookup_path, parse_symbol_kind};
impl MagellanIntegration {
/// Query symbols in a file, with optional filters and relationship context.
///
/// # Arguments
/// * `file_path` - Path to the file to query
/// * `kind_filter` - Optional symbol kind filter (e.g., "fn", "struct", "class")
/// * `with_callers` - If true, include symbols that call each returned symbol
/// * `with_callees` - If true, include symbols that each returned symbol calls
///
/// # Returns
/// Vector of symbols with their relationships (if requested).
pub fn query_symbols_by_file(
&mut self,
file_path: &Path,
kind_filter: Option<&str>,
with_callers: bool,
with_callees: bool,
) -> Result<Vec<SymbolWithRelations>> {
let path_str = file_path
.to_str()
.ok_or_else(|| SpliceError::Other(format!("Invalid UTF-8 in path: {:?}", file_path)))?;
// Query symbols with optional kind filter
let symbol_facts = if let Some(kind) = kind_filter {
let symbol_kind = parse_symbol_kind(kind);
self.inner
.symbols_in_file_with_kind(path_str, Some(symbol_kind))
} else {
self.inner.symbols_in_file(path_str)
}
.map_err(|e| {
SpliceError::Other(format!(
"Failed to query symbols in file {}: {}",
path_str, e
))
})?;
// Convert to SymbolWithRelations, optionally fetching relationships
let mut results = Vec::new();
for fact in symbol_facts {
// Skip symbols without names (e.g., impl blocks)
let name = match fact.name {
Some(n) => n,
None => continue,
};
let symbol = SymbolInfo {
entity_id: 0, // SymbolFact doesn't include entity_id
name: name.clone(),
file_path: fact.file_path.to_string_lossy().to_string(),
kind: fact.kind_normalized,
byte_start: fact.byte_start,
byte_end: fact.byte_end,
start_line: None,
end_line: None,
};
let (callers, callees) = if with_callers || with_callees {
self.fetch_call_relationships_for_symbol(
path_str,
&name,
with_callers,
with_callees,
)?
} else {
(Vec::new(), Vec::new())
};
results.push(SymbolWithRelations {
symbol,
callers,
callees,
});
}
Ok(results)
}
/// Fetch call relationships for a symbol by name.
fn fetch_call_relationships_for_symbol(
&mut self,
file_path: &str,
symbol_name: &str,
fetch_callers: bool,
fetch_callees: bool,
) -> Result<(Vec<SymbolInfo>, Vec<SymbolInfo>)> {
let mut callers = Vec::new();
let mut callees = Vec::new();
if fetch_callers {
let call_facts = self
.inner
.callers_of_symbol(file_path, symbol_name)
.map_err(|e| SpliceError::Other(format!("Failed to get callers: {}", e)))?;
for fact in call_facts {
// Resolve caller name to SymbolInfo
// CallFact contains the caller's file_path and name
if let Ok(caller_symbols) = self
.inner
.symbol_extents(&fact.file_path.to_string_lossy(), &fact.caller)
{
for (_id, caller_fact) in caller_symbols {
callers.push(SymbolInfo {
entity_id: _id,
name: caller_fact.name.unwrap_or_else(|| fact.caller.clone()),
file_path: caller_fact.file_path.to_string_lossy().to_string(),
kind: caller_fact.kind_normalized,
byte_start: caller_fact.byte_start,
byte_end: caller_fact.byte_end,
start_line: None,
end_line: None,
});
}
}
}
}
if fetch_callees {
let call_facts = self
.inner
.calls_from_symbol(file_path, symbol_name)
.map_err(|e| SpliceError::Other(format!("Failed to get callees: {}", e)))?;
for fact in call_facts {
// Resolve callee name to SymbolInfo
// CallFact contains the callee's file_path and name
if let Ok(callee_symbols) = self
.inner
.symbol_extents(&fact.file_path.to_string_lossy(), &fact.callee)
{
for (_id, callee_fact) in callee_symbols {
callees.push(SymbolInfo {
entity_id: _id,
name: callee_fact.name.unwrap_or_else(|| fact.callee.clone()),
file_path: callee_fact.file_path.to_string_lossy().to_string(),
kind: callee_fact.kind_normalized,
byte_start: callee_fact.byte_start,
byte_end: callee_fact.byte_end,
start_line: None,
end_line: None,
});
}
}
}
}
Ok((callers, callees))
}
/// Find symbol by name across ALL indexed files.
///
/// # Arguments
/// * `name` - Symbol name to search for
/// * `ambiguous` - If true, return all matches. If false, return first match only.
///
/// # Returns
/// Vector of matching symbols (empty if none found).
///
/// # Performance
/// This requires O(N) file queries where N = number of indexed files.
/// Magellan has no global symbol name index.
///
/// Batch 1: Backend-neutral implementation.
pub fn find_symbol_by_name(&mut self, name: &str, ambiguous: bool) -> Result<Vec<SymbolInfo>> {
match self.backend {
IntegrationBackend::Sqlite => self.find_symbol_by_name_sqlite(name, ambiguous),
#[cfg(feature = "geometric")]
IntegrationBackend::Geometric => self.find_symbol_by_name_geometric(name, ambiguous),
}
}
/// SQLite implementation of find_symbol_by_name.
///
/// Uses magellan's `SymbolNavigator` for O(1) resolution, falling back to
/// O(N) file scan if the navigator cannot resolve the name.
fn find_symbol_by_name_sqlite(
&mut self,
name: &str,
ambiguous: bool,
) -> Result<Vec<SymbolInfo>> {
let nav = self.inner.navigator();
if let Ok(resolved) = nav.resolve(name) {
if !resolved.is_empty() {
let results: Vec<SymbolInfo> = resolved
.into_iter()
.map(|si| SymbolInfo {
entity_id: si.id,
name: si.name,
file_path: si.file_path.unwrap_or_default(),
kind: si.kind_normalized.unwrap_or(si.kind),
byte_start: si.byte_start,
byte_end: si.byte_start,
start_line: Some(si.start_line),
end_line: Some(si.end_line),
})
.collect();
if ambiguous {
return Ok(results);
} else {
return Ok(vec![results[0].clone()]);
}
}
}
let mut results = Vec::new();
let file_nodes = self
.inner
.all_file_nodes()
.map_err(|e| SpliceError::Other(format!("Failed to get file nodes: {}", e)))?;
for file_path in file_nodes.keys() {
if let Ok(matches) = self.inner.symbol_extents(file_path, name) {
for (entity_id, fact) in matches {
let symbol = SymbolInfo {
entity_id,
name: fact.name.clone().unwrap_or_default(),
file_path: fact.file_path.to_string_lossy().to_string(),
kind: fact.kind_normalized,
byte_start: fact.byte_start,
byte_end: fact.byte_end,
start_line: Some(fact.start_line),
end_line: Some(fact.end_line),
};
results.push(symbol);
if !ambiguous && !results.is_empty() {
return Ok(results);
}
}
}
}
Ok(results)
}
/// Geometric backend implementation of find_symbol_by_name.
#[cfg(feature = "geometric")]
fn find_symbol_by_name_geometric(
&self,
name: &str,
ambiguous: bool,
) -> Result<Vec<SymbolInfo>> {
if let Some(ref geo) = self.geo_inner {
let matches = geo.find_symbols_by_name_info(name);
let results: Vec<SymbolInfo> = matches
.into_iter()
.map(|info| SymbolInfo {
entity_id: info.id as i64,
name: info.name,
file_path: info.file_path,
kind: format!("{:?}", info.kind),
byte_start: info.byte_start as usize,
byte_end: info.byte_end as usize,
start_line: Some(info.start_line as usize),
end_line: Some(info.end_line as usize),
})
.collect();
if !ambiguous && !results.is_empty() {
Ok(results.into_iter().take(1).collect())
} else {
Ok(results)
}
} else {
Err(SpliceError::Other(
"Geometric backend not initialized".to_string(),
))
}
}
/// Find symbol by file path and name.
///
/// Batch 1: Backend-neutral symbol lookup.
///
/// # Arguments
/// * `file_path` - Path to the file containing the symbol
/// * `name` - Symbol name to search for
///
/// # Returns
/// Some(SymbolInfo) if found, None if not found.
pub fn find_symbol_by_path_and_name(
&mut self,
file_path: &Path,
name: &str,
) -> Result<Option<SymbolInfo>> {
let normalized = normalize_lookup_path(file_path);
match self.backend {
IntegrationBackend::Sqlite => {
let path_str = normalized.to_str().ok_or_else(|| {
SpliceError::Other(format!("Invalid UTF-8 in path: {:?}", normalized))
})?;
let matches = self
.inner
.symbol_extents(path_str, name)
.map_err(|e| SpliceError::Other(format!("Failed to find symbol: {}", e)))?;
if let Some((entity_id, fact)) = matches.first() {
Ok(Some(SymbolInfo {
entity_id: *entity_id,
name: fact.name.clone().unwrap_or_else(|| name.to_string()),
file_path: fact.file_path.to_string_lossy().to_string(),
kind: fact.kind_normalized.clone(),
byte_start: fact.byte_start,
byte_end: fact.byte_end,
start_line: None,
end_line: None,
}))
} else {
Ok(None)
}
}
#[cfg(feature = "geometric")]
IntegrationBackend::Geometric => {
if let Some(ref geo) = self.geo_inner {
let path_str = normalized.to_str().ok_or_else(|| {
SpliceError::Other(format!("Invalid UTF-8 in path: {:?}", normalized))
})?;
// Use geometric backend's method to find symbol by name and path
if let Some(id) = geo.find_symbol_id_by_name_and_path(name, path_str) {
if let Some(info) = geo.find_symbol_by_id_info(id) {
return Ok(Some(SymbolInfo {
entity_id: id as i64,
name: info.name,
file_path: info.file_path,
kind: format!("{:?}", info.kind),
byte_start: info.byte_start as usize,
byte_end: info.byte_end as usize,
start_line: None,
end_line: None,
}));
}
}
Ok(None)
} else {
Err(SpliceError::Other(
"Geometric backend not initialized".to_string(),
))
}
}
}
}
/// Find symbol by 16-char SHA-256 or 32-char BLAKE3 symbol ID.
///
/// # Arguments
/// * `symbol_id` - 16-char (V1 SHA-256) or 32-char (V2 BLAKE3) lowercase hex symbol ID
///
/// # Returns
/// Some(SymbolInfo) if found, None if not found.
///
/// # Performance
/// This requires O(N) entity iteration where N = total symbols.
/// Magellan does not store symbol_id or provide reverse lookup.
/// Consider building a symbol_id index in future if performance is inadequate.
///
/// # Note
/// Symbol IDs are generated as:
/// - V1: SHA-256(name:path:byte_start)[0..8] -> 16 hex chars
/// - V2: BLAKE3(name:path:byte_start)[0..16] -> 32 hex chars
///
/// We regenerate IDs during iteration to find matches, trying V2 first.
pub fn find_symbol_by_id(&mut self, symbol_id: &str) -> Result<Option<SymbolInfo>> {
match self.backend {
IntegrationBackend::Sqlite => self.find_symbol_by_id_sqlite(symbol_id),
#[cfg(feature = "geometric")]
IntegrationBackend::Geometric => self.find_symbol_by_id_geo(symbol_id),
}
}
/// Find symbol by ID (SQLite implementation).
fn find_symbol_by_id_sqlite(&mut self, symbol_id: &str) -> Result<Option<SymbolInfo>> {
use crate::symbol_id::{generate_v1, generate_v2};
use rusqlite::Connection;
let conn = Connection::open(&self.db_path).map_err(|e| {
SpliceError::Other(format!(
"Failed to open database for symbol ID lookup: {}",
e
))
})?;
let mut stmt = conn
.prepare("SELECT id, name, file_path, data FROM graph_entities WHERE kind = 'Symbol'")
.map_err(|e| SpliceError::Other(format!("Failed to prepare query: {}", e)))?;
let symbol_rows = stmt
.query_map([], |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
))
})
.map_err(|e| SpliceError::Other(format!("Failed to query symbols: {}", e)))?;
for row_result in symbol_rows {
let (entity_id, name, file_path, data_json) =
row_result.map_err(|e| SpliceError::Other(format!("Failed to read row: {}", e)))?;
// Parse the JSON data to get byte_start
let data: serde_json::Value = serde_json::from_str(&data_json).map_err(|e| {
SpliceError::Other(format!("Failed to parse symbol data JSON: {}", e))
})?;
let byte_start = data
.get("byte_start")
.and_then(|v| v.as_u64())
.ok_or_else(|| SpliceError::Other("Symbol data missing byte_start".to_string()))?;
let byte_start = byte_start as usize;
// Try V2 (32-char BLAKE3) first, then V1 (16-char SHA-256) for backward compatibility
let generated_v2 = generate_v2(&name, &file_path, byte_start);
if generated_v2.as_str() == symbol_id {
// Found V2 match - extract remaining fields
let byte_end = data
.get("byte_end")
.and_then(|v| v.as_u64())
.ok_or_else(|| {
SpliceError::Other("Symbol data missing byte_end".to_string())
})?;
let byte_end = byte_end as usize;
let kind = data
.get("kind")
.and_then(|v| v.as_str())
.unwrap_or("Unknown")
.to_string();
let start_line = data
.get("start_line")
.and_then(|v| v.as_u64())
.map(|l| l as usize);
let end_line = data
.get("end_line")
.and_then(|v| v.as_u64())
.map(|l| l as usize);
return Ok(Some(SymbolInfo {
entity_id,
name,
file_path,
kind,
byte_start,
byte_end,
start_line,
end_line,
}));
}
// Try V1 (16-char SHA-256) for backward compatibility
let generated_v1 = generate_v1(&name, &file_path, byte_start);
if generated_v1.as_str() == symbol_id {
// Found V1 match - extract remaining fields
let byte_end = data
.get("byte_end")
.and_then(|v| v.as_u64())
.ok_or_else(|| {
SpliceError::Other("Symbol data missing byte_end".to_string())
})?;
let byte_end = byte_end as usize;
let kind = data
.get("kind")
.and_then(|v| v.as_str())
.unwrap_or("Unknown")
.to_string();
let start_line = data
.get("start_line")
.and_then(|v| v.as_u64())
.map(|l| l as usize);
let end_line = data
.get("end_line")
.and_then(|v| v.as_u64())
.map(|l| l as usize);
return Ok(Some(SymbolInfo {
entity_id,
name,
file_path,
kind,
byte_start,
byte_end,
start_line,
end_line,
}));
}
}
Ok(None)
}
/// Find symbol by ID (Geometric implementation).
#[cfg(feature = "geometric")]
fn find_symbol_by_id_geo(&mut self, symbol_id: &str) -> Result<Option<SymbolInfo>> {
if let Some(ref geo) = self.geo_inner {
// Parse symbol_id as u64 for geometric backend
let id = symbol_id.parse::<u64>().map_err(|_| {
SpliceError::Other(format!(
"Invalid symbol ID for geometric backend: {}. Expected u64.",
symbol_id
))
})?;
if let Some(info) = geo.find_symbol_by_id_info(id) {
Ok(Some(SymbolInfo {
entity_id: info.id as i64,
name: info.name,
file_path: info.file_path,
kind: format!("{:?}", info.kind),
byte_start: info.byte_start as usize,
byte_end: info.byte_end as usize,
start_line: None,
end_line: None,
}))
} else {
Ok(None)
}
} else {
Err(SpliceError::Other(
"Geometric backend not initialized".to_string(),
))
}
}
/// List all indexed files, with optional symbol counts.
///
/// Batch 2: Supports both SQLite and Geometric backends.
pub fn list_indexed_files(&mut self, with_symbol_counts: bool) -> Result<Vec<FileMetadata>> {
match self.backend {
IntegrationBackend::Sqlite => {
let file_nodes = self
.inner
.all_file_nodes()
.map_err(|e| SpliceError::Other(format!("Failed to get file nodes: {}", e)))?;
file_nodes
.into_iter()
.map(|(path, node)| {
let symbol_count = if with_symbol_counts {
Some(self.count_symbols_in_file(&path)?)
} else {
None
};
Ok(FileMetadata {
path,
hash: node.hash,
last_indexed_at: node.last_indexed_at,
last_modified: node.last_modified,
symbol_count,
})
})
.collect()
}
#[cfg(feature = "geometric")]
IntegrationBackend::Geometric => {
if let Some(ref geo) = self.geo_inner {
let files = geo.get_all_files();
files
.into_iter()
.map(|(path, hash, last_indexed)| {
let symbol_count = if with_symbol_counts {
let symbols = geo.symbols_in_file(&path).map_err(|e| {
SpliceError::Other(format!(
"Failed to count symbols in {}: {}",
path, e
))
})?;
Some(symbols.len())
} else {
None
};
Ok(FileMetadata {
path,
hash: hash.unwrap_or_default(),
last_indexed_at: last_indexed,
last_modified: 0, // Not stored in geometric backend
symbol_count,
})
})
.collect()
} else {
Err(SpliceError::Other(
"Geometric backend not initialized".to_string(),
))
}
}
}
}
/// Count symbols for a specific file.
fn count_symbols_in_file(&mut self, path: &str) -> Result<usize> {
match self.backend {
IntegrationBackend::Sqlite => {
let symbols = self.inner.symbols_in_file(path).map_err(|e| {
SpliceError::Other(format!("Failed to count symbols in {}: {}", path, e))
})?;
Ok(symbols.len())
}
#[cfg(feature = "geometric")]
IntegrationBackend::Geometric => {
if let Some(ref geo) = self.geo_inner {
let symbols = geo.symbols_in_file(path).map_err(|e| {
SpliceError::Other(format!("Failed to count symbols in {}: {}", path, e))
})?;
Ok(symbols.len())
} else {
Err(SpliceError::Other(
"Geometric backend not initialized".to_string(),
))
}
}
}
}
}