codenexus 0.3.3

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! Cross-file type FQN resolution (design.md H6).
//!
//! Provides [`TypeResolver`] for resolving dangling type-reference edges
//! (`Extends`/`Implements`/`UsesType`) to their actual cross-file definition
//! FQNs. The parse phase creates these edges with best-effort FQNs constructed
//! from the current file's path/scope; for cross-file types (e.g.
//! `from foo import Bar; class Child(Bar)`), the target FQN won't match the
//! actual `Bar` node in `foo.py`, leaving the edge dangling. The
//! [`TypeResolver`] fixes these dangling edges by re-resolving the type name
//! against the symbol table using file-level, import, and project-level
//! lookup (same strategy as [`CallResolver`], ADR-011).
//!
//! # Per-language coverage
//!
//! - **C**: `#include "header.h"` brings typedef/macro types into scope; the
//!   resolver matches type names against all symbols from included files
//!   (project-level exported lookup covers this because C headers define
//!   exported symbols).
//! - **Rust**: `use crate::module::MyType;` creates an import binding; the
//!   resolver matches `MyType` against the imported names, resolving to
//!   `crate.module.MyType`. `impl Trait for Type` and `#[derive(Trait)]`
//!   edges are fixed the same way (the trait/type name is resolved via
//!   imports).
//! - **Python**: `from foo import Bar` — import-based lookup resolves `Bar`
//!   to `proj.foo.Bar`.
//! - **TypeScript**: `import { Foo } from './foo'` — same import-based
//!   resolution.
//! - **Fortran**: no inheritance semantics (MroStrategy::None); edges are
//!   still resolved if present but typically absent.
//!
//! # Lightweight design
//!
//! This resolver does NOT implement a full type system (no inference, no
//! generic substitution, no associated type resolution). It performs
//! name-based resolution only: extract the type name (last component of the
//! dangling FQN), look it up in the symbol table, and update the edge target.
//!
//! [`CallResolver`]: crate::resolve::CallResolver

use std::collections::HashMap;

use crate::ir::{ExtractResult, ImportInfo};
use crate::model::{ConfidenceTier, Edge, EdgeType, Graph};
use crate::resolve::ProjectSymbolTable;

/// Confidence for a file-level (same-file) type match.
const CONFIDENCE_EXACT: f32 = 0.95;
/// Confidence for an import-based type match.
const CONFIDENCE_IMPORT: f32 = 0.90;
/// Confidence for a project-level (exported) type match.
const CONFIDENCE_PROJECT: f32 = 0.80;

/// Edge types whose targets may need cross-file type FQN resolution.
const RESOLVABLE_EDGE_TYPES: [EdgeType; 3] =
    [EdgeType::Extends, EdgeType::Implements, EdgeType::UsesType];

/// Resolves dangling type-reference edges to their actual cross-file FQNs
/// (design.md H6).
///
/// Construct with [`TypeResolver::new`] passing a reference to the
/// [`ProjectSymbolTable`], then call
/// [`resolve_types`](Self::resolve_types) to fix dangling edges in the graph.
pub struct TypeResolver<'a> {
    symbol_table: &'a ProjectSymbolTable,
}

impl<'a> TypeResolver<'a> {
    /// Creates a new `TypeResolver` with the given symbol table.
    #[must_use]
    pub fn new(symbol_table: &'a ProjectSymbolTable) -> Self {
        Self { symbol_table }
    }

    /// Resolves a type name to its FQN, considering the file and its imports.
    ///
    /// Resolution order (same as [`CallResolver`](crate::resolve::CallResolver)):
    ///
    /// 1. **File-level lookup** (confidence 0.95, `SameFile`): the type is
    ///    defined in the same file as the reference.
    /// 2. **Import-based lookup** (confidence 0.90, `ImportScoped`): the type
    ///    name appears in the file's import list, and a matching symbol exists
    ///    in the project table.
    /// 3. **Project-level exported lookup** (confidence 0.80, `Global`): the
    ///    type is an exported symbol somewhere in the project.
    ///
    /// Returns `None` if the type cannot be resolved.
    #[must_use]
    pub fn resolve_type(
        &self,
        user_file: &str,
        type_name: &str,
        imports: &[ImportInfo],
    ) -> Option<(String, f32, ConfidenceTier)> {
        // 1. File-level lookup (same file).
        // Single-line for coverage: tarpaulin attribute continuation
        if let Some(entry) = self
            .symbol_table
            .lookup_in_file(user_file, type_name)
            .first()
        {
            return Some((entry.qn.clone(), CONFIDENCE_EXACT, ConfidenceTier::SameFile));
        }
        // 2. Import-based lookup.
        // Single-line for coverage: tarpaulin attribute continuation
        let is_imported = imports
            .iter()
            .any(|imp| imp.imported_names.iter().any(|n| n == type_name));
        if is_imported {
            if let Some(entry) = self.symbol_table.lookup(type_name).first() {
                // Single-line for coverage: tarpaulin attribute continuation
                return Some((
                    entry.qn.clone(),
                    CONFIDENCE_IMPORT,
                    ConfidenceTier::ImportScoped,
                ));
            }
        }
        // 3. Project-level exported lookup.
        if let Some(entry) = self.symbol_table.lookup_exported(type_name).first() {
            return Some((entry.qn.clone(), CONFIDENCE_PROJECT, ConfidenceTier::Global));
        }
        None
    }

