fossil-mcp 0.1.5

Multi-language static analysis toolkit with MCP server. Detects dead code, code clones, and AI scaffolding.
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
//! Graph builder: constructs a CodeGraph from parsed files.
//!
//! The `GraphBuilder` builds a call graph from the extracted code nodes and edges
//! in `ParsedFile`s. It resolves intra-file calls by name matching and tracks
//! unresolved cross-file calls for later aggregation.

use std::collections::{BinaryHeap, HashMap, HashSet};

use crate::core::{
    CallEdge, CodeNode, EdgeConfidence, Language, NodeId, NodeKind, ParsedFile, SourceLocation,
    Visibility,
};
use crate::parsers::{extract_calls, extract_functions, ParserRegistry, ZeroCopyParseTree};
use petgraph::graph::NodeIndex;

use super::code_graph::CodeGraph;
use super::import_resolver::ImportResolver;

/// Compute priority for a call based on resolution confidence, simplicity, and reachability.
/// Processes high-confidence calls first for cache locality and prioritizes
/// calls from reachable functions (demand-driven).
fn compute_call_priority(call: &crate::core::UnresolvedCall, is_caller_reachable: bool) -> u32 {
    let mut priority = 0;

    // Reachability-based priority (demand-driven)
    // Calls from reachable functions have higher priority
    if is_caller_reachable {
        priority += 200; // Highest priority: reachable callers
    }

    // File-scoped calls (has source_module) - higher confidence
    if call.source_module.is_some() {
        priority += 100;
    }

    // No import aliasing - simpler resolution, fewer fallbacks
    if call.imported_as.is_none() {
        priority += 10;
    }

    priority
}

/// Builds a `CodeGraph` from parsed source files.
pub struct GraphBuilder {
    registry: ParserRegistry,
}

impl GraphBuilder {
    pub fn new() -> Result<Self, crate::core::Error> {
        Ok(Self {
            registry: ParserRegistry::with_defaults()?,
        })
    }

    /// Build a graph from a single source file.
    pub fn build_file_graph(
        &self,
        source: &str,
        file_path: &str,
        language: Language,
    ) -> Result<CodeGraph, crate::core::Error> {
        let ext = std::path::Path::new(file_path)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        let parser = self
            .registry
            .get_parser_for_extension(ext)
            .or_else(|| self.registry.get_parser(language))
            .ok_or_else(|| {
                crate::core::Error::parse(format!("No parser for {}", language.name()))
            })?;

        let parsed = parser.parse_file(file_path, source)?;
        self.build_from_parsed_file(&parsed)
    }

    /// Build a graph from a `ParsedFile` (already parsed by a language parser).
    pub fn build_from_parsed_file(
        &self,
        parsed: &ParsedFile,
    ) -> Result<CodeGraph, crate::core::Error> {
        let mut graph = CodeGraph::new().with_language(parsed.language);

        // Index: name -> NodeId for intra-file call resolution
        let mut name_to_id: HashMap<String, NodeId> = HashMap::new();

        // Add all nodes
        for node in &parsed.nodes {
            graph.add_node(node.clone());
            name_to_id.insert(node.name.clone(), node.id);
            if node.full_name != node.name {
                name_to_id.insert(node.full_name.clone(), node.id);
            }
        }

        // Add resolved edges
        for edge in &parsed.edges {
            let _ = graph.add_edge(edge.clone());
        }

        // Mark entry points
        for &ep_id in &parsed.entry_points {
            if let Some(idx) = graph.get_index(ep_id) {
                graph.add_entry_point(idx);
            }
        }

        // Detect additional entry points by heuristics
        // Collect first, then mutate (avoids borrow checker issue)
        let entry_indices: Vec<NodeIndex> = graph
            .nodes()
            .filter(|(_, n)| is_entry_point_heuristic(n))
            .map(|(idx, _)| idx)
            .collect();
        let test_indices: Vec<NodeIndex> = graph
            .nodes()
            .filter(|(_, n)| is_test_entry_point(n))
            .map(|(idx, _)| idx)
            .collect();

        for idx in entry_indices {
            graph.add_entry_point(idx);
        }
        for idx in test_indices {
            graph.add_test_entry_point(idx);
        }

        Ok(graph)
    }

    /// Build a merged graph from multiple parsed files.
    pub fn build_project_graph(
        &self,
        parsed_files: &[ParsedFile],
    ) -> Result<CodeGraph, crate::core::Error> {
        let mut project_graph = CodeGraph::new();

        // Build per-file graphs and merge
        for pf in parsed_files.iter() {
            let file_graph = self.build_from_parsed_file(pf)?;
            project_graph.merge(&file_graph);
        }

        // === Demand-driven filtering - only resolve calls from reachable functions ===
        // Compute intra-file reachability from entry points BEFORE cross-file resolution
        // This allows us to skip resolving calls from unreachable (dead code) functions
        let intrafile_reachable = project_graph.compute_production_reachable();
        let intrafile_test_reachable = project_graph.compute_test_reachable();
        let all_reachable: std::collections::HashSet<NodeIndex> = intrafile_reachable
            .union(&intrafile_test_reachable)
            .copied()
            .collect();

        // Barrel file suffixes for re-export chain resolution
        let barrel_suffixes = [
            "index.ts",
            "index.js",
            "index.tsx",
            "index.jsx",
            "__init__.py",
        ];

        // Build import resolver for file-scoped name resolution
        let resolver = ImportResolver::new(parsed_files);

        // === Cross-file call resolution ===
        // Build barrel re-export cache and ParsedFile index in a single pass
        // (eliminates O(files × barrels × lines) re-parsing + O(4030) linear scan per lookup)
        let mut barrel_cache: std::collections::HashMap<String, Vec<BarrelReexport>> =
            std::collections::HashMap::new();
        let mut barrel_pf_index: HashMap<String, &ParsedFile> = HashMap::new();
        for pf in parsed_files {
            if barrel_suffixes.iter().any(|s| pf.path.ends_with(s)) {
                barrel_cache.insert(pf.path.clone(), extract_barrel_reexports(&pf.source));
                barrel_pf_index.insert(pf.path.clone(), pf);
            }
        }

        // === Call clustering - resolve identical (source_module, callee_name) calls once ===
        // Cache for resolved clusters: (source_module, callee_name) -> resolved_target_id
        let mut resolution_cache: HashMap<(Option<String>, String), Option<NodeId>> =
            HashMap::new();

        // === Build priority worklist for high-confidence calls ===

        // Count total calls before worklist optimization
        let _total_unresolved_calls: usize = parsed_files
            .iter()
            .map(|pf| pf.unresolved_calls.len())
            .sum();

        // Collect all unresolved calls with their caller files for priority-based worklist
        // Use reachability info for smart prioritization
        // We resolve ALL calls, but prioritize calls from reachable functions first
        let mut all_unresolved_calls: Vec<(&crate::core::UnresolvedCall, String, Language)> =
            Vec::new();
        for pf in parsed_files {
            for unresolved in &pf.unresolved_calls {
                all_unresolved_calls.push((unresolved, pf.path.clone(), pf.language));
            }
        }

        // Build priority worklist (BinaryHeap for efficient max-priority extraction)
        // Store (priority, index) pairs to look up calls separately
        // Include reachability info in priority computation
        let mut worklist: BinaryHeap<(u32, usize)> = all_unresolved_calls
            .iter()
            .enumerate()
            .map(|(i, (call, _, _))| {
                let caller_idx = project_graph.get_index(call.caller_id);
                let is_caller_reachable = caller_idx
                    .map(|idx| all_reachable.contains(&idx))
                    .unwrap_or(false);
                let priority = compute_call_priority(call, is_caller_reachable);
                // BinaryHeap is a max-heap: higher priority popped first
                (priority, i)
            })
            .collect();

        // Resolve cross-file calls using priority worklist
        let mut cross_file_edges = Vec::new();
        let mut _clustered_resolutions = 0;
        while let Some((_, call_index)) = worklist.pop() {
            let (unresolved, caller_file, caller_lang) = &all_unresolved_calls[call_index];
            // Try the imported_as name first, then fall back to callee_name
            let callee_name = unresolved
                .imported_as
                .as_deref()
                .unwrap_or(&unresolved.callee_name);

            // Check if this (source_module, callee_name) cluster has already been resolved
            let cluster_key = (unresolved.source_module.clone(), callee_name.to_string());
            if let Some(cached_result) = resolution_cache.get(&cluster_key) {
                // Reuse cached resolution without repeating the work
                if let Some(resolved_id) = cached_result {
                    cross_file_edges.push(CallEdge::new(
                        unresolved.caller_id,
                        *resolved_id,
                        EdgeConfidence::HighLikely,
                    ));
                    _clustered_resolutions += 1;
                }
                continue; // Skip detailed resolution for this call
            }

            // Try file-scoped resolution first (higher confidence)
            let mut resolved = false;
            let mut resolved_id: Option<NodeId> = None;
            if let Some(source_module) = &unresolved.source_module {
                let candidates = resolver.resolve(source_module, caller_file, *caller_lang);
                if let Some(callee_idx) =
                    project_graph.find_node_by_name_in_files(callee_name, &candidates)
                {
                    if let Some(to_id) = project_graph.get_node(callee_idx).map(|n| n.id) {
                        cross_file_edges.push(CallEdge::new(
                            unresolved.caller_id,
                            to_id,
                            EdgeConfidence::HighLikely,
                        ));
                        resolved = true;
                        resolved_id = Some(to_id);
                    }
                }
                // Also try original callee_name in scoped files
                if !resolved && unresolved.imported_as.is_some() {
                    if let Some(callee_idx) = project_graph
                        .find_node_by_name_in_files(&unresolved.callee_name, &candidates)
                    {
                        if let Some(to_id) = project_graph.get_node(callee_idx).map(|n| n.id) {
                            cross_file_edges.push(CallEdge::new(
                                unresolved.caller_id,
                                to_id,
                                EdgeConfidence::HighLikely,
                            ));
                            resolved = true;
                            resolved_id = Some(to_id);
                        }
                    }
                }

                // If file-scoped lookup failed and candidate is a barrel file,
                // follow re-export chain: use cached re-exports to find real source.
                if !resolved {
                    let barrel_candidates =
                        resolver.resolve(source_module, caller_file, *caller_lang);
                    for candidate_file in &barrel_candidates {
                        if !barrel_suffixes.iter().any(|s| candidate_file.ends_with(s)) {
                            continue;
                        }
                        // === QUICK WIN: Use HashMap instead of iter().find() ===
                        // Try exact match first (O(1)), then fuzzy match fallback (O(barrels))
                        let mut barrel_pf: Option<&&ParsedFile> =
                            barrel_pf_index.get(candidate_file);

                        // Fallback to fuzzy matching if exact match failed
                        if barrel_pf.is_none() {
                            barrel_pf = barrel_pf_index
                                .iter()
                                .find(|(path, _)| {
                                    path.ends_with(candidate_file.as_str())
                                        || candidate_file.ends_with(path.as_str())
                                })
                                .map(|(_, pf)| pf);
                        }

                        if let Some(&barrel_pf) = barrel_pf {
                            // Use cached re-exports instead of re-parsing
                            let reexports = barrel_cache
                                .get(&barrel_pf.path)
                                .cloned()
                                .unwrap_or_default();
                            for reexport in reexports {
                                let reexport_candidates = resolver.resolve(
                                    &reexport.source_path,
                                    &barrel_pf.path,
                                    barrel_pf.language,
                                );

                                if reexport.exported_name == callee_name {
                                    // Exact named re-export: export { X } from './path'
                                    if let Some(idx) = project_graph.find_node_by_name_in_files(
                                        &reexport.original_name,
                                        &reexport_candidates,
                                    ) {
                                        if let Some(to_id) =
                                            project_graph.get_node(idx).map(|n| n.id)
                                        {
                                            cross_file_edges.push(CallEdge::new(
                                                unresolved.caller_id,
                                                to_id,
                                                EdgeConfidence::HighLikely,
                                            ));
                                            resolved = true;
                                            resolved_id = Some(to_id);
                                        }
                                    }
                                } else if reexport.exported_name == "*" {
                                    // Wildcard re-export: export * from './path'
                                    // Look for the callee in the re-exported source files
                                    if let Some(idx) = project_graph.find_node_by_name_in_files(
                                        callee_name,
                                        &reexport_candidates,
                                    ) {
                                        if let Some(to_id) =
                                            project_graph.get_node(idx).map(|n| n.id)
                                        {
                                            cross_file_edges.push(CallEdge::new(
                                                unresolved.caller_id,
                                                to_id,
                                                EdgeConfidence::HighLikely,
                                            ));
                                            resolved = true;
                                            resolved_id = Some(to_id);
                                        }
                                    }
                                    // Also try original callee_name if it was renamed via import
                                    if !resolved && unresolved.imported_as.is_some() {
                                        if let Some(idx) = project_graph.find_node_by_name_in_files(
                                            &unresolved.callee_name,
                                            &reexport_candidates,
                                        ) {
                                            if let Some(to_id) =
                                                project_graph.get_node(idx).map(|n| n.id)
                                            {
                                                cross_file_edges.push(CallEdge::new(
                                                    unresolved.caller_id,
                                                    to_id,
                                                    EdgeConfidence::HighLikely,
                                                ));
                                                resolved = true;
                                                resolved_id = Some(to_id);
                                            }
                                        }
                                    }
                                }
                                if resolved {
                                    break;
                                }
                            }
                        }
                        if resolved {
                            break;
                        }
                    }
                }
            }

            // Fall back to proximity-based global lookup (language-scoped)
            if !resolved {
                resolved = Self::resolve_global_with_proximity(
                    callee_name,
                    caller_file.as_str(),
                    *caller_lang,
                    &unresolved.caller_id,
                    &project_graph,
                    &mut cross_file_edges,
                );
                if !resolved && unresolved.imported_as.is_some() {
                    Self::resolve_global_with_proximity(
                        &unresolved.callee_name,
                        caller_file.as_str(),
                        *caller_lang,
                        &unresolved.caller_id,
                        &project_graph,
                        &mut cross_file_edges,
                    );
                }
            }

            // Update cache with resolved target for this (source_module, callee_name) cluster
            // Only cache file-scoped resolutions (those with source_module)
            // Global resolutions can have multiple targets, so we skip caching those
            if unresolved.source_module.is_some() {
                resolution_cache.insert(cluster_key, resolved_id);
            }
        }

        for edge in cross_file_edges.iter() {
            let _ = project_graph.add_edge(edge.clone());
        }

        // === Dispatch edge building ===

        // Collect method names per class from the graph
        // (optimization: only process method nodes, not all node kinds)
        let mut class_methods: HashMap<String, HashSet<String>> = HashMap::new();
        for (_, node) in project_graph.nodes() {
            // Only process method/constructor nodes (not functions, variables, etc.)
            if !matches!(node.kind, NodeKind::Method | NodeKind::Constructor) {
                continue;
            }
            if let Some(class_name) = extract_class_from_full_name(&node.full_name) {
                class_methods
                    .entry(class_name)
                    .or_default()
                    .insert(node.name.clone());
            }
        }

        // For each class that extends/implements a parent, create dispatch edges
        let mut dispatch_edges = Vec::new();
        for pf in parsed_files {
            for rel in &pf.class_relations {
                for parent in &rel.parents {
                    // Find methods on child that also exist on parent
                    let child_methods = class_methods.get(&rel.class_name);
                    let parent_methods = class_methods.get(parent);
                    if let (Some(child_ms), Some(parent_ms)) = (child_methods, parent_methods) {
                        for method_name in child_ms.intersection(parent_ms) {
                            // Find the parent's method node and create edge to child's method
                            let parent_full = format!("{}.{}", parent, method_name);
                            let child_full = format!("{}.{}", rel.class_name, method_name);
                            if let (Some(parent_idx), Some(child_idx)) = (
                                project_graph.find_node_by_name(&parent_full),
                                project_graph.find_node_by_name(&child_full),
                            ) {
                                let parent_id = project_graph.get_node(parent_idx).unwrap().id;
                                let child_id = project_graph.get_node(child_idx).unwrap().id;
                                dispatch_edges.push(CallEdge::new(
                                    parent_id,
                                    child_id,
                                    EdgeConfidence::Possible,
                                ));
                            }
                        }
                    }
                }
            }
        }

        for edge in dispatch_edges.iter() {
            let _ = project_graph.add_edge(edge.clone());
        }

        Ok(project_graph)
    }

    /// Proximity-based global fallback for cross-file call resolution.
    ///
    /// Language-scoped: only considers candidates in compatible languages.
    /// Three-level strategy to disambiguate when multiple functions share a name:
    ///   Level 1 — Same-file: unambiguous, `Certain` confidence.
    ///   Level 2 — Directory proximity: prefer same-dir, then parent-dir. `HighLikely`.
    ///   Level 3 — All matches: create edges to every candidate with `Possible` confidence.
    fn resolve_global_with_proximity(
        callee_name: &str,
        caller_file: &str,
        caller_lang: Language,
        caller_id: &NodeId,
        graph: &CodeGraph,
        edges: &mut Vec<CallEdge>,
    ) -> bool {
        use std::path::Path;

        // Level 1: Same-file preference
        if let Some(idx) = graph.find_node_by_name_in_file(callee_name, caller_file) {
            if let Some(to_id) = graph.get_node(idx).map(|n| n.id) {
                edges.push(CallEdge::new(*caller_id, to_id, EdgeConfidence::Certain));
                return true;
            }
        }

        // Get all candidates — filtered to compatible languages only
        let candidates = graph.find_nodes_by_name_and_language(callee_name, caller_lang);
        if candidates.is_empty() {
            return false;
        }
        if candidates.len() == 1 {
            if let Some(to_id) = graph.get_node(candidates[0]).map(|n| n.id) {
                edges.push(CallEdge::new(*caller_id, to_id, EdgeConfidence::HighLikely));
                return true;
            }
        }

        // Level 2: Directory proximity
        let caller_dir = Path::new(caller_file).parent().map(|p| p.to_path_buf());
        let caller_parent_dir = caller_dir
            .as_ref()
            .and_then(|d| d.parent())
            .map(|p| p.to_path_buf());

        let mut same_dir = Vec::new();
        let mut parent_dir = Vec::new();

        for &idx in &candidates {
            if let Some(node) = graph.get_node(idx) {
                let node_dir = Path::new(&node.location.file)
                    .parent()
                    .map(|p| p.to_path_buf());
                if node_dir == caller_dir {
                    same_dir.push(idx);
                } else if caller_parent_dir.is_some() && node_dir == caller_parent_dir {
                    parent_dir.push(idx);
                }
            }
        }

        if same_dir.len() == 1 {
            if let Some(to_id) = graph.get_node(same_dir[0]).map(|n| n.id) {
                edges.push(CallEdge::new(*caller_id, to_id, EdgeConfidence::HighLikely));
                return true;
            }
        }
        if same_dir.is_empty() && parent_dir.len() == 1 {
            if let Some(to_id) = graph.get_node(parent_dir[0]).map(|n| n.id) {
                edges.push(CallEdge::new(*caller_id, to_id, EdgeConfidence::HighLikely));
                return true;
            }
        }

        // Level 3: All matches — create edges to every candidate with Possible confidence
        for &idx in &candidates {
            if let Some(to_id) = graph.get_node(idx).map(|n| n.id) {
                edges.push(CallEdge::new(*caller_id, to_id, EdgeConfidence::Possible));
            }
        }
        true
    }

    /// Access the parser registry.
    pub fn registry(&self) -> &ParserRegistry {
        &self.registry
    }
}

/// Build a CodeGraph from a ZeroCopyParseTree using the extractors.
pub fn build_graph_from_tree(
    tree: &ZeroCopyParseTree,
    file_path: &str,
    language: Language,
) -> CodeGraph {
    let mut graph = CodeGraph::new().with_language(language);
    let functions = extract_functions(tree);
    let calls = extract_calls(tree);

    // Create nodes for each function
    let mut name_to_id: HashMap<String, NodeId> = HashMap::new();

    for (name, start_line, end_line, is_public, node_kind) in &functions {
        let visibility = if *is_public {
            Visibility::Public
        } else {
            Visibility::Private
        };
        // Use the NodeKind from extraction instead of guessing from name
        let kind = *node_kind;

        let node = CodeNode::new(
            name.clone(),
            kind,
            SourceLocation::new(file_path.to_string(), *start_line, *end_line, 0, 0),
            language,
            visibility,
        )
        .with_lines_of_code(end_line.saturating_sub(*start_line) + 1);

        let node_id = node.id;
        let idx = graph.add_node(node);
        name_to_id.insert(name.clone(), node_id);

        if is_main_like(name) {
            graph.add_entry_point(idx);
        }
        if is_test_like(name) {
            graph.add_test_entry_point(idx);
        }
    }

    // Create edges for calls
    for (call_line, callee_name) in &calls {
        let caller_id =
            find_containing_function(&functions, *call_line).and_then(|name| name_to_id.get(name));
        let callee_id = name_to_id.get(callee_name.as_str());

        if let (Some(&from_id), Some(&to_id)) = (caller_id, callee_id) {
            let edge = CallEdge::certain(from_id, to_id);
            let _ = graph.add_edge(edge);
        }
    }

    graph
}

fn find_containing_function(
    functions: &[(String, usize, usize, bool, NodeKind)],
    line: usize,
) -> Option<&str> {
    let mut best: Option<&(String, usize, usize, bool, NodeKind)> = None;
    for func in functions {
        if line >= func.1
            && line <= func.2
            && (best.is_none() || (func.2 - func.1) < (best.unwrap().2 - best.unwrap().1))
        {
            best = Some(func);
        }
    }
    best.map(|f| f.0.as_str())
}

fn is_entry_point_heuristic(node: &CodeNode) -> bool {
    is_main_like(&node.name)
        || node.attributes.iter().any(|a| {
            a.contains("route")
                || a.contains("handler")
                || a.contains("endpoint")
                || a.contains("api")
                || a.contains("main")
        })
}

fn is_test_entry_point(node: &CodeNode) -> bool {
    node.is_test || is_test_like(&node.name)
}

fn is_main_like(name: &str) -> bool {
    matches!(name, "main" | "__main__" | "Main" | "app" | "run" | "start")
}

/// Extract the class name from a full_name like "ClassName.method" or "ClassName::method".
fn extract_class_from_full_name(full_name: &str) -> Option<String> {
    // Try dot separator (Python, JS, Java, C#)
    if let Some(dot_pos) = full_name.rfind('.') {
        let class_part = &full_name[..dot_pos];
        if !class_part.is_empty() && !class_part.contains('/') {
            return Some(class_part.to_string());
        }
    }
    // Try :: separator (Rust, C++)
    if let Some(sep_pos) = full_name.rfind("::") {
        let class_part = &full_name[..sep_pos];
        if !class_part.is_empty() {
            return Some(class_part.to_string());
        }
    }
    None
}

fn is_test_like(name: &str) -> bool {
    name.starts_with("test_")
        || name.starts_with("Test")
        || name.ends_with("_test")
        || name.starts_with("it_")
        || name.starts_with("should_")
}

/// A re-export extracted from a barrel file's source text.
#[derive(Clone)]
struct BarrelReexport {
    /// The name as exported (may be an alias).
    exported_name: String,
    /// The original name in the source module.
    original_name: String,
    /// The relative source module path (e.g. `./db`).
    source_path: String,
}

/// Extract re-export statements from a barrel file's source text.
///
/// Handles both JS/TS and Python barrel patterns:
/// - JS/TS: `export { Name } from './path'`, `export * from './path'`
/// - Python: `from .module import name`, `from .module import name as alias`, `from .module import *`
fn extract_barrel_reexports(source: &str) -> Vec<BarrelReexport> {
    let mut results = Vec::new();
    for line in source.lines() {
        let trimmed = line.trim();

        // JS/TS: export ... from '...'
        if trimmed.starts_with("export") {
            if let Some(reexports) = extract_js_reexports(trimmed) {
                results.extend(reexports);
            }
            continue;
        }

        // Python: from .module import name [as alias]
        if trimmed.starts_with("from ") && trimmed.contains(" import ") {
            if let Some(reexports) = extract_python_reexports(trimmed) {
                results.extend(reexports);
            }
        }
    }
    results
}

/// Parse JS/TS re-export line: `export { X } from './path'` or `export * from './path'`
fn extract_js_reexports(trimmed: &str) -> Option<Vec<BarrelReexport>> {
    // Extract the `from '...'` or `from "..."` path
    let from_path = {
        let pos = trimmed.find("from ")?;
        let after = trimmed[pos + 5..].trim().trim_end_matches(';').trim();
        if (after.starts_with('\'') && after.ends_with('\''))
            || (after.starts_with('"') && after.ends_with('"'))
        {
            Some(after[1..after.len() - 1].to_string())
        } else {
            None
        }
    }?;

    let mut results = Vec::new();

    // `export * from './path'`
    if trimmed.contains("export *") || trimmed.contains("export  *") {
        results.push(BarrelReexport {
            exported_name: "*".to_string(),
            original_name: "*".to_string(),
            source_path: from_path,
        });
        return Some(results);
    }

    // `export { ... } from './path'`
    let brace_start = trimmed.find('{')?;
    let brace_end = trimmed.find('}')?;
    let names_str = &trimmed[brace_start + 1..brace_end];
    for name_part in names_str.split(',') {
        let name_part = name_part.trim();
        if name_part.is_empty() {
            continue;
        }
        if let Some(as_pos) = name_part.find(" as ") {
            let original = name_part[..as_pos].trim().to_string();
            let alias = name_part[as_pos + 4..].trim().to_string();
            results.push(BarrelReexport {
                exported_name: alias,
                original_name: original,
                source_path: from_path.clone(),
            });
        } else {
            results.push(BarrelReexport {
                exported_name: name_part.to_string(),
                original_name: name_part.to_string(),
                source_path: from_path.clone(),
            });
        }
    }
    Some(results)
}

/// Parse Python re-export line: `from .module import name [as alias]`
fn extract_python_reexports(trimmed: &str) -> Option<Vec<BarrelReexport>> {
    // Split on " import " to get module path and imported names
    let import_pos = trimmed.find(" import ")?;
    let module_part = trimmed[5..import_pos].trim(); // after "from ", before " import "
    let names_part = trimmed[import_pos + 8..].trim(); // after " import "

    // Module must be a relative import (starts with .)
    if !module_part.starts_with('.') {
        return None;
    }

    let mut results = Vec::new();

    // `from .module import *`
    if names_part == "*" {
        results.push(BarrelReexport {
            exported_name: "*".to_string(),
            original_name: "*".to_string(),
            source_path: module_part.to_string(),
        });
        return Some(results);
    }

    // `from .module import A, B as C, D`
    // Handle parenthesized imports: `from .module import (A, B)`
    let names_str = names_part
        .trim_start_matches('(')
        .trim_end_matches(')')
        .trim();
    for name_part in names_str.split(',') {
        let name_part = name_part.trim();
        if name_part.is_empty() {
            continue;
        }
        if let Some(as_pos) = name_part.find(" as ") {
            let original = name_part[..as_pos].trim().to_string();
            let alias = name_part[as_pos + 4..].trim().to_string();
            results.push(BarrelReexport {
                exported_name: alias,
                original_name: original,
                source_path: module_part.to_string(),
            });
        } else {
            results.push(BarrelReexport {
                exported_name: name_part.to_string(),
                original_name: name_part.to_string(),
                source_path: module_part.to_string(),
            });
        }
    }
    Some(results)
}

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

    #[test]
    fn test_build_graph_from_python() {
        let builder = GraphBuilder::new().unwrap();
        let graph = builder
            .build_file_graph(
                r#"
def main():
    helper()

def helper():
    pass

def unused():
    pass
"#,
                "test.py",
                Language::Python,
            )
            .unwrap();

        assert!(graph.node_count() >= 3);
        assert!(graph.find_node_by_name("main").is_some());
    }

    #[test]
    fn test_build_graph_edges() {
        let builder = GraphBuilder::new().unwrap();
        let graph = builder
            .build_file_graph(
                r#"
def foo():
    bar()

def bar():
    pass
"#,
                "test.py",
                Language::Python,
            )
            .unwrap();

        assert!(graph.node_count() >= 2);
    }

    #[test]
    fn test_entry_point_heuristics() {
        assert!(is_main_like("main"));
        assert!(is_main_like("__main__"));
        assert!(!is_main_like("helper"));

        assert!(is_test_like("test_foo"));
        assert!(is_test_like("TestFoo"));
        assert!(!is_test_like("foo"));
    }

    #[test]
    fn test_extract_class_from_full_name() {
        assert_eq!(
            extract_class_from_full_name("MyClass.method"),
            Some("MyClass".to_string())
        );
        assert_eq!(
            extract_class_from_full_name("MyStruct::method"),
            Some("MyStruct".to_string())
        );
        assert_eq!(extract_class_from_full_name("bare_function"), None);
        // File paths shouldn't be treated as class names
        assert_eq!(extract_class_from_full_name("src/auth.rs"), None);
    }

    #[test]
    fn test_source_module_propagated_in_parsed_file() {
        // Verify that source_module is set when parsing JS/TS files with imports
        let builder = GraphBuilder::new().unwrap();
        let parsed = builder
            .registry()
            .get_parser(Language::TypeScript)
            .unwrap()
            .parse_file(
                "src/app.ts",
                r#"
import { helper } from './utils';

function main() {
    helper();
}
"#,
            )
            .unwrap();

        let has_source_module = parsed.unresolved_calls.iter().any(|u| {
            (u.callee_name == "helper" || u.imported_as.as_deref() == Some("helper"))
                && u.source_module.as_deref() == Some("./utils")
        });
        assert!(
            has_source_module,
            "UnresolvedCall for 'helper' should have source_module='./utils', got: {:?}",
            parsed
                .unresolved_calls
                .iter()
                .map(|u| (&u.callee_name, &u.imported_as, &u.source_module))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_import_scoped_resolution_picks_correct_file() {
        // Two files both define "helper", but only one is the import target.
        // File A (src/utils.ts) defines helper()
        // File B (src/other.ts) also defines helper()
        // File C (src/app.ts) imports helper from './utils' and calls it
        // The builder should resolve to the helper in utils.ts, not other.ts.
        let builder = GraphBuilder::new().unwrap();

        let parsed_a = builder
            .registry()
            .get_parser(Language::TypeScript)
            .unwrap()
            .parse_file(
                "src/utils.ts",
                r#"
export function helper() {
    return "from utils";
}
"#,
            )
            .unwrap();

        let parsed_b = builder
            .registry()
            .get_parser(Language::TypeScript)
            .unwrap()
            .parse_file(
                "src/other.ts",
                r#"
export function helper() {
    return "from other";
}
"#,
            )
            .unwrap();

        let parsed_c = builder
            .registry()
            .get_parser(Language::TypeScript)
            .unwrap()
            .parse_file(
                "src/app.ts",
                r#"
import { helper } from './utils';

function main() {
    helper();
}
"#,
            )
            .unwrap();

        let graph = builder
            .build_project_graph(&[parsed_a, parsed_b, parsed_c])
            .unwrap();

        // main should have an edge to helper
        let main_idx = graph.find_node_by_name("main");
        assert!(main_idx.is_some(), "Should find main node");

        // Check that main calls helper in utils.ts (file-scoped)
        let main_callees: Vec<_> = graph.calls_from(main_idx.unwrap()).collect();
        assert!(
            !main_callees.is_empty(),
            "main should have outgoing edges to helper"
        );

        // The resolved callee should be in src/utils.ts
        let callee_node = graph.get_node(main_callees[0]).unwrap();
        assert_eq!(
            callee_node.location.file, "src/utils.ts",
            "Should resolve to helper in src/utils.ts, not src/other.ts. Got: {}",
            callee_node.location.file
        );
    }

    #[test]
    fn test_class_relations_populated() {
        let builder = GraphBuilder::new().unwrap();
        let parsed = builder
            .registry()
            .get_parser(Language::Python)
            .unwrap()
            .parse_file(
                "test.py",
                r#"
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "woof"
"#,
            )
            .unwrap();

        assert!(
            !parsed.class_relations.is_empty(),
            "Should have class relations, got: {:?}",
            parsed.class_relations
        );
        let dog_rel = parsed
            .class_relations
            .iter()
            .find(|r| r.class_name == "Dog");
        assert!(dog_rel.is_some(), "Should find Dog in class_relations");
        assert!(
            dog_rel.unwrap().parents.contains(&"Animal".to_string()),
            "Dog should extend Animal"
        );
    }

    #[test]
    fn test_extends_attributes_on_child_methods() {
        let builder = GraphBuilder::new().unwrap();
        let parsed = builder
            .registry()
            .get_parser(Language::Python)
            .unwrap()
            .parse_file(
                "test.py",
                r#"
class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "woof"
"#,
            )
            .unwrap();

        // The "speak" method in Dog should have "extends:Animal" attribute
        let dog_speak = parsed
            .nodes
            .iter()
            .find(|n| n.name == "speak" && n.attributes.iter().any(|a| a == "extends:Animal"));
        assert!(
            dog_speak.is_some(),
            "Dog.speak should have extends:Animal attribute. Nodes: {:?}",
            parsed
                .nodes
                .iter()
                .map(|n| (&n.name, &n.attributes, n.location.line_start))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_extract_barrel_reexports_js() {
        let source = r#"export { connect } from './db';
export { helper as h } from './utils';
export * from './all';
"#;
        let reexports = extract_barrel_reexports(source);
        assert_eq!(reexports.len(), 3);
        assert_eq!(reexports[0].exported_name, "connect");
        assert_eq!(reexports[0].original_name, "connect");
        assert_eq!(reexports[0].source_path, "./db");
        assert_eq!(reexports[1].exported_name, "h");
        assert_eq!(reexports[1].original_name, "helper");
        assert_eq!(reexports[1].source_path, "./utils");
        assert_eq!(reexports[2].exported_name, "*");
        assert_eq!(reexports[2].source_path, "./all");
    }

    #[test]
    fn test_extract_barrel_reexports_python() {
        let source = r#"from .db import connect
from .utils import helper as h
from .models import *
"#;
        let reexports = extract_barrel_reexports(source);
        assert_eq!(
            reexports.len(),
            3,
            "Should extract 3 Python re-exports, got: {:?}",
            reexports
                .iter()
                .map(|r| (&r.exported_name, &r.source_path))
                .collect::<Vec<_>>()
        );
        assert_eq!(reexports[0].exported_name, "connect");
        assert_eq!(reexports[0].original_name, "connect");
        assert_eq!(reexports[0].source_path, ".db");
        assert_eq!(reexports[1].exported_name, "h");
        assert_eq!(reexports[1].original_name, "helper");
        assert_eq!(reexports[1].source_path, ".utils");
        assert_eq!(reexports[2].exported_name, "*");
        assert_eq!(reexports[2].source_path, ".models");
    }

    #[test]
    fn test_extract_barrel_reexports_python_multi_import() {
        let source = "from .db import connect, disconnect, query\n";
        let reexports = extract_barrel_reexports(source);
        assert_eq!(reexports.len(), 3);
        assert_eq!(reexports[0].exported_name, "connect");
        assert_eq!(reexports[1].exported_name, "disconnect");
        assert_eq!(reexports[2].exported_name, "query");
    }

    #[test]
    fn test_extract_barrel_reexports_ignores_absolute_python_imports() {
        // Absolute Python imports (no leading dot) are not barrel re-exports
        let source = "from os import path\nfrom sys import argv\n";
        let reexports = extract_barrel_reexports(source);
        assert_eq!(
            reexports.len(),
            0,
            "Absolute Python imports should not be treated as barrel re-exports"
        );
    }
}