magellan 3.1.7

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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
//! Tests for graph algorithms (Phase 40)
//!
//! Tests reachability analysis, dead code detection, and program slicing using
//! sqlitegraph algorithm functions.

use tempfile::TempDir;

#[test]
fn test_reachable_symbols_finds_transitive_closure() {
    // Test that reachable_symbols finds all symbols reachable from a start point
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
    helper_b();
}

fn helper_a() {
    shared();
}

fn helper_b() {
    shared();
}

fn shared() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get main's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let main_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("main"))
        .expect("Should find main symbol");

    let main_fqn = main_symbol
        .fqn
        .as_ref()
        .or(main_symbol.canonical_fqn.as_ref())
        .expect("main should have FQN");

    // Test forward reachability from main
    // main -> helper_a, helper_b -> shared
    let reachable = graph.reachable_symbols(main_fqn, None).unwrap();

    // We should find at least some reachable symbols
    // (The exact count depends on whether main is included)
    assert!(
        !reachable.is_empty(),
        "Should find reachable symbols from main"
    );

    // Verify we find the expected symbols
    let fqn_names: Vec<_> = reachable.iter().filter_map(|s| s.fqn.as_deref()).collect();

    // helper_a and helper_b should be directly reachable from main
    assert!(
        fqn_names.contains(&"helper_a") || fqn_names.contains(&"test.rs::helper_a"),
        "Should find helper_a as reachable from main"
    );
}

#[test]
fn test_dead_symbols_finds_unreachable_code() {
    // Test that dead_symbols finds code not reachable from entry point
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
}

fn helper_a() {
    shared();
}

fn shared() {}

fn unused_function() {
    shared();
}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get main's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let main_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("main"))
        .expect("Should find main symbol");

    let main_fqn = main_symbol
        .fqn
        .as_ref()
        .or(main_symbol.canonical_fqn.as_ref())
        .expect("main should have FQN");

    // Find dead code from main
    let dead = graph.dead_symbols(main_fqn).unwrap();

    // unused_function should be detected as dead
    let dead_fqns: Vec<_> = dead
        .iter()
        .filter_map(|s| s.symbol.fqn.as_deref())
        .collect();

    assert!(
        dead_fqns.contains(&"unused_function")
            || dead_fqns.iter().any(|f| f.contains("unused_function")),
        "unused_function should be detected as dead"
    );
}

#[test]
fn test_reverse_reachable_finds_callers() {
    // Test that reverse_reachable_symbols finds all callers
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
    helper_b();
}

fn helper_a() {
    shared();
}

fn helper_b() {
    shared();
}

fn shared() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get shared's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let shared_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("shared"))
        .expect("Should find shared symbol");

    let shared_fqn = shared_symbol
        .fqn
        .as_ref()
        .or(shared_symbol.canonical_fqn.as_ref())
        .expect("shared should have FQN");

    // Find callers of shared (reverse reachability)
    let callers = graph.reverse_reachable_symbols(shared_fqn, None).unwrap();

    // helper_a and helper_b should both call shared
    let caller_fqns: Vec<_> = callers.iter().filter_map(|s| s.fqn.as_deref()).collect();

    assert!(
        !callers.is_empty(),
        "Should have callers for shared function"
    );

    // At minimum, we should find helper_a or helper_b in the caller list
    assert!(
        caller_fqns.contains(&"helper_a")
            || caller_fqns.contains(&"helper_b")
            || caller_fqns.iter().any(|f| f.contains("helper")),
        "Should find at least one helper function as a caller of shared"
    );
}

#[test]
fn test_algorithm_empty_database() {
    // Test algorithm behavior on empty database
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");

    let graph = CodeGraph::open(&db_path).unwrap();

    // Querying reachable symbols on empty DB should error
    let result = graph.reachable_symbols("nonexistent", None);
    assert!(
        result.is_err(),
        "Should error when symbol not found in database"
    );
}

#[test]
fn test_algorithm_nonexistent_symbol() {
    // Test algorithm behavior with nonexistent symbol
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = "fn main() {}";

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();

    // Querying nonexistent symbol should error
    let result = graph.reachable_symbols("this_symbol_does_not_exist", None);
    assert!(result.is_err(), "Should error when symbol ID not found");
}

// Program slicing tests (Phase 40-04)

#[test]
fn test_backward_slice_finds_callers() {
    // Test that backward_slice finds all callers of a target symbol
    // Using call-graph reachability as fallback
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    intermediate();
}

fn intermediate() {
    leaf();
}

fn leaf() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get leaf's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let leaf_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("leaf"))
        .expect("Should find leaf symbol");

    let leaf_fqn = leaf_symbol
        .fqn
        .as_ref()
        .or(leaf_symbol.canonical_fqn.as_ref())
        .expect("leaf should have FQN");

    // Run backward slice on leaf
    let slice_result = graph.backward_slice(leaf_fqn).unwrap();

    // intermediate should be in the backward slice (it calls leaf)
    let slice_fqns: Vec<_> = slice_result
        .slice
        .included_symbols
        .iter()
        .filter_map(|s| s.fqn.as_deref())
        .collect();

    assert!(
        !slice_fqns.is_empty(),
        "Backward slice from leaf should contain callers"
    );

    // intermediate calls leaf, so it should be in the backward slice
    assert!(
        slice_fqns.contains(&"intermediate")
            || slice_fqns.iter().any(|f| f.contains("intermediate")),
        "intermediate should be in backward slice from leaf"
    );
}

#[test]
fn test_forward_slice_finds_callees() {
    // Test that forward_slice finds all symbols reachable from target
    // Using call-graph reachability as fallback
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    intermediate();
}

fn intermediate() {
    leaf();
}

fn leaf() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get main's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let main_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("main"))
        .expect("Should find main symbol");

    let main_fqn = main_symbol
        .fqn
        .as_ref()
        .or(main_symbol.canonical_fqn.as_ref())
        .expect("main should have FQN");

    // Run forward slice from main
    let slice_result = graph.forward_slice(main_fqn).unwrap();

    // intermediate should be in the forward slice (called by main)
    let slice_fqns: Vec<_> = slice_result
        .slice
        .included_symbols
        .iter()
        .filter_map(|s| s.fqn.as_deref())
        .collect();

    assert!(
        !slice_fqns.is_empty(),
        "Forward slice from main should contain callees"
    );

    // intermediate is called by main
    assert!(
        slice_fqns.contains(&"intermediate")
            || slice_fqns.iter().any(|f| f.contains("intermediate")),
        "intermediate should be in forward slice from main"
    );
}

#[test]
fn test_slice_statistics() {
    // Test that slice statistics are correctly computed
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
    helper_b();
}

fn helper_a() {
    shared();
}

fn helper_b() {
    shared();
}

fn shared() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get shared's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let shared_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("shared"))
        .expect("Should find shared symbol");

    let shared_fqn = shared_symbol
        .fqn
        .as_ref()
        .or(shared_symbol.canonical_fqn.as_ref())
        .expect("shared should have FQN");

    // Run backward slice
    let slice_result = graph.backward_slice(shared_fqn).unwrap();

    // Statistics should reflect the slice content
    assert_eq!(
        slice_result.statistics.total_symbols,
        slice_result.slice.included_symbols.len(),
        "total_symbols should match included symbols count"
    );

    // With call-graph fallback, data_dependencies is 0
    assert_eq!(
        slice_result.statistics.data_dependencies, 0,
        "data_dependencies should be 0 with call-graph fallback"
    );

    // control_dependencies should be non-zero (we have callers)
    assert!(
        slice_result.statistics.control_dependencies > 0,
        "control_dependencies should be non-zero"
    );
}

#[test]
fn test_slice_is_empty_for_isolated_function() {
    // Test that slice of isolated function returns minimal results
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn isolated_function() {
    let x = 42;
}

fn other_function() {
    let y = 10;
}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get isolated_function's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let isolated_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("isolated_function"))
        .expect("Should find isolated_function symbol");

    let isolated_fqn = isolated_symbol
        .fqn
        .as_ref()
        .or(isolated_symbol.canonical_fqn.as_ref())
        .expect("isolated_function should have FQN");

    // Run backward slice - should be empty (no callers)
    let backward_slice = graph.backward_slice(isolated_fqn).unwrap();
    assert!(
        backward_slice.slice.included_symbols.is_empty(),
        "Backward slice of isolated function should be empty"
    );

    // Run forward slice - should be empty (no callees)
    let forward_slice = graph.forward_slice(isolated_fqn).unwrap();
    assert!(
        forward_slice.slice.included_symbols.is_empty(),
        "Forward slice of isolated function should be empty"
    );
}

#[test]
fn test_slice_direction_consistency() {
    // Test that backward and forward slices are consistent
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn a() {
    b();
}

fn b() {
    c();
}

fn c() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get b's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let b_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("b"))
        .expect("Should find b symbol");

    let b_fqn = b_symbol
        .fqn
        .as_ref()
        .or(b_symbol.canonical_fqn.as_ref())
        .expect("b should have FQN");

    // Run both backward and forward slices
    let backward = graph.backward_slice(b_fqn).unwrap();
    let forward = graph.forward_slice(b_fqn).unwrap();

    // Verify direction is correctly set
    assert!(
        matches!(backward.slice.direction, magellan::SliceDirection::Backward),
        "Backward slice should have Backward direction"
    );
    assert!(
        matches!(forward.slice.direction, magellan::SliceDirection::Forward),
        "Forward slice should have Forward direction"
    );

    // b should be the target for both
    assert_eq!(
        backward.slice.target.kind, forward.slice.target.kind,
        "Target should be the same for both slices"
    );
}

#[test]
fn test_enumerate_paths_finds_execution_paths() {
    // Test that enumerate_paths finds all execution paths from a start point
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
    helper_b();
}

fn helper_a() {
    leaf();
}

fn helper_b() {
    leaf();
}

fn leaf() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get main's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let main_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("main"))
        .expect("Should find main symbol");

    let main_fqn = main_symbol
        .fqn
        .as_ref()
        .or(main_symbol.canonical_fqn.as_ref())
        .expect("main should have FQN");

    // Test path enumeration from main
    let result = graph.enumerate_paths(main_fqn, None, 10, 100).unwrap();

    // The result should be valid (even if paths are empty due to graph structure)
    // Verify statistics are properly computed
    if !result.paths.is_empty() {
        assert!(
            result.statistics.avg_length > 0.0,
            "Average path length should be positive when paths exist"
        );
        assert!(
            result.statistics.max_length >= result.statistics.min_length,
            "Max length should be >= min length"
        );
    } else {
        // If no paths found, verify stats are still in valid state
        assert!(
            result.statistics.avg_length >= 0.0,
            "Average path length should be non-negative"
        );
    }

    // Test that we can also enumerate to a specific target
    let leaf_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("leaf"))
        .expect("Should find leaf symbol");

    let leaf_fqn = leaf_symbol
        .fqn
        .as_ref()
        .or(leaf_symbol.canonical_fqn.as_ref())
        .expect("leaf should have FQN");

    // Enumerate paths from main to leaf
    let result_to_leaf = graph
        .enumerate_paths(main_fqn, Some(leaf_fqn), 10, 100)
        .unwrap();

    // Should return a valid result
    assert!(
        result_to_leaf.total_enumerated >= 0,
        "Total enumerated should be non-negative"
    );
}

#[test]
fn test_enumerate_paths_with_end_symbol() {
    // Test path enumeration with a specific end symbol
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper();
}

fn helper() {
    target();
}

fn target() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get main's and target's FQNs
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let main_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("main"))
        .expect("Should find main symbol");
    let target_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("target"))
        .expect("Should find target symbol");

    let main_fqn = main_symbol
        .fqn
        .as_ref()
        .or(main_symbol.canonical_fqn.as_ref())
        .expect("main should have FQN");
    let target_fqn = target_symbol
        .fqn
        .as_ref()
        .or(target_symbol.canonical_fqn.as_ref())
        .expect("target should have FQN");

    // Enumerate paths from main to target
    let result = graph
        .enumerate_paths(main_fqn, Some(target_fqn), 10, 100)
        .unwrap();

    // We should find at least one path from main to target
    assert!(
        !result.paths.is_empty(),
        "Should find at least one path from main to target"
    );

    // Each path should end at target
    for path in &result.paths {
        let last_fqn = path
            .symbols
            .last()
            .and_then(|s| s.fqn.as_deref())
            .unwrap_or("");
        assert!(
            last_fqn.contains("target") || last_fqn == target_fqn,
            "Path should end at target symbol"
        );
    }
}

#[test]
fn test_enumerate_paths_respects_bounds() {
    // Test that enumerate_paths respects max_depth and max_paths bounds
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    // Create code with multiple paths
    let source = r#"
fn main() {
    a();
    b();
    c();
}

fn a() { x(); }
fn b() { x(); }
fn c() { x(); }

fn x() {
    y();
}

fn y() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get main's FQN
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let main_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("main"))
        .expect("Should find main symbol");

    let main_fqn = main_symbol
        .fqn
        .as_ref()
        .or(main_symbol.canonical_fqn.as_ref())
        .expect("main should have FQN");

    // Test with max_paths = 2
    let result = graph.enumerate_paths(main_fqn, None, 10, 2).unwrap();

    // Should return at most 2 paths
    assert!(
        result.paths.len() <= 2,
        "Should respect max_paths bound (got {} paths)",
        result.paths.len()
    );
}

// SCC and condensation tests (Phase 40-02)

#[test]
fn test_detect_cycles_finds_mutual_recursion() {
    // Test that detect_cycles finds mutually recursive functions
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
}

fn a() {
    b();
}

fn b() {
    a();
}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Detect cycles
    let report = graph.detect_cycles().unwrap();

    // Should find one cycle (mutual recursion between a and b)
    assert!(
        report.total_count > 0,
        "Should detect cycles in mutually recursive code"
    );

    // Find the cycle with mutual recursion
    let mutual_cycle = report
        .cycles
        .iter()
        .find(|c| matches!(c.kind, magellan::graph::CycleKind::MutualRecursion));

    assert!(mutual_cycle.is_some(), "Should find mutual recursion cycle");

    let cycle = mutual_cycle.unwrap();
    let cycle_fqns: Vec<_> = cycle
        .members
        .iter()
        .filter_map(|s| s.fqn.as_deref())
        .collect();

    assert!(
        cycle_fqns.iter().any(|f| f.contains("a")),
        "Cycle should contain function 'a'"
    );
    assert!(
        cycle_fqns.iter().any(|f| f.contains("b")),
        "Cycle should contain function 'b'"
    );
}

#[test]
fn test_detect_cycles_no_cycles_in_dag() {
    // Test that detect_cycles returns no cycles for DAG code
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
}

fn a() {
    b();
}

fn b() {
    c();
}

fn c() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Detect cycles
    let report = graph.detect_cycles().unwrap();

    // Should find no cycles (code is a DAG)
    assert!(
        report.total_count == 0,
        "Should detect no cycles in DAG code (found {})",
        report.total_count
    );
    assert!(report.cycles.is_empty(), "Cycle list should be empty");
}

#[test]
fn test_find_cycles_containing_specific_symbol() {
    // Test that find_cycles_containing finds cycles with a specific symbol
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
    x();
}

fn a() {
    b();
}

fn b() {
    a();
}

fn x() {
    y();
}

fn y() {
    x();
}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get FQN for function 'a'
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let a_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("a"))
        .expect("Should find 'a' symbol");

    let a_fqn = a_symbol
        .fqn
        .as_ref()
        .or(a_symbol.canonical_fqn.as_ref())
        .expect("Symbol should have FQN");

    // Find cycles containing 'a'
    let cycles = graph.find_cycles_containing(a_fqn).unwrap();

    // Should find one cycle containing 'a'
    assert!(!cycles.is_empty(), "Should find cycles containing 'a'");

    // Verify the cycle contains 'a'
    let cycle_fqns: Vec<_> = cycles[0]
        .members
        .iter()
        .filter_map(|s| s.fqn.as_deref())
        .collect();

    assert!(
        cycle_fqns.iter().any(|f| f.contains("a")),
        "Cycle should contain 'a'"
    );
    assert!(
        cycle_fqns.iter().any(|f| f.contains("b")),
        "Cycle should contain 'b' (a's cycle partner)"
    );
}

#[test]
fn test_find_cycles_containing_non_cyclic_symbol() {
    // Test that find_cycles_containing returns empty for non-cyclic symbols
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
}

fn a() {
    b();
}

fn b() {
    c();
}

fn c() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Get FQN for function 'a' (not in a cycle)
    let symbols = graph.symbols_in_file(&path_str).unwrap();
    let a_symbol = symbols
        .iter()
        .find(|s| s.name.as_deref() == Some("a"))
        .expect("Should find 'a' symbol");

    let a_fqn = a_symbol
        .fqn
        .as_ref()
        .or(a_symbol.canonical_fqn.as_ref())
        .expect("Symbol should have FQN");

    // Find cycles containing 'a'
    let cycles = graph.find_cycles_containing(a_fqn).unwrap();

    // Should find no cycles
    assert!(
        cycles.is_empty(),
        "Should find no cycles for non-cyclic symbol 'a'"
    );
}

#[test]
fn test_condense_call_graph_creates_dag() {
    // Test that condense_call_graph collapses SCCs into supernodes
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
}

fn a() {
    b();
}

fn b() {
    a();
    c();
}

fn c() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Condense the call graph
    let result = graph.condense_call_graph().unwrap();

    // Should have supernodes
    assert!(
        !result.graph.supernodes.is_empty(),
        "Should create supernodes"
    );

    // One supernode should contain the cycle {a, b}
    let cycle_supernode = result.graph.supernodes.iter().find(|s| {
        let fqns: Vec<_> = s.members.iter().filter_map(|m| m.fqn.as_deref()).collect();
        fqns.iter().any(|f| f.contains("a")) && fqns.iter().any(|f| f.contains("b"))
    });

    assert!(
        cycle_supernode.is_some(),
        "Should have a supernode containing the cycle between a and b"
    );

    // condensation graph should be a DAG (no cycles between supernodes)
    // Verify we have a reasonable structure
    // Note: There may be extra nodes for call intermediates, so we use a reasonable upper bound
    assert!(
        result.graph.supernodes.len() <= 10, // main, a+b cycle, c, plus call nodes
        "Should have a reasonable number of supernodes (got {})",
        result.graph.supernodes.len()
    );
}

#[test]
fn test_condense_call_graph_single_symbol_supernodes() {
    // Test that single symbols (not in cycles) get their own supernodes
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
}

fn a() {
    b();
}

fn b() {}
fn c() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Condense the call graph
    let result = graph.condense_call_graph().unwrap();

    // Each non-cyclic function should be its own supernode
    let single_member_supernodes: Vec<_> = result
        .graph
        .supernodes
        .iter()
        .filter(|s| s.members.len() == 1)
        .collect();

    assert!(
        single_member_supernodes.len() >= 3,
        "Should have at least 3 single-member supernodes (main, b, c)"
    );
}

#[test]
fn test_condense_call_graph_symbol_to_supernode_mapping() {
    // Test that supernodes contain the correct symbols
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    a();
}

fn a() {
    b();
}

fn b() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Condense the call graph
    let result = graph.condense_call_graph().unwrap();

    // Find the supernode containing 'main'
    let main_supernode = result.graph.supernodes.iter().find(|s| {
        s.members.iter().any(|m| {
            m.fqn
                .as_deref()
                .map(|f| f.contains("main"))
                .unwrap_or(false)
        })
    });

    assert!(
        main_supernode.is_some(),
        "Should find a supernode containing 'main'"
    );

    // Verify the mapping is consistent
    // (Each symbol with a symbol_id should map to a supernode)
    let mut mapped_count = 0;
    for supernode in &result.graph.supernodes {
        for member in &supernode.members {
            if let Some(ref sym_id) = member.symbol_id {
                if let Some(&mapped_id) = result.original_to_supernode.get(sym_id) {
                    assert_eq!(
                        mapped_id, supernode.id,
                        "Symbol {} should map to the correct supernode",
                        sym_id
                    );
                    mapped_count += 1;
                }
            }
        }
    }

    // At least main should have a symbol_id and be mapped
    assert!(
        mapped_count > 0,
        "At least one symbol should be in the mapping"
    );
}

// ============================================================================
// Regression Tests for Identified Pitfalls (from RESEARCH.md)
// ============================================================================

#[test]
fn test_fqn_fallback_lookup() {
    // Verifies FQN fallback works for symbol resolution
    // Users can query by simple names like "main" instead of symbol_id
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper();
}

fn helper() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Test FQN fallback - should work with just "main" instead of full symbol_id
    let reachable = graph.reachable_symbols("main", None).unwrap();

    // Should find helper when starting from FQN "main"
    assert!(
        !reachable.is_empty(),
        "FQN fallback should resolve 'main' to the correct symbol"
    );
}

// ============================================================================
// Edge Case Tests
// ============================================================================

#[test]
fn test_single_symbol_graph() {
    // Test algorithms handle graph with a single symbol
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = "fn main() {}\n";

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Single symbol should have no reachable symbols
    let reachable = graph.reachable_symbols("main", None).unwrap();
    // main itself is not included in results, so empty is expected
    assert!(
        reachable.is_empty(),
        "Single symbol should have no reachable callees"
    );

    // Cycle detection should work (single symbol is not a cycle)
    let cycles = graph.detect_cycles().unwrap();
    assert!(
        cycles.cycles.is_empty(),
        "Single symbol with no self-loop should have no cycles"
    );

    // Condensation should work (single supernode)
    let condensed = graph.condense_call_graph().unwrap();
    assert!(
        !condensed.graph.supernodes.is_empty(),
        "Even single symbol should create a supernode"
    );
}

#[test]
fn test_disconnected_components() {
    // Test algorithms handle graph with multiple disjoint call graphs
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
}

fn helper_a() {}

fn standalone_function() {
    helper_b();
}

fn helper_b() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Reachability from main should not reach standalone_function
    let reachable_from_main = graph.reachable_symbols("main", None).unwrap();
    let standalone_found = reachable_from_main.iter().any(|s| {
        s.fqn
            .as_deref()
            .map(|f| f.contains("standalone_function"))
            .unwrap_or(false)
    });

    assert!(
        !standalone_found,
        "Reachability should not cross disconnected components"
    );

    // Verify standalone_function has its own reachable callees
    let reachable_from_standalone = graph
        .reachable_symbols("standalone_function", None)
        .unwrap();
    let helper_b_found = reachable_from_standalone.iter().any(|s| {
        s.fqn
            .as_deref()
            .map(|f| f.contains("helper_b"))
            .unwrap_or(false)
    });

    assert!(
        helper_b_found,
        "Standalone component should have its own reachable callees"
    );
}

// ============================================================================
// Integration Tests for Combined Algorithms
// ============================================================================

#[test]
fn test_slice_after_condense() {
    // Test that slicing works correctly after condensation
    // This verifies that condensation doesn't break symbol resolution
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
}

fn helper_a() {
    shared();
}

fn shared() {}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // First condense the graph
    let _condensed = graph.condense_call_graph().unwrap();

    // Then slice - should still work (use backward_slice)
    let slice_result = graph.backward_slice("helper_a").unwrap();

    assert!(
        !slice_result.slice.included_symbols.is_empty(),
        "Slicing should work after condensation"
    );

    // The slice should include main (caller of helper_a)
    let main_found = slice_result.slice.included_symbols.iter().any(
        |s: &magellan::graph::algorithms::SymbolInfo| {
            s.fqn
                .as_deref()
                .map(|f: &str| f.contains("main"))
                .unwrap_or(false)
        },
    );

    assert!(
        main_found,
        "Backward slice from helper_a should include main"
    );
}

#[test]
fn test_dead_code_with_cycles() {
    // Test dead code detection when there are cycles in the graph
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    helper_a();
}

fn helper_a() {
    helper_b();
}

fn helper_b() {
    helper_a(); // Cycle with helper_a
}

fn unused_cycle_start() {
    unused_cycle_end();
}

fn unused_cycle_end() {
    unused_cycle_start(); // Disconnected cycle
}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // Dead code detection should find the unused cycle
    let dead = graph.dead_symbols("main").unwrap();

    // dead_symbols returns Vec<DeadSymbol> directly
    let unused_found = dead.iter().any(|s| {
        s.symbol
            .fqn
            .as_deref()
            .map(|f| f.contains("unused_cycle"))
            .unwrap_or(false)
    });

    assert!(
        unused_found,
        "Dead code detection should find disconnected cycles"
    );
}

#[test]
fn test_cycle_then_slice() {
    // Test slicing within a cycle
    use magellan::CodeGraph;

    let temp_dir = TempDir::new().unwrap();
    let db_path = temp_dir.path().join("test.rs");
    let file_path = temp_dir.path().join("test.rs");

    let source = r#"
fn main() {
    cycle_start();
}

fn cycle_start() {
    cycle_middle();
}

fn cycle_middle() {
    cycle_end();
}

fn cycle_end() {
    cycle_start(); // Back edge creates cycle
}
"#;

    let mut graph = CodeGraph::open(&db_path).unwrap();
    let path_str = file_path.to_string_lossy().to_string();

    graph.index_file(&path_str, source.as_bytes()).unwrap();
    graph.index_calls(&path_str, source.as_bytes()).unwrap();

    // First verify we have a cycle
    let cycles = graph.detect_cycles().unwrap();
    assert!(!cycles.cycles.is_empty(), "Should detect the cycle");

    // Slice should still work within the cycle (use backward_slice)
    let slice_result = graph.backward_slice("cycle_middle").unwrap();

    // Backward slice from cycle_middle should include cycle_start and main
    assert!(
        !slice_result.slice.included_symbols.is_empty(),
        "Slice within cycle should return results"
    );
}