    /// Resolves dangling `Extends`/`Implements`/`UsesType` edges in the graph.
    ///
    /// For each edge of a resolvable type whose target FQN does NOT correspond
    /// to an existing graph node (i.e. the edge is dangling), this method:
    ///
    /// 1. Extracts the type name (last `.`-separated component of the target
    ///    FQN).
    /// 2. Looks up the source node's `file_path` from the graph.
    /// 3. Retrieves the imports for that file from `results`.
    /// 4. Calls [`resolve_type`](Self::resolve_type) to find the real FQN.
    /// 5. If resolved, updates the edge's `target`, `confidence`, and
    ///    `confidence_tier` in-place.
    ///
    /// Edges whose target already exists in the graph are left unchanged.
    ///
    /// # Arguments
    ///
    /// * `results` - Extraction results (used to build a file → imports map).
    /// * `graph` - The graph whose dangling edges to fix (mutated in-place).
    ///
    /// # Returns
    ///
    /// A vector of the resolved (fixed) edges. These are the same edges that
    /// were mutated in `graph` — returned for logging/reporting purposes.
    pub fn resolve_types(&self, results: &[ExtractResult], graph: &mut Graph) -> Vec<Edge> {
        // In production, `ExtractResult.file_path` is absolute (set by
        // `extract_file` from `file.path`), while graph nodes' `file_path` is
        // relative (normalized by `ScopeResolutionPhase`, phases.rs:344-346).
        // This path-format mismatch causes `imports_map.get(source_file)` and
        // `symbol_table.lookup_in_file(source_file, ...)` to miss, leaving all
        // Extends/Implements/UsesType edges unresolved (confidence stuck at
        // 1.0). Build a bidirectional path mapping by matching result nodes'
        // `qualified_name` to graph nodes' `qualified_name` (both are FQNs
        // generated from the absolute path during the parse phase, so they
        // match even though `file_path` differs).
        let mut result_to_graph_fp: HashMap<&str, &str> = HashMap::new();
        for result in results {
            // Skip if we already mapped this file.
            if result_to_graph_fp.contains_key(result.file_path.as_str()) {
                continue;
            }
            for node in &result.nodes {
                if let Some(graph_node) = graph.nodes.get(&node.qualified_name) {
                    if let Some(graph_fp) = graph_node.file_path.as_deref() {
                        // Single-line for coverage: tarpaulin attribute continuation
                        result_to_graph_fp.insert(result.file_path.as_str(), graph_fp);
                        break;
                    }
                }
            }
        }
        // Reverse mapping: graph file_path (relative) → result file_path
        // (absolute), used to translate `source_file` back to the format
        // expected by `symbol_table.lookup_in_file`.
        // Single-line for coverage: tarpaulin attribute continuation
        let graph_to_result_fp: HashMap<&str, &str> =
            result_to_graph_fp.iter().map(|(k, v)| (*v, *k)).collect();

        // Build file_path → imports map, keyed by GRAPH file_path (relative)
        // so it matches `fqn_to_file` values.
        // Single-line for coverage: tarpaulin attribute continuation
        let imports_map: HashMap<&str, &[ImportInfo]> = results
            .iter()
            .map(|r| {
                let key = result_to_graph_fp
                    .get(r.file_path.as_str())
                    .copied()
                    .unwrap_or(r.file_path.as_str());
                (key, r.imports.as_slice())
            })
            .collect();

        // Build fqn → file_path map from graph nodes (for source lookup).
        // Single-line for coverage: tarpaulin attribute continuation
        let fqn_to_file: HashMap<&str, &str> = graph
            .nodes
            .values()
            .filter_map(|n| {
                n.file_path
                    .as_deref()
                    .map(|fp| (n.qualified_name.as_str(), fp))
            })
            .collect();

        let mut resolved_edges = Vec::new();
        for edge in &mut graph.edges {
            // Only fix resolvable edge types.
            if !RESOLVABLE_EDGE_TYPES.contains(&edge.edge_type) {
                continue;
            }
            // Skip if target FQN already matches a real node (not dangling).
            if graph.nodes.contains_key(&edge.target) {
                continue;
            }
            // Get the source node's file path (relative, from graph).
            // Single-line for coverage: tarpaulin attribute continuation
            let Some(&source_file) = fqn_to_file.get(edge.source.as_str()) else {
                continue;
            };
            // Extract the type name from the dangling FQN (last component).
            let type_name = edge.target.rsplit('.').next().unwrap_or(&edge.target);
            // Retrieve imports for this file (imports_map keyed by relative
            // path, matching source_file).
            let imports = imports_map.get(source_file).copied().unwrap_or(&[]);
            // Translate relative source_file back to absolute for symbol table
            // lookup (file table keyed by result.file_path = absolute).
            // Single-line for coverage: tarpaulin attribute continuation
            let lookup_file = graph_to_result_fp
                .get(source_file)
                .copied()
                .unwrap_or(source_file);
            // Attempt resolution.
            // Single-line for coverage: tarpaulin attribute continuation
            let Some((resolved_qn, confidence, tier)) =
                self.resolve_type(lookup_file, type_name, imports)
            else {
                continue;
            };
            // Skip if the resolved FQN is the same as the current target
            // (no change needed — shouldn't happen since target is dangling,
            // but guard against edge cases where the FQN generator produced
            // the correct string but the node just isn't in the graph).
            if resolved_qn == edge.target {
                continue;
            }
            // Update the edge in-place.
            edge.target = resolved_qn;
            edge.confidence = confidence;
            edge.confidence_tier = tier;
            resolved_edges.push(edge.clone());
        }
        resolved_edges
    }
}

