magellan 3.1.9

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
use base64::Engine;

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::graph::CodeGraph;

/// Project-level summary (~50 tokens)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectSummary {
    /// Project name (from Cargo.toml or directory)
    pub name: String,
    /// Project version
    pub version: String,
    /// Primary language
    pub language: String,
    /// Total files indexed
    pub total_files: usize,
    /// Total symbols indexed
    pub total_symbols: usize,
    /// Symbol breakdown by kind
    pub symbol_counts: SymbolCounts,
    /// Entry points (main functions, etc.)
    pub entry_points: Vec<String>,
    /// Brief description
    pub description: String,
}

/// Symbol counts by kind
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SymbolCounts {
    pub functions: usize,
    pub methods: usize,
    pub structs: usize,
    pub traits: usize,
    pub enums: usize,
    pub modules: usize,
    pub other: usize,
}

/// File-level context (~100 tokens)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileContext {
    /// File path
    pub path: String,
    /// Language
    pub language: String,
    /// Total symbols in file
    pub symbol_count: usize,
    /// Public symbols
    pub public_symbols: Vec<String>,
    /// Symbol breakdown
    pub symbol_counts: SymbolCounts,
    /// Dependencies (imports)
    pub imports: Vec<String>,
}

/// Symbol detail (~150-500 tokens)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolDetail {
    /// Symbol name
    pub name: String,
    /// Symbol kind (fn, struct, etc.)
    pub kind: String,
    /// File containing this symbol
    pub file: String,
    /// Line number
    pub line: usize,
    /// Signature (if available)
    pub signature: Option<String>,
    /// Documentation (if available)
    pub documentation: Option<String>,
    /// Caller symbols
    pub callers: Vec<String>,
    /// Callee symbols
    pub callees: Vec<String>,
    /// Related symbols (same module, etc.)
    pub related: Vec<String>,
}

/// Paginated result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginatedResult<T> {
    /// Current page (1-indexed)
    pub page: usize,
    /// Total pages available
    pub total_pages: usize,
    /// Items per page
    pub page_size: usize,
    /// Total items across all pages
    pub total_items: usize,
    /// Cursor for next page (base64 encoded)
    pub next_cursor: Option<String>,
    /// Cursor for previous page
    pub prev_cursor: Option<String>,
    /// Items on this page
    pub items: Vec<T>,
}

impl<T> PaginatedResult<T> {
    /// Create a new paginated result
    pub fn new(items: Vec<T>, page: usize, page_size: usize, total_items: usize) -> Self {
        let total_pages = total_items.div_ceil(page_size);
        let next_cursor = if page < total_pages {
            Some(base64::engine::general_purpose::STANDARD.encode(format!("page={}", page + 1)))
        } else {
            None
        };
        let prev_cursor = if page > 1 {
            Some(base64::engine::general_purpose::STANDARD.encode(format!("page={}", page - 1)))
        } else {
            None
        };

        // Slice items to only return the requested page
        let start_idx = (page.saturating_sub(1)) * page_size;
        let end_idx = (start_idx + page_size).min(items.len());
        let paged_items = if start_idx < items.len() {
            items
                .into_iter()
                .skip(start_idx)
                .take(end_idx - start_idx)
                .collect()
        } else {
            Vec::new()
        };

        Self {
            page,
            total_pages,
            page_size,
            total_items,
            next_cursor,
            prev_cursor,
            items: paged_items,
        }
    }

    /// Create empty result
    pub fn empty(page: usize, page_size: usize) -> Self {
        Self::new(Vec::new(), page, page_size, 0)
    }
}

/// Query for listing symbols
#[derive(Debug, Clone, Deserialize)]
pub struct ListQuery {
    /// Filter by symbol kind (fn, struct, etc.)
    pub kind: Option<String>,
    /// Filter by file path pattern
    pub file_pattern: Option<String>,
    /// Page number (1-indexed)
    pub page: Option<usize>,
    /// Page size (default: 50)
    pub page_size: Option<usize>,
    /// Cursor for pagination (overrides page)
    pub cursor: Option<String>,
}

impl Default for ListQuery {
    fn default() -> Self {
        Self {
            kind: None,
            file_pattern: None,
            page: Some(1),
            page_size: Some(50),
            cursor: None,
        }
    }
}

/// Get project summary
pub fn get_project_summary(graph: &mut CodeGraph) -> Result<ProjectSummary> {
    let total_files = graph.count_files()?;
    let total_symbols = graph.count_symbols()?;

    // Get symbol counts by label
    let mut counts = SymbolCounts::default();

    for label in &["fn", "method", "struct", "trait", "enum", "mod"] {
        let symbols = graph.get_symbols_by_label(label)?;
        let count = symbols.len();

        match *label {
            "fn" => counts.functions = count,
            "method" => counts.methods = count,
            "struct" => counts.structs = count,
            "trait" => counts.traits = count,
            "enum" => counts.enums = count,
            "mod" => counts.modules = count,
            _ => counts.other += count,
        }
    }

    // Detect project info from Cargo.toml if available
    let (name, version) = detect_project_info()?;

    // Detect primary language
    let language = detect_primary_language(graph)?;

    // Find entry points
    let entry_points = find_entry_points(graph)?;

    // Generate description
    let description = format!(
        "{} {} written in {}, {} files, {} symbols ({} functions, {} structs)",
        name, version, language, total_files, total_symbols, counts.functions, counts.structs
    );

    Ok(ProjectSummary {
        name,
        version,
        language,
        total_files,
        total_symbols,
        symbol_counts: counts,
        entry_points,
        description,
    })
}

/// Get file context
pub fn get_file_context(graph: &mut CodeGraph, file_path: &str) -> Result<FileContext> {
    let symbols = graph.symbols_in_file(file_path)?;

    let mut counts = SymbolCounts::default();
    let mut public_symbols = Vec::new();

    for symbol in &symbols {
        let kind = symbol.kind_normalized.as_str();

        match kind {
            "fn" => counts.functions += 1,
            "method" => counts.methods += 1,
            "struct" => counts.structs += 1,
            "trait" => counts.traits += 1,
            "enum" => counts.enums += 1,
            "mod" => counts.modules += 1,
            _ => counts.other += 1,
        }

        // Check if symbol is public (simple heuristic: not starting with _)
        if let Some(ref name) = symbol.name {
            if !name.starts_with('_') {
                public_symbols.push(format!("{}:{}", kind, name));
            }
        }
    }

    // Detect language
    let language = crate::common::detect_language_from_path(file_path);

    // Imports not yet implemented - would require additional graph queries
    let imports = Vec::new();

    Ok(FileContext {
        path: file_path.to_string(),
        language,
        symbol_count: symbols.len(),
        public_symbols,
        symbol_counts: counts,
        imports,
    })
}

/// Get symbol detail
pub fn get_symbol_detail(
    graph: &mut CodeGraph,
    symbol_name: &str,
    file_path: Option<&str>,
) -> Result<SymbolDetail> {
    // Find the symbol
    let symbols = if let Some(file) = file_path {
        graph
            .symbols_in_file(file)?
            .into_iter()
            .filter(|s| s.name.as_deref() == Some(symbol_name))
            .collect::<Vec<_>>()
    } else {
        // Search across all files
        let results = graph.get_symbols_by_label(symbol_name)?;
        results
            .into_iter()
            .filter_map(|r| {
                graph.symbols_in_file(&r.file_path).ok().and_then(|syms| {
                    syms.into_iter()
                        .find(|s| s.name.as_deref() == Some(symbol_name))
                })
            })
            .collect::<Vec<_>>()
    };

    let symbol = symbols
        .first()
        .ok_or_else(|| anyhow::anyhow!("Symbol '{}' not found", symbol_name))?;

    // Get callers
    let callers = graph
        .callers_of_symbol(&symbol.file_path.to_string_lossy(), symbol_name)?
        .iter()
        .map(|c| c.caller.clone())
        .collect();

    // Get callees
    let callees = graph
        .calls_from_symbol(&symbol.file_path.to_string_lossy(), symbol_name)?
        .iter()
        .map(|c| c.callee.clone())
        .collect();

    // Get related symbols (same module)
    let related = graph
        .symbols_in_file(&symbol.file_path.to_string_lossy())?
        .iter()
        .filter(|s| s.name.as_deref() != Some(symbol_name))
        .filter_map(|s| s.name.clone())
        .take(10)
        .collect();

    Ok(SymbolDetail {
        name: symbol_name.to_string(),
        kind: symbol.kind_normalized.clone(),
        file: symbol.file_path.to_string_lossy().to_string(),
        line: symbol.start_line,
        signature: None,     // Would come from LSP enrichment
        documentation: None, // Would come from LSP enrichment
        callers,
        callees,
        related,
    })
}

/// Get symbols that call the given symbol
pub fn get_callers(
    graph: &mut CodeGraph,
    symbol_name: &str,
    file_path: Option<&str>,
) -> Result<Vec<SymbolListItem>> {
    let symbols = if let Some(file) = file_path {
        graph
            .symbols_in_file(file)?
            .into_iter()
            .filter(|s| s.name.as_deref() == Some(symbol_name))
            .collect::<Vec<_>>()
    } else {
        let results = graph.get_symbols_by_label(symbol_name)?;
        results
            .into_iter()
            .filter_map(|r| {
                graph.symbols_in_file(&r.file_path).ok().and_then(|syms| {
                    syms.into_iter()
                        .find(|s| s.name.as_deref() == Some(symbol_name))
                })
            })
            .collect::<Vec<_>>()
    };

    let symbol = symbols
        .first()
        .ok_or_else(|| anyhow::anyhow!("Symbol '{}' not found", symbol_name))?;

    let callers = graph.callers_of_symbol(&symbol.file_path.to_string_lossy(), symbol_name)?;
    let items = callers
        .into_iter()
        .map(|c| SymbolListItem {
            name: c.caller,
            kind: "function".to_string(),
            file: c.file_path.to_string_lossy().to_string(),
            line: c.start_line,
        })
        .collect();

    Ok(items)
}

/// Get symbols called by the given symbol
pub fn get_callees(
    graph: &mut CodeGraph,
    symbol_name: &str,
    file_path: Option<&str>,
) -> Result<Vec<SymbolListItem>> {
    let symbols = if let Some(file) = file_path {
        graph
            .symbols_in_file(file)?
            .into_iter()
            .filter(|s| s.name.as_deref() == Some(symbol_name))
            .collect::<Vec<_>>()
    } else {
        let results = graph.get_symbols_by_label(symbol_name)?;
        results
            .into_iter()
            .filter_map(|r| {
                graph.symbols_in_file(&r.file_path).ok().and_then(|syms| {
                    syms.into_iter()
                        .find(|s| s.name.as_deref() == Some(symbol_name))
                })
            })
            .collect::<Vec<_>>()
    };

    let symbol = symbols
        .first()
        .ok_or_else(|| anyhow::anyhow!("Symbol '{}' not found", symbol_name))?;

    let callees = graph.calls_from_symbol(&symbol.file_path.to_string_lossy(), symbol_name)?;
    let items = callees
        .into_iter()
        .map(|c| SymbolListItem {
            name: c.callee,
            kind: "function".to_string(),
            file: c.file_path.to_string_lossy().to_string(),
            line: c.start_line,
        })
        .collect();

    Ok(items)
}

/// List symbols with pagination
pub fn list_symbols(
    graph: &mut CodeGraph,
    query: &ListQuery,
) -> Result<PaginatedResult<SymbolListItem>> {
    let page = query
        .cursor
        .as_ref()
        .and_then(|c| base64::engine::general_purpose::STANDARD.decode(c).ok())
        .and_then(|d| String::from_utf8(d).ok())
        .and_then(|s| {
            s.strip_prefix("page=")
                .and_then(|p| p.parse::<usize>().ok())
        })
        .unwrap_or(query.page.unwrap_or(1));

    let page_size = query.page_size.unwrap_or(50);

    // Get all symbols or filter by kind
    let all_symbols = if let Some(ref kind) = query.kind {
        graph
            .get_symbols_by_label(kind)?
            .into_iter()
            .map(|r| SymbolListItem {
                name: r.name,
                kind: kind.clone(),
                file: r.file_path,
                line: 0, // SymbolQueryResult doesn't have line info
            })
            .collect::<Vec<_>>()
    } else {
        // Get symbols from all files
        let files = graph.all_file_nodes()?;
        let mut items = Vec::new();

        for (file_path, _) in files {
            if let Ok(symbols) = graph.symbols_in_file(&file_path) {
                for symbol in symbols {
                    if let Some(ref name) = symbol.name {
                        items.push(SymbolListItem {
                            name: name.clone(),
                            kind: symbol.kind_normalized.clone(),
                            file: file_path.clone(),
                            line: symbol.start_line,
                        });
                    }
                }
            }
        }
        items
    };

    let total_items = all_symbols.len();

    Ok(PaginatedResult::new(
        all_symbols,
        page,
        page_size,
        total_items,
    ))
}

/// Symbol list item for pagination
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolListItem {
    pub name: String,
    pub kind: String,
    pub file: String,
    pub line: usize,
}

// Helper functions

fn detect_project_info() -> Result<(String, String)> {
    // Try to find Cargo.toml
    let cargo_toml = std::path::Path::new("Cargo.toml");
    if cargo_toml.exists() {
        if let Ok(content) = std::fs::read_to_string(cargo_toml) {
            let name = content
                .lines()
                .find(|l| l.starts_with("name = "))
                .and_then(|l| l.split('"').nth(1))
                .unwrap_or("unknown")
                .to_string();

            let version = content
                .lines()
                .find(|l| l.starts_with("version = "))
                .and_then(|l| l.split('"').nth(1))
                .unwrap_or("0.1.0")
                .to_string();

            return Ok((name, version));
        }
    }

    // Fallback to directory name
    let dir_name = std::env::current_dir()
        .ok()
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
        .unwrap_or_else(|| "unknown".to_string());

    Ok((dir_name, "0.1.0".to_string()))
}

fn detect_primary_language(graph: &mut CodeGraph) -> Result<String> {
    // Count files by extension
    let files = graph.all_file_nodes()?;
    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();

    for (path, _) in files {
        if let Some(ext) = std::path::Path::new(&path)
            .extension()
            .and_then(|e| e.to_str())
        {
            *counts.entry(ext.to_string()).or_insert(0) += 1;
        }
    }

    // Find most common extension
    let primary = counts
        .iter()
        .max_by_key(|(_, &count)| count)
        .map(|(ext, _)| ext.as_str())
        .unwrap_or("unknown");

    let language = match primary {
        "rs" => "Rust",
        "py" => "Python",
        "c" | "h" => "C",
        "cpp" | "hpp" | "cc" => "C++",
        "java" => "Java",
        "js" | "mjs" => "JavaScript",
        "ts" | "tsx" => "TypeScript",
        _ => "Unknown",
    };

    Ok(language.to_string())
}

fn find_entry_points(graph: &mut CodeGraph) -> Result<Vec<String>> {
    let mut entry_points = Vec::new();

    // Look for main functions
    if let Ok(mains) = graph.get_symbols_by_label("main") {
        for m in mains {
            entry_points.push(format!("{} ({})", m.name, m.file_path));
        }
    }

    // Look for lib.rs
    if let Ok(libs) = graph.get_symbols_by_label("lib") {
        for l in libs {
            entry_points.push(format!("{} ({})", l.name, l.file_path));
        }
    }

    Ok(entry_points)
}

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

    #[test]
    fn test_paginated_result_creation() {
        let items: Vec<i32> = (1..101).collect();
        let result = PaginatedResult::new(items, 1, 50, 100);

        assert_eq!(result.page, 1);
        assert_eq!(result.total_pages, 2);
        assert_eq!(result.page_size, 50);
        assert_eq!(result.total_items, 100);
        assert!(result.next_cursor.is_some());
        assert!(result.prev_cursor.is_none());
        assert_eq!(result.items.len(), 50);
    }

    #[test]
    fn test_list_query_default() {
        let query = ListQuery::default();
        assert_eq!(query.page, Some(1));
        assert_eq!(query.page_size, Some(50));
        assert!(query.kind.is_none());
    }
}