magellan 3.2.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
//! Ambiguity tracking tests for CodeGraph
//!
//! Tests the AmbiguityOps trait and its implementation:
//! - create_ambiguous_group: Establish or update ambiguity groups
//! - resolve_by_symbol_id: Precise SymbolId-based resolution
//! - get_candidates: Enumerate all candidates for a display FQN
//!
//! Also includes CLI integration tests for:
//! - --symbol-id flag: Find by stable SymbolId
//! - --ambiguous flag: Show all candidates for display FQN
//! - --first flag: Deprecation warning verification

use magellan::graph::ambiguity::AmbiguityOps;
use magellan::graph::query;
use magellan::CodeGraph;
use std::fs;
use tempfile::TempDir;

// ============================================================================
// AmbiguityOps Unit Tests
// ============================================================================

#[test]
fn test_create_ambiguous_group_single_symbol() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create and index a test file
    let test_file = temp_dir.path().join("handler.rs");
    fs::write(&test_file, "fn Handler() {}").unwrap();

    let path_str = test_file.to_string_lossy().to_string();
    let source = fs::read(&test_file).unwrap();
    graph.index_file(&path_str, &source).unwrap();

    // Get the symbol entity ID
    let (_node_id, _fact, _symbol_id_option) =
        query::symbol_nodes_in_file_with_ids(&mut graph, &path_str)
            .unwrap()
            .into_iter()
            .next()
            .expect("Should have one symbol");

    // Create group with single symbol (should work)
    // We use the entity_id from the symbol, not symbol_id
    let entity_id = query::symbol_id_by_name(&mut graph, &path_str, "Handler")
        .unwrap()
        .expect("Handler should exist");

    let result = graph.create_ambiguous_group("Handler", &[entity_id]);
    assert!(
        result.is_ok(),
        "Should successfully create ambiguity group with single symbol"
    );
}

#[test]
fn test_create_ambiguous_group_multiple_symbols() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create two files with same symbol name (ambiguous display FQN)
    let file1 = temp_dir.path().join("handler.rs");
    fs::write(&file1, "fn Handler() {}").unwrap();

    let file2 = temp_dir.path().join("parser.rs");
    fs::write(&file2, "fn Handler() {}").unwrap();

    // Index both files
    let path1 = file1.to_string_lossy().to_string();
    let path2 = file2.to_string_lossy().to_string();
    let source1 = fs::read(&file1).unwrap();
    let source2 = fs::read(&file2).unwrap();
    graph.index_file(&path1, &source1).unwrap();
    graph.index_file(&path2, &source2).unwrap();

    // Get entity IDs for both symbols
    let entity_id1 = query::symbol_id_by_name(&mut graph, &path1, "Handler")
        .unwrap()
        .expect("Handler in handler.rs should exist");
    let entity_id2 = query::symbol_id_by_name(&mut graph, &path2, "Handler")
        .unwrap()
        .expect("Handler in parser.rs should exist");

    // Get the actual display_fqn from the first symbol
    let (_node_id1, fact1, _) = query::symbol_nodes_in_file_with_ids(&mut graph, &path1)
        .unwrap()
        .into_iter()
        .find(|(_, fact, _)| fact.name.as_deref() == Some("Handler"))
        .expect("Handler should exist");

    let display_fqn = fact1.display_fqn.as_deref().unwrap_or("Handler");

    // Create group with both symbols
    let result = graph.create_ambiguous_group(display_fqn, &[entity_id1, entity_id2]);
    assert!(
        result.is_ok(),
        "Should successfully create ambiguity group with multiple symbols"
    );

    // Verify candidates exist (may have 2, index_references also creates groups)
    let candidates = graph.get_candidates(display_fqn).unwrap();
    assert!(
        candidates.len() >= 2,
        "Should have at least 2 candidates for ambiguous display FQN (may be more due to index_references)"
    );
}

#[test]
fn test_resolve_by_symbol_id_found() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create and index a test file
    let test_file = temp_dir.path().join("handler.rs");
    fs::write(&test_file, "fn Handler() {}").unwrap();

    let path_str = test_file.to_string_lossy().to_string();
    let source = fs::read(&test_file).unwrap();
    graph.index_file(&path_str, &source).unwrap();

    // Get the SymbolId and display_fqn from the indexed symbol
    let (_node_id, fact, symbol_id_option) =
        query::symbol_nodes_in_file_with_ids(&mut graph, &path_str)
            .unwrap()
            .into_iter()
            .find(|(_, fact, _)| fact.name.as_deref() == Some("Handler"))
            .expect("Handler should exist");

    // Test resolve_by_symbol_id with actual SymbolId
    if let Some(symbol_id) = symbol_id_option {
        // Use display_fqn from the fact, falling back to name if not set
        let display_fqn = fact.display_fqn.as_deref().unwrap_or("Handler");
        let result = graph.resolve_by_symbol_id(display_fqn, &symbol_id).unwrap();
        assert!(
            result.is_some(),
            "Should find symbol when SymbolId exists and matches display FQN"
        );

        let found = result.unwrap();
        assert_eq!(
            found.symbol_id.unwrap(),
            symbol_id,
            "Returned symbol should have matching SymbolId"
        );
    }
}

#[test]
fn test_resolve_by_symbol_id_not_found() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Index a dummy file to ensure schema is initialized
    let test_file = temp_dir.path().join("dummy.rs");
    fs::write(&test_file, "fn dummy() {}").unwrap();
    let path_str = test_file.to_string_lossy().to_string();
    let source = fs::read(&test_file).unwrap();
    graph.index_file(&path_str, &source).unwrap();

    let result = graph
        .resolve_by_symbol_id("Handler", "nonexistent_id_123456789012")
        .unwrap();
    assert!(
        result.is_none(),
        "Should return None when SymbolId doesn't exist"
    );
}

#[test]
fn test_resolve_by_symbol_id_display_fqn_mismatch() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create and index a test file
    let test_file = temp_dir.path().join("handler.rs");
    fs::write(&test_file, "fn Handler() {}").unwrap();

    let path_str = test_file.to_string_lossy().to_string();
    let source = fs::read(&test_file).unwrap();
    graph.index_file(&path_str, &source).unwrap();

    // Get the SymbolId
    let (_node_id, _fact, symbol_id_option) =
        query::symbol_nodes_in_file_with_ids(&mut graph, &path_str)
            .unwrap()
            .into_iter()
            .find(|(_, fact, _)| fact.name.as_deref() == Some("Handler"))
            .expect("Handler should exist");

    // Query with different display_fqn
    if let Some(symbol_id) = symbol_id_option {
        let result = graph
            .resolve_by_symbol_id("DifferentHandler", &symbol_id)
            .unwrap();
        assert!(
            result.is_none(),
            "Should return None when SymbolId exists but display_fqn doesn't match"
        );
    }
}

#[test]
fn test_get_candidates_empty() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Index a dummy file to ensure schema is initialized
    let test_file = temp_dir.path().join("dummy.rs");
    fs::write(&test_file, "fn dummy() {}").unwrap();
    let path_str = test_file.to_string_lossy().to_string();
    let source = fs::read(&test_file).unwrap();
    graph.index_file(&path_str, &source).unwrap();

    let candidates = graph.get_candidates("nonexistent_fqn").unwrap();
    assert_eq!(
        candidates.len(),
        0,
        "Should return empty Vec for non-existent display FQN"
    );
}

#[test]
fn test_get_candidates_multiple() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create three files with same symbol name
    for name in &["handler.rs", "parser.rs", "auth.rs"] {
        let file = temp_dir.path().join(name);
        fs::write(&file, "fn Handler() {}").unwrap();

        let path_str = file.to_string_lossy().to_string();
        let source = fs::read(&file).unwrap();
        graph.index_file(&path_str, &source).unwrap();
    }

    // Get candidates for Handler display FQN
    // Note: The actual display_fqn may vary, so we find it from the indexed symbols
    let _candidates = graph.get_candidates("Handler").unwrap();

    // Should find candidates (exact count depends on FQN computation)
    // Just verify the query doesn't error - empty result is valid for non-existent display_fqn
    assert!(true, "Query should succeed without error");
}

#[test]
fn test_ambiguous_group_idempotent() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create two files with same symbol name
    let file1 = temp_dir.path().join("handler.rs");
    fs::write(&file1, "fn Handler() {}").unwrap();

    let file2 = temp_dir.path().join("parser.rs");
    fs::write(&file2, "fn Handler() {}").unwrap();

    // Index both files
    let path1 = file1.to_string_lossy().to_string();
    let path2 = file2.to_string_lossy().to_string();
    let source1 = fs::read(&file1).unwrap();
    let source2 = fs::read(&file2).unwrap();
    graph.index_file(&path1, &source1).unwrap();
    graph.index_file(&path2, &source2).unwrap();

    // Get entity IDs and display_fqn
    let entity_id1 = query::symbol_id_by_name(&mut graph, &path1, "Handler")
        .unwrap()
        .expect("Handler in handler.rs should exist");
    let entity_id2 = query::symbol_id_by_name(&mut graph, &path2, "Handler")
        .unwrap()
        .expect("Handler in parser.rs should exist");

    let (_node_id1, fact1, _) = query::symbol_nodes_in_file_with_ids(&mut graph, &path1)
        .unwrap()
        .into_iter()
        .find(|(_, fact, _)| fact.name.as_deref() == Some("Handler"))
        .expect("Handler should exist");

    let display_fqn = fact1.display_fqn.as_deref().unwrap_or("Handler");

    // Create group twice with same symbols
    graph
        .create_ambiguous_group(display_fqn, &[entity_id1, entity_id2])
        .unwrap();
    graph
        .create_ambiguous_group(display_fqn, &[entity_id1, entity_id2])
        .unwrap();

    // Verify candidates exist (idempotent - no duplicates from double call)
    let candidates = graph.get_candidates(display_fqn).unwrap();
    assert!(
        candidates.len() >= 2,
        "Should have at least 2 candidates (idempotent call doesn't create duplicates)"
    );
}

// ============================================================================
// CLI Integration Tests
// ============================================================================

#[test]
fn test_cli_find_by_symbol_id() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Insert symbol with known SymbolId by indexing a file
    let test_file = temp_dir.path().join("lib.rs");
    fs::write(&test_file, "fn function_name() {}").unwrap();

    let path_str = test_file.to_string_lossy().to_string();
    let source = fs::read(&test_file).unwrap();
    graph.index_file(&path_str, &source).unwrap();

    // Get the SymbolId
    let (_node_id, _fact, symbol_id_option) =
        query::symbol_nodes_in_file_with_ids(&mut graph, &path_str)
            .unwrap()
            .into_iter()
            .find(|(_, fact, _)| fact.name.as_deref() == Some("function_name"))
            .expect("function_name should exist");

    if let Some(symbol_id) = symbol_id_option {
        // Run CLI find with --symbol-id
        let output = std::process::Command::new(env!("CARGO_BIN_EXE_magellan"))
            .arg("find")
            .arg("--db")
            .arg(&db_path)
            .arg("--symbol-id")
            .arg(&symbol_id)
            .output()
            .unwrap();

        // Verify output contains the symbol
        assert!(output.status.success(), "CLI should succeed");
        let stdout = String::from_utf8(output.stdout).unwrap();
        assert!(
            stdout.contains(&symbol_id) || stdout.contains("function_name"),
            "Output should contain symbol_id or function_name"
        );
    }
}

#[test]
fn test_cli_find_ambiguous() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Insert ambiguous symbols
    let file1 = temp_dir.path().join("handler.rs");
    fs::write(&file1, "fn Handler() {}").unwrap();

    let file2 = temp_dir.path().join("parser.rs");
    fs::write(&file2, "fn Handler() {}").unwrap();

    let path1 = file1.to_string_lossy().to_string();
    let path2 = file2.to_string_lossy().to_string();
    let source1 = fs::read(&file1).unwrap();
    let source2 = fs::read(&file2).unwrap();
    graph.index_file(&path1, &source1).unwrap();
    graph.index_file(&path2, &source2).unwrap();

    // Get the display_fqn for Handler
    let (_node_id, fact, _) = query::symbol_nodes_in_file_with_ids(&mut graph, &path1)
        .unwrap()
        .into_iter()
        .find(|(_, fact, _)| fact.name.as_deref() == Some("Handler"))
        .expect("Handler should exist");

    let display_fqn = fact.display_fqn.as_deref().unwrap_or("Handler");

    // Run CLI find with --ambiguous
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_magellan"))
        .arg("find")
        .arg("--db")
        .arg(&db_path)
        .arg("--ambiguous")
        .arg(display_fqn)
        .output()
        .unwrap();

    // Verify error-free output (shows candidates)
    assert!(output.status.success(), "CLI should succeed");
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("candidate") || stderr.contains("Symbol") || stderr.contains("Canonical"),
        "stderr should show candidates information"
    );
}

#[test]
fn test_cli_find_first_deprecation_warning() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Insert ambiguous symbols
    let file1 = temp_dir.path().join("handler.rs");
    fs::write(&file1, "fn Handler() {}").unwrap();

    let file2 = temp_dir.path().join("parser.rs");
    fs::write(&file2, "fn Handler() {}").unwrap();

    let path1 = file1.to_string_lossy().to_string();
    let path2 = file2.to_string_lossy().to_string();
    let source1 = fs::read(&file1).unwrap();
    let source2 = fs::read(&file2).unwrap();
    graph.index_file(&path1, &source1).unwrap();
    graph.index_file(&path2, &source2).unwrap();

    // Run CLI find with --first (NOT using --output json to trigger human-mode warning)
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_magellan"))
        .arg("find")
        .arg("--db")
        .arg(&db_path)
        .arg("--name")
        .arg("Handler")
        .arg("--first")
        .output()
        .unwrap();

    // Verify deprecation warning in stderr
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("deprecated"),
        "stderr should contain deprecation warning for --first flag"
    );
}

#[test]
fn test_cli_find_ambiguous_with_display_fqn() {
    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut graph = CodeGraph::open(&db_path).unwrap();

    // Create TWO files with the same symbol name (creating ambiguity)
    let file1 = temp_dir.path().join("handler.rs");
    fs::write(&file1, "fn Handler() {}").unwrap();

    let file2 = temp_dir.path().join("parser.rs");
    fs::write(&file2, "fn Handler() {}").unwrap();

    // Index both files
    let path1 = file1.to_string_lossy().to_string();
    let path2 = file2.to_string_lossy().to_string();
    let source1 = fs::read(&file1).unwrap();
    let source2 = fs::read(&file2).unwrap();
    graph.index_file(&path1, &source1).unwrap();
    graph.index_file(&path2, &source2).unwrap();

    // Extract the display_fqn from the FIRST indexed symbol
    // CRITICAL: --ambiguous flag requires display_fqn, NOT just symbol name
    let (_node_id, fact, _) = query::symbol_nodes_in_file_with_ids(&mut graph, &path1)
        .unwrap()
        .into_iter()
        .find(|(_, fact, _)| fact.name.as_deref() == Some("Handler"))
        .expect("Handler should exist");

    let display_fqn = fact.display_fqn.as_deref().unwrap_or("Handler");

    // Run CLI find with --ambiguous using the FULL display_fqn
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_magellan"))
        .arg("find")
        .arg("--db")
        .arg(&db_path)
        .arg("--ambiguous")
        .arg(display_fqn) // Use display_fqn, not just "Handler"
        .output()
        .unwrap();

    // Verify output succeeds
    assert!(
        output.status.success(),
        "CLI should succeed with --ambiguous flag"
    );

    // Verify stderr contains candidate information (Symbol ID, Canonical, or Name)
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(
        stderr.contains("Symbol ID") || stderr.contains("Canonical") || stderr.contains("Name"),
        "stderr should show candidate details (Symbol ID, Canonical, or Name). Got: {}",
        stderr
    );

    // Verify the output shows multiple candidates (both Handler symbols)
    // The output should list candidates with their details
    assert!(
        stderr.contains("Symbol ID"),
        "stderr should list Symbol IDs for all candidates"
    );
}