#[cfg(all(test, feature = "lang-rust", feature = "lang-python"))]
mod tests {
    use super::*;
    use crate::model::{Edge, EdgeType, Graph, Language, Node, NodeLabel};
    use crate::resolve::build_symbol_table;

    // FQN format: proj.{file_path_with_dots}.{name} (ADR-001: extension retained)
    // e.g. a.py + A → proj.a.py.A

    // --- helpers ---

    fn make_class(name: &str, file: &str, lang: Language) -> Node {
        let qn = format!("proj.{file}.{name}");
        Node::builder(NodeLabel::Class, name, qn)
            .file_path(file)
            .language(lang)
            .project("proj")
            .is_exported(true)
            .build()
    }

    fn make_function(name: &str, file: &str, lang: Language) -> Node {
        let qn = format!("proj.{file}.{name}");
        Node::builder(NodeLabel::Function, name, qn)
            .file_path(file)
            .language(lang)
            .project("proj")
            .build()
    }

    fn add_extends(graph: &mut Graph, source: &str, target: &str) {
        graph.add_edge(Edge::new(source, target, EdgeType::Extends, "proj"));
    }

    fn add_implements(graph: &mut Graph, source: &str, target: &str) {
        graph.add_edge(Edge::new(source, target, EdgeType::Implements, "proj"));
    }

    fn build_results_and_table(
        nodes: Vec<(Node, &str)>,
    ) -> (Vec<ExtractResult>, ProjectSymbolTable) {
        let mut results: std::collections::HashMap<&str, ExtractResult> =
            std::collections::HashMap::new();
        for (node, file) in nodes {
            let lang = node.language.unwrap_or(Language::Python);
            let result = results
                .entry(file)
                .or_insert_with(|| ExtractResult::new(file, lang));
            result.push_node(node);
        }
        let results_vec: Vec<ExtractResult> = results.into_values().collect();
        let table = build_symbol_table(&results_vec, "proj");
        (results_vec, table)
    }

    // --- resolve_type ---

    #[test]
    fn resolve_type_same_file() {
        let class = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class, "a.py")]);
        let resolver = TypeResolver::new(&table);
        let (qn, conf, tier) = resolver
            .resolve_type("a.py", "A", &[])
            .expect("should resolve");
        assert_eq!(qn, "proj.a.py.A");
        assert!((conf - 0.95).abs() < f32::EPSILON);
        assert_eq!(tier, ConfidenceTier::SameFile);
        let _ = &results;
    }

    #[test]
    fn resolve_type_import_scoped() {
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);
        let imports = vec![ImportInfo {
            source_file: "a".to_string(),
            imported_names: vec!["A".to_string()],
            line: 1,
        }];
        let resolver = TypeResolver::new(&table);
        let (qn, conf, tier) = resolver
            .resolve_type("b.py", "A", &imports)
            .expect("should resolve via import");
        assert_eq!(qn, "proj.a.py.A");
        assert!((conf - 0.90).abs() < f32::EPSILON);
        assert_eq!(tier, ConfidenceTier::ImportScoped);
        let _ = &results;
    }

    #[test]
    fn resolve_type_global_exported() {
        let class_a = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py")]);
        let resolver = TypeResolver::new(&table);
        // No imports — should fall through to project-level exported lookup.
        let (qn, conf, tier) = resolver
            .resolve_type("b.py", "A", &[])
            .expect("should resolve via project export");
        assert_eq!(qn, "proj.a.py.A");
        assert!((conf - 0.80).abs() < f32::EPSILON);
        assert_eq!(tier, ConfidenceTier::Global);
        let _ = &results;
    }

    #[test]
    fn resolve_type_not_found() {
        let (results, table) = build_results_and_table(vec![]);
        let resolver = TypeResolver::new(&table);
        assert!(resolver.resolve_type("a.py", "Nonexistent", &[]).is_none());
        let _ = &results;
    }

    // --- resolve_types: dangling Extends edge fix ---

    #[test]
    fn resolve_types_fixes_dangling_extends_edge() {
        // File a.py defines class A (FQN: proj.a.py.A).
        // File b.py defines class B (FQN: proj.b.py.B) that extends A.
        // The parse phase creates B -> proj.b.py.A (dangling, wrong file).
        // The TypeResolver should fix it to B -> proj.a.py.A.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Dangling edge: B extends proj.b.py.A (wrong — A is in a.py).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");

        // Add import to b.py: from a import A.
        let mut results_with_imports = results;
        for r in &mut results_with_imports {
            if r.file_path == "b.py" {
                r.imports.push(ImportInfo {
                    source_file: "a".to_string(),
                    imported_names: vec!["A".to_string()],
                    line: 1,
                });
            }
        }

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results_with_imports, &mut graph);

        assert_eq!(fixed.len(), 1);
        let edge = &graph.edges[0];
        assert_eq!(edge.target, "proj.a.py.A");
        assert!((edge.confidence - 0.90).abs() < f32::EPSILON);
        assert_eq!(edge.confidence_tier, ConfidenceTier::ImportScoped);
    }

    #[test]
    fn resolve_types_skips_non_dangling_edges() {
        // Edge target exists in the graph — should not be touched.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Non-dangling: target proj.a.py.A exists.
        add_extends(&mut graph, "proj.b.py.B", "proj.a.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty());
        // Edge unchanged.
        assert_eq!(graph.edges[0].target, "proj.a.py.A");
    }

    #[test]
    fn resolve_types_skips_non_resolvable_edge_types() {
        let func = make_function("foo", "a.py", Language::Python);
        let class = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(func, "a.py"), (class, "a.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_function("foo", "a.py", Language::Python));
        graph.add_node(make_class("A", "a.py", Language::Python));
        // Calls edge — not resolvable by TypeResolver.
        graph.add_edge(Edge::new(
            "proj.a.py.foo",
            "proj.a.py.Nonexistent",
            EdgeType::Calls,
            "proj",
        ));

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty());
    }

    #[test]
    fn resolve_types_fixes_dangling_implements_edge() {
        let trait_def = make_class("MyTrait", "a.rs", Language::Rust);
        let impl_class = make_class("MyImpl", "b.rs", Language::Rust);
        let (results, table) =
            build_results_and_table(vec![(trait_def, "a.rs"), (impl_class, "b.rs")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("MyTrait", "a.rs", Language::Rust));
        graph.add_node(make_class("MyImpl", "b.rs", Language::Rust));
        // Dangling: MyImpl implements proj.b.rs.MyTrait (wrong file).
        add_implements(&mut graph, "proj.b.rs.MyImpl", "proj.b.rs.MyTrait");

        let mut results_with_imports = results;
        for r in &mut results_with_imports {
            if r.file_path == "b.rs" {
                r.imports.push(ImportInfo {
                    source_file: "a".to_string(),
                    imported_names: vec!["MyTrait".to_string()],
                    line: 1,
                });
            }
        }

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results_with_imports, &mut graph);
        assert_eq!(fixed.len(), 1);
        assert_eq!(graph.edges[0].target, "proj.a.rs.MyTrait");
        assert_eq!(graph.edges[0].edge_type, EdgeType::Implements);
    }

    #[test]
    fn resolve_types_unresolvable_edge_left_unchanged() {
        // Dangling edge whose type name doesn't exist anywhere — left as-is.
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Dangling: target Nonexistent doesn't exist anywhere.
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty());
        // Edge unchanged (still dangling).
        assert_eq!(graph.edges[0].target, "proj.b.py.Nonexistent");
    }

    #[test]
    fn resolve_types_global_fallback_when_no_imports() {
        // Dangling edge with no imports — should use project-level exported
        // lookup.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Dangling: B extends proj.b.py.A (wrong — A is in a.py, no import).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert_eq!(fixed.len(), 1);
        assert_eq!(graph.edges[0].target, "proj.a.py.A");
        assert!((graph.edges[0].confidence - 0.80).abs() < f32::EPSILON);
        assert_eq!(graph.edges[0].confidence_tier, ConfidenceTier::Global);
    }

    #[test]
    fn resolve_types_skips_edge_when_source_node_missing() {
        // Source FQN not in graph — can't determine file path — skip.
        let class_a = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        // Source proj.unknown.X doesn't exist in graph.
        add_extends(&mut graph, "proj.unknown.X", "proj.unknown.Y");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty());
    }

    #[test]
    fn resolve_types_skips_when_resolved_equals_current_target() {
        // Dangling target whose type name doesn't exist in the symbol table
        // — resolve_type returns None, edge unchanged.
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("B", "b.py", Language::Python));
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty());
    }

    #[test]
    fn resolve_types_handles_path_format_mismatch() {
        // Regression test for the TypeResolver path mismatch bug.
        //
        // In production, `ExtractResult.file_path` is absolute (e.g.
        // "/home/user/proj/src/b.py") while graph nodes' `file_path` is
        // relative (e.g. "src/b.py") — normalized by ScopeResolutionPhase.
        // TypeResolver builds `imports_map` from `ExtractResult.file_path`
        // (absolute) but queries it with `fqn_to_file` values (relative),
        // causing `imports_map.get(source_file)` to return None.
        //
        // The fix: TypeResolver builds a bidirectional path mapping by
        // matching result nodes' `qualified_name` to graph nodes'
        // `qualified_name` (both are FQNs from the absolute path during
        // parse, so they match). This allows `imports_map` to be keyed by
        // the graph's relative paths and `lookup_in_file` to be queried
        // with the result's absolute path.
        //
        // FQNs are generated from the absolute path (as in production), so
        // they include all path segments: "/abs/path/a.py" → "proj.abs.path.a.py.A".
        // Graph nodes use the SAME FQN but have file_path normalized to relative.

        // Simulate production: extraction with ABSOLUTE file_path.
        let abs_a = "/abs/path/a.py";
        let abs_b = "/abs/path/b.py";
        // FQN segments from absolute path: ["abs", "path", "a.py"]
        let qn_a = "proj.abs.path.a.py.A";
        let qn_b = "proj.abs.path.b.py.B";

        let class_a = Node::builder(NodeLabel::Class, "A", qn_a)
            .file_path(abs_a)
            .language(Language::Python)
            .project("proj")
            .is_exported(true)
            .build();
        let class_b = Node::builder(NodeLabel::Class, "B", qn_b)
            .file_path(abs_b)
            .language(Language::Python)
            .project("proj")
            .build();

        let results = vec![
            {
                let mut r = ExtractResult::new(abs_a, Language::Python);
                r.push_node(class_a);
                r
            },
            {
                let mut r = ExtractResult::new(abs_b, Language::Python);
                r.push_node(class_b);
                r.imports.push(ImportInfo {
                    source_file: "a".to_string(),
                    imported_names: vec!["A".to_string()],
                    line: 1,
                });
                r
            },
        ];
        let table = build_symbol_table(&results, "proj");

        // Graph nodes: id set to FQN (simulating ScopeResolutionPhase
        // phases.rs:338-342 which sets g.id = node.qualified_name), and
        // file_path normalized to RELATIVE (phases.rs:344-346).
        let mut graph = Graph::new();
        let graph_a = Node::builder(NodeLabel::Class, "A", qn_a)
            .id(qn_a)
            .file_path("a.py")
            .language(Language::Python)
            .project("proj")
            .is_exported(true)
            .build();
        let graph_b = Node::builder(NodeLabel::Class, "B", qn_b)
            .id(qn_b)
            .file_path("b.py")
            .language(Language::Python)
            .project("proj")
            .build();
        graph.add_node(graph_a);
        graph.add_node(graph_b);
        // Dangling edge: B extends A (wrong file segment in FQN).
        graph.add_edge(Edge::new(
            qn_b,
            "proj.abs.path.b.py.A",
            EdgeType::Extends,
            "proj",
        ));

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);

        // With the path-mapping fix, import-scoped resolution (0.90) should
        // succeed despite the path-format mismatch.
        assert_eq!(fixed.len(), 1, "should fix the dangling edge");
        assert_eq!(graph.edges[0].target, qn_a, "should resolve to A's FQN");
        assert!(
            (graph.edges[0].confidence - 0.90).abs() < f32::EPSILON,
            "import-scoped (0.90) should succeed with path mapping; got {}",
            graph.edges[0].confidence
        );
        assert_eq!(graph.edges[0].confidence_tier, ConfidenceTier::ImportScoped);
    }

    #[test]
    fn resolve_types_skips_duplicate_file_path_in_results() {
        // Two ExtractResults with the same file_path — the second result
        // should be skipped by the `result_to_graph_fp.contains_key` guard.
        let class_a = make_class("A", "a.py", Language::Python);

        let mut result1 = ExtractResult::new("a.py", Language::Python);
        result1.push_node(class_a.clone());
        let mut result2 = ExtractResult::new("a.py", Language::Python);
        result2.push_node(class_a);

        let results = vec![result1, result2];
        let table = build_symbol_table(&results, "proj");

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        // Dangling edge to force resolve_types to iterate results.
        add_extends(&mut graph, "proj.a.py.A", "proj.a.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        // Edge is unresolvable → no fix, but duplicate path is exercised.
        assert!(fixed.is_empty(), "unresolvable edge → no fix");
    }

    #[test]
    fn resolve_types_fixes_dangling_uses_type_edge() {
        // UsesType is in RESOLVABLE_EDGE_TYPES but not previously tested.
        let type_a = make_class("TypeA", "a.py", Language::Python);
        let user_b = make_class("UserB", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(type_a, "a.py"), (user_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("TypeA", "a.py", Language::Python));
        graph.add_node(make_class("UserB", "b.py", Language::Python));
        // Dangling: UserB uses proj.b.py.TypeA (wrong file).
        graph.add_edge(Edge::new(
            "proj.b.py.UserB",
            "proj.b.py.TypeA",
            EdgeType::UsesType,
            "proj",
        ));

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert_eq!(fixed.len(), 1, "should fix the dangling UsesType edge");
        assert_eq!(graph.edges[0].target, "proj.a.py.TypeA");
        assert_eq!(graph.edges[0].edge_type, EdgeType::UsesType);
    }

    #[test]
    fn resolve_types_skips_when_resolved_qn_equals_current_target() {
        // Edge case: the type name resolves to a FQN that equals the current
        // (dangling) edge target. This happens when the symbol table has an
        // entry for the type but the graph doesn't have a node with that FQN.
        // Covers L248: `if resolved_qn == edge.target { continue; }`.
        //
        // Setup: class A is in the symbol table (via ExtractResult) but NOT
        // in the graph. Class B is in both. Both are in file b.py. Edge
        // B -> proj.b.py.A is dangling (A not in graph). resolve_type finds
        // A via file-level lookup (same file as B) → returns "proj.b.py.A"
        // which equals edge.target → L248 continue → no fix.
        let class_a = make_class("A", "b.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "b.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        // Only add B to the graph — A is in the symbol table but not the graph.
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Dangling edge: B extends proj.b.py.A (A is in symbol table but not graph).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        // resolved_qn ("proj.b.py.A") == edge.target ("proj.b.py.A") → skip.
        assert!(
            fixed.is_empty(),
            "resolved_qn == current target → no fix needed"
        );
        // Edge target unchanged.
        assert_eq!(graph.edges[0].target, "proj.b.py.A");
        // Confidence/tier unchanged (still default 1.0 / Global from Edge::new).
        assert!((graph.edges[0].confidence - 1.0).abs() < f32::EPSILON);
        assert_eq!(graph.edges[0].confidence_tier, ConfidenceTier::Global);
    }

    // --- Coverage gap tests: import-match-but-lookup-fails, graph node without file_path ---

    #[test]
    fn resolve_type_import_match_but_lookup_fails() {
        // Import references "MissingType" which is not in the symbol table.
        // is_imported=true but lookup("MissingType") returns empty → falls
        // through to project-level lookup, which also returns empty → None.
        let (results, table) = build_results_and_table(vec![]);
        let imports = vec![ImportInfo {
            source_file: "missing".to_string(),
            imported_names: vec!["MissingType".to_string()],
            line: 1,
        }];
        let resolver = TypeResolver::new(&table);
        assert!(
            resolver
                .resolve_type("a.py", "MissingType", &imports)
                .is_none(),
            "imported but undefined type should not resolve"
        );
        let _ = &results;
    }

    #[test]
    fn resolve_types_skips_graph_node_without_file_path() {
        // Graph node C has no file_path → path-mapping loop skips it (line 171
        // None branch). Resolution should still work for other nodes (B) that
        // DO have file_path.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let class_c = make_class("C", "c.py", Language::Python);

        let results = vec![
            {
                let mut r = ExtractResult::new("a.py", Language::Python);
                r.push_node(class_a);
                r
            },
            {
                let mut r = ExtractResult::new("b.py", Language::Python);
                r.push_node(class_b);
                r.imports.push(ImportInfo {
                    source_file: "a".to_string(),
                    imported_names: vec!["A".to_string()],
                    line: 1,
                });
                r
            },
            {
                let mut r = ExtractResult::new("c.py", Language::Python);
                r.push_node(class_c);
                r
            },
        ];
        let table = build_symbol_table(&results, "proj");

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // C has no file_path in the graph — triggers line 171 None branch.
        let c_no_fp = Node::builder(NodeLabel::Class, "C", "proj.c.py.C")
            .language(Language::Python)
            .project("proj")
            .build();
        graph.add_node(c_no_fp);
        // Dangling edge: B extends proj.b.py.A (wrong file in FQN).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        // B's edge should still be resolved despite C having no file_path.
        assert_eq!(fixed.len(), 1, "B's edge should be resolved");
        assert_eq!(graph.edges[0].target, "proj.a.py.A");
    }

    #[test]
    fn resolve_types_skips_result_node_not_in_graph() {
        // Cover `graph.nodes.get(&node.qualified_name)` None branch (line 170):
        // result "c.py" has node C, but C's FQN is not in the graph. The
        // path-mapping loop skips C and moves to the next node. Result "a.py"
        // has node A which IS in the graph, so the mapping is built for "a.py"
        // only. The dangling edge from A is still resolved.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_c = make_class("C", "c.py", Language::Python);

        let results = vec![
            {
                let mut r = ExtractResult::new("a.py", Language::Python);
                r.push_node(class_a);
                r
            },
            {
                let mut r = ExtractResult::new("c.py", Language::Python);
                r.push_node(class_c);
                r
            },
        ];
        let table = build_symbol_table(&results, "proj");

        let mut graph = Graph::new();
        // Only A is in the graph — C is in results but NOT in graph.
        graph.add_node(make_class("A", "a.py", Language::Python));
        // Dangling edge: A extends proj.a.py.Nonexistent.
        add_extends(&mut graph, "proj.a.py.A", "proj.a.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        // "Nonexistent" is not in the symbol table → unresolvable → no fix.
        assert!(fixed.is_empty(), "unresolvable edge → no fix");
    }

    #[test]
    fn resolve_types_lookup_file_fallback_when_no_path_mapping() {
        // Cover `graph_to_result_fp.get(source_file).copied().unwrap_or
        // (source_file)` fallback (line 237): when the source node's file_path
        // is not in graph_to_result_fp (no matching result), lookup_file
        // falls back to source_file itself.
        //
        // Setup: Source node B is in graph with file_path "b.py". There is
        // NO ExtractResult for "b.py". But result "a.py" has an exported
        // class A. B's dangling edge targets "proj.b.py.A" (wrong file).
        // Since no result matches B, no path mapping is built for "b.py".
        // lookup_file falls back to "b.py". File-level and import-based
        // lookups fail (no entries for "b.py"), but project-level exported
        // lookup finds A → resolves to "proj.a.py.A".
        let class_a = make_class("A", "a.py", Language::Python);
        let results = vec![{
            let mut r = ExtractResult::new("a.py", Language::Python);
            r.push_node(class_a);
            r
        }];
        let table = build_symbol_table(&results, "proj");

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        // B is in the graph but has NO corresponding ExtractResult.
        let b = Node::builder(NodeLabel::Class, "B", "proj.b.py.B")
            .file_path("b.py")
            .language(Language::Python)
            .project("proj")
            .build();
        graph.add_node(b);
        // Dangling edge: B extends proj.b.py.A (wrong file in FQN).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        // Project-level exported lookup should find A → resolve to proj.a.py.A.
        assert_eq!(fixed.len(), 1, "should resolve via global exported lookup");
        assert_eq!(graph.edges[0].target, "proj.a.py.A");
    }

    #[test]
    fn resolve_types_skips_non_resolvable_edge_type() {
        // Calls edges are NOT in RESOLVABLE_EDGE_TYPES — should be skipped
        // (line 215-217). Only Extends/Implements/UsesType are processed.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        graph.add_edge(Edge::new(
            "proj.b.py.B",
            "proj.b.py.A",
            EdgeType::Calls,
            "proj",
        ));

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty(), "Calls edge should not be resolved");
        assert_eq!(
            graph.edges[0].target, "proj.b.py.A",
            "edge target unchanged"
        );
    }

    #[test]
    fn resolve_types_skips_non_dangling_edge() {
        // Edge target already exists in graph → not dangling → skip
        // (line 219-221). Only dangling edges (target not in graph) are fixed.
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // B extends A — A exists in graph → not dangling → skip.
        graph.add_edge(Edge::new(
            "proj.b.py.B",
            "proj.a.py.A",
            EdgeType::Extends,
            "proj",
        ));

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty(), "non-dangling edge should be skipped");
        assert_eq!(
            graph.edges[0].target, "proj.a.py.A",
            "edge target unchanged"
        );
        assert!(
            (graph.edges[0].confidence - 1.0).abs() < f32::EPSILON,
            "confidence unchanged"
        );
    }

    #[test]
    fn resolve_types_skips_edge_when_source_has_no_file_path() {
        // Source node exists in graph but has no file_path →
        // fqn_to_file.get returns None → skip (line 224-226).
        let class_a = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        // B exists in graph but has NO file_path.
        let b_no_fp = Node::builder(NodeLabel::Class, "B", "proj.b.py.B")
            .language(Language::Python)
            .project("proj")
            .build();
        graph.add_node(b_no_fp);
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty(), "source with no file_path → skip");
    }

    // --- resolve_type: imported but not found (is_imported=true, lookup empty) ---

    #[test]
    fn resolve_type_imported_but_not_found_returns_none() {
        // Type name appears in imports, but is not in the symbol table at all
        // (external dependency). `lookup` returns empty → falls through to
        // `lookup_exported` which also returns empty → None.
        let (results, table) = build_results_and_table(vec![]);
        let imports = vec![ImportInfo {
            source_file: "external".to_string(),
            imported_names: vec!["ExternalType".to_string()],
            line: 1,
        }];
        let resolver = TypeResolver::new(&table);
        assert!(
            resolver
                .resolve_type("a.py", "ExternalType", &imports)
                .is_none(),
            "imported type not in symbol table should return None"
        );
        let _ = &results;
    }

    // --- resolve_types: resolve_type returns None → edge skipped ---

    #[test]
    fn resolve_types_skips_when_type_not_found_in_symbol_table() {
        // Dangling Extends edge where the type name is NOT in the symbol table.
        // resolve_type returns None → edge is skipped (line 241-245).
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("B", "b.py", Language::Python));
        // B extends TrulyNonexistent (not in symbol table at all).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.TruelyNonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(
            fixed.is_empty(),
            "edge with unresolvable type should be skipped: {:?}",
            fixed
        );
        // Edge target should be unchanged.
        assert_eq!(
            graph.edges[0].target, "proj.b.py.TruelyNonexistent",
            "unresolvable edge target should remain unchanged"
        );
    }

    // --- resolve_type: imported and found via project-level (import true, lookup empty, exported found) ---

    #[test]
    fn resolve_type_imported_but_found_via_project_export() {
        // Type is in imports AND is an exported symbol. `lookup` might find it
        // directly (since it's in the symbol table), but this test verifies the
        // import path is exercised when the type is also project-exported.
        let class_a = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py")]);
        let imports = vec![ImportInfo {
            source_file: "a".to_string(),
            imported_names: vec!["A".to_string()],
            line: 1,
        }];
        let resolver = TypeResolver::new(&table);
        // A is in the symbol table, so lookup should find it via import path.
        let result = resolver.resolve_type("b.py", "A", &imports);
        assert!(result.is_some(), "imported type should be found");
        let (qn, _conf, tier) = result.unwrap();
        assert_eq!(qn, "proj.a.py.A");
        // Since A is in the symbol table, lookup finds it → ImportScoped.
        assert_eq!(tier, ConfidenceTier::ImportScoped);
        let _ = &results;
    }

    // --- resolve_types: file-level (SameFile) resolution where edge IS fixed ---

    #[test]
    fn resolve_types_fixes_edge_via_same_file_resolution() {
        // Dangling edge resolved via file-level lookup (SameFile confidence).
        // Type A is in the same file as source B, but the edge target FQN has
        // the wrong file path (proj.a.py.A instead of proj.b.py.A). Since
        // proj.a.py.A is NOT in the graph, the edge is dangling. resolve_type
        // finds A via file-level lookup → returns proj.b.py.A (different from
        // edge.target) → edge is fixed with SameFile confidence.
        let class_a = make_class("A", "b.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "b.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "b.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Dangling: target proj.a.py.A not in graph (A is at proj.b.py.A).
        add_extends(&mut graph, "proj.b.py.B", "proj.a.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert_eq!(fixed.len(), 1, "should fix via same-file lookup");
        assert_eq!(graph.edges[0].target, "proj.b.py.A");
        assert!(
            (graph.edges[0].confidence - 0.95).abs() < f32::EPSILON,
            "SameFile confidence should be 0.95"
        );
        assert_eq!(graph.edges[0].confidence_tier, ConfidenceTier::SameFile);
    }

    // --- resolve_types: empty results ---

    #[test]
    fn resolve_types_with_empty_results_skips_all_edges() {
        // Empty results → no path mapping, no imports_map, fqn_to_file still
        // built from graph nodes. Edges with source in graph can be processed
        // but resolve_type will fail (empty symbol table) → no fixes.
        let class_b = make_class("B", "b.py", Language::Python);
        let results: Vec<ExtractResult> = vec![];
        let table = build_symbol_table(&results, "proj");

        let mut graph = Graph::new();
        graph.add_node(class_b);
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty(), "empty results → no resolution possible");
    }

    // --- resolve_types: multiple dangling edges ---

    #[test]
    fn resolve_types_fixes_multiple_dangling_edges() {
        // Multiple dangling edges in the same graph — some resolvable, some
        // not. Verifies the edge iteration loop accumulates resolved_edges
        // correctly (line 257 push for each fixed edge).
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let class_c = make_class("C", "c.py", Language::Python);
        let (results, table) = build_results_and_table(vec![
            (class_a, "a.py"),
            (class_b, "b.py"),
            (class_c, "c.py"),
        ]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        graph.add_node(make_class("C", "c.py", Language::Python));
        // Edge 1: B extends proj.b.py.A (dangling, resolvable via global).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");
        // Edge 2: C extends proj.c.py.Nonexistent (dangling, unresolvable).
        add_extends(&mut graph, "proj.c.py.C", "proj.c.py.Nonexistent");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert_eq!(fixed.len(), 1, "only one edge should be fixed");
        assert_eq!(fixed[0].source, "proj.b.py.B");
        assert_eq!(fixed[0].target, "proj.a.py.A");
    }

    // --- resolve_types: mixed dangling and non-dangling edges ---

    #[test]
    fn resolve_types_mixed_dangling_and_non_dangling_edges() {
        // Graph with both dangling and non-dangling edges — only dangling
        // edges should be processed (line 219-221 skip for non-dangling).
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py"), (class_b, "b.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        // Edge 1: non-dangling (target exists in graph).
        graph.add_edge(Edge::new(
            "proj.b.py.B",
            "proj.a.py.A",
            EdgeType::Extends,
            "proj",
        ));
        // Edge 2: dangling (target not in graph, resolvable via global).
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert_eq!(fixed.len(), 1, "only the dangling edge should be fixed");
        // First edge (non-dangling) should be unchanged.
        assert_eq!(graph.edges[0].target, "proj.a.py.A");
        // Second edge (dangling) should be fixed.
        assert_eq!(graph.edges[1].target, "proj.a.py.A");
    }

    // --- resolve_types: graph with no edges ---

    #[test]
    fn resolve_types_with_no_edges_returns_empty() {
        // Graph with nodes but no edges → edge iteration loop body never
        // executes → resolved_edges is empty.
        let class_a = make_class("A", "a.py", Language::Python);
        let (results, table) = build_results_and_table(vec![(class_a, "a.py")]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert!(fixed.is_empty(), "no edges → no fixes");
    }

    // --- resolve_types: multiple resolvable edges accumulate in order ---

    #[test]
    fn resolve_types_multiple_resolved_edges_preserve_insertion_order() {
        // Two dangling edges, both resolvable → both fixed and pushed to
        // resolved_edges in iteration order (line 257).
        let class_a = make_class("A", "a.py", Language::Python);
        let class_b = make_class("B", "b.py", Language::Python);
        let class_c = make_class("C", "c.py", Language::Python);
        let (results, table) = build_results_and_table(vec![
            (class_a, "a.py"),
            (class_b, "b.py"),
            (class_c, "c.py"),
        ]);

        let mut graph = Graph::new();
        graph.add_node(make_class("A", "a.py", Language::Python));
        graph.add_node(make_class("B", "b.py", Language::Python));
        graph.add_node(make_class("C", "c.py", Language::Python));
        // Both edges are dangling and resolvable via global exported lookup.
        add_extends(&mut graph, "proj.b.py.B", "proj.b.py.A");
        add_extends(&mut graph, "proj.c.py.C", "proj.c.py.A");

        let resolver = TypeResolver::new(&table);
        let fixed = resolver.resolve_types(&results, &mut graph);
        assert_eq!(fixed.len(), 2, "both edges should be fixed");
        // Verify insertion order matches edge iteration order.
        assert_eq!(fixed[0].source, "proj.b.py.B");
        assert_eq!(fixed[1].source, "proj.c.py.C");
        // Both should resolve to the same target (proj.a.py.A).
        assert_eq!(fixed[0].target, "proj.a.py.A");
        assert_eq!(fixed[1].target, "proj.a.py.A");
    }
}