code2graph 0.0.0-beta.17

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
// SPDX-License-Identifier: Apache-2.0

//! Tier A resolver: fast, broad, name/scope based.
//!
//! Builds a `leaf-name → definitions` table across all files, attributes each
//! reference to the symbol whose span encloses it (the caller), and links it to
//! every definition sharing the callee's name. An ambiguous name that fans out
//! to several definitions tags each edge [`Confidence::NameOnly`]; a name with a
//! single global candidate is tagged [`Confidence::Scoped`]. Additionally, an
//! import reference whose `from_path` uniquely matches exactly one candidate's
//! module namespace suffix is tagged [`Confidence::Scoped`] while all other
//! fan-out edges for that reference stay [`Confidence::NameOnly`]. This is the
//! recall-first baseline that works for every language without per-language
//! binding rules — the confidence varies, edges are otherwise preserved. The one
//! exception is scalability: a name shared by more than `MAX_NAME_FANOUT`
//! definitions is hopelessly ambiguous, so its combinatorial cross-product is
//! dropped (keeping any import-disambiguated survivor) — see `MAX_NAME_FANOUT`.
//! A precise resolver tags its edges [`Confidence::Exact`] instead.
//!
//! It returns neutral [`Edge`]s and never writes to storage.

use std::collections::HashMap;

use crate::graph::types::{
    CodeGraph, Confidence, Edge, FileFacts, Provenance, RefRole, Symbol, SymbolKind,
};

use super::Resolver;
use super::{
    dedup_files_last_wins, enclosing_symbol_index, namespaces_end_with, normalize_from_path,
    retain_first_symbol_by_id,
};

/// Fan-out cap: when a leaf name is shared by more than this many definitions,
/// a bare name match conveys no useful recall — a call to `new`/`get`/`id` in a
/// large workspace can match thousands of definitions, and emitting an edge to
/// every one is `O(refs × defs)` combinatorial noise (tens of millions of edges
/// on a real multi-crate codebase), not signal. Above the cap we keep only an
/// import-path-disambiguated survivor (still precise) and otherwise emit nothing
/// for that reference. Genuine small-candidate recall (the common case) is
/// unaffected; only hopelessly-ambiguous hot names are dropped.
pub(crate) const MAX_NAME_FANOUT: usize = 64;

/// Name-table resolver. See module docs.
#[derive(Debug, Default, Clone, Copy)]
pub struct SymbolTableResolver;

fn is_type_definition(kind: SymbolKind) -> bool {
    matches!(
        kind,
        SymbolKind::Struct
            | SymbolKind::Enum
            | SymbolKind::Trait
            | SymbolKind::Class
            | SymbolKind::Interface
            | SymbolKind::TypeAlias
            | SymbolKind::Table
            | SymbolKind::View
    )
}

impl Resolver for SymbolTableResolver {
    fn resolve(&self, files: &[FileFacts]) -> crate::Result<CodeGraph> {
        crate::validate_file_facts(files)?;
        // A file path identifies a unique source: on duplicate `file` keys, keep
        // the LAST version (matching the IncrementalGraph store's upsert). Bind
        // once so symbol collection and the reference loop below iterate the same
        // deduped set — otherwise duplicate keys would emit duplicate symbol
        // identities and diverge from the incremental store.
        let files = dedup_files_last_wins(files);

        // leaf name → indices into the flattened symbol list
        let mut symbols: Vec<Symbol> = files
            .iter()
            .flat_map(|f| f.symbols.iter().cloned())
            .collect();
        // A CodeGraph must contain exactly one node per SymbolId: a Go/Java
        // package can span multiple files, each emitting the same
        // namespace-only package symbol. Keep the first occurrence. This must
        // happen before any index map below is built (those maps index into
        // `symbols` by position).
        retain_first_symbol_by_id(&mut symbols);

        // Ordinary references and module references have disjoint target domains.
        // This prevents a file/module symbol from polluting callable/value lookup.
        let mut by_name: HashMap<&str, Vec<usize>> = HashMap::new();
        // Type references may legitimately name a module/type-like container.
        let mut type_by_name: HashMap<&str, Vec<usize>> = HashMap::new();
        let mut modules_by_name: HashMap<&str, Vec<usize>> = HashMap::new();
        // Per-file symbol index for caller attribution (span containment).
        let mut by_file: HashMap<&str, Vec<usize>> = HashMap::new();
        for (i, s) in symbols.iter().enumerate() {
            if s.kind == SymbolKind::Module {
                modules_by_name.entry(s.name.as_str()).or_default().push(i);
                type_by_name.entry(s.name.as_str()).or_default().push(i);
            } else if let Some(name) = s.id.leaf_name() {
                by_name.entry(name).or_default().push(i);
                type_by_name.entry(name).or_default().push(i);
            }
            by_file.entry(s.file.as_str()).or_default().push(i);
        }

        let mut edges: Vec<Edge> = Vec::new();
        for f in files.iter().copied() {
            let file_syms = by_file.get(f.file.as_str());
            for r in &f.references {
                // Relationship references name their subject explicitly because
                // identity-less containers (such as Rust impl blocks) are not
                // symbols. Ordinary references retain span-based caller attribution.
                let explicit_subject = r
                    .qualifier
                    .as_deref()
                    .filter(|_| r.role == RefRole::IsImplementation)
                    .and_then(|subject| type_by_name.get(subject))
                    .and_then(|candidates| {
                        let local: Vec<_> = candidates
                            .iter()
                            .copied()
                            .filter(|&index| symbols[index].file == f.file)
                            .collect();
                        match local.as_slice() {
                            [candidate] => Some(*candidate),
                            [] if candidates.len() == 1 => candidates.first().copied(),
                            _ => None,
                        }
                    });
                let from_idx = if let Some(candidate) = explicit_subject {
                    candidate
                } else {
                    let Some(candidate) = file_syms
                        .and_then(|idxs| enclosing_symbol_index(&symbols, idxs, r.occ.byte))
                    else {
                        continue; // reference not inside any extracted symbol — unattributable
                    };
                    candidate
                };

                let targets = match r.role {
                    RefRole::ModuleRef => modules_by_name.get(r.name.as_str()),
                    RefRole::TypeRef => type_by_name.get(r.name.as_str()),
                    _ => by_name.get(r.name.as_str()),
                };
                let Some(targets) = targets else {
                    continue; // unresolved: no definition in this reference's target domain
                };

                // Count non-self candidates and compute import-path
                // disambiguation (Win-2) in a single pass over `targets`.
                // `import_segs` is precomputed so the inner loop stays cheap.
                let import_segs: Vec<&str> = if r.role == RefRole::Import {
                    r.from_path
                        .as_deref()
                        .map_or_else(Vec::new, normalize_from_path)
                } else {
                    Vec::new()
                };
                let mut non_self_count: usize = 0;
                let mut import_match_first: Option<usize> = None;
                let mut import_match_second: Option<usize> = None;
                for &i in targets.iter() {
                    if i == from_idx
                        || (r.role == RefRole::TypeRef
                            && r.type_ref_ctx.is_some()
                            && !is_type_definition(symbols[i].kind))
                    {
                        continue;
                    }
                    non_self_count += 1;
                    if !import_segs.is_empty() && namespaces_end_with(&symbols[i].id, &import_segs)
                    {
                        if import_match_first.is_none() {
                            import_match_first = Some(i);
                        } else {
                            import_match_second = Some(i);
                        }
                    }
                }
                // Promote only when exactly one candidate matched the import path.
                let import_bound: Option<usize> = if import_match_second.is_none() {
                    import_match_first
                } else {
                    None
                };

                // Fan-out cap: a name shared by too many definitions is
                // hopelessly ambiguous — the full cross-product is combinatorial
                // noise, not recall (see `MAX_NAME_FANOUT`). Keep only an
                // import-disambiguated survivor (still precise) and drop the rest.
                if non_self_count > MAX_NAME_FANOUT {
                    if let Some(bound) = import_bound {
                        edges.push(Edge {
                            from: symbols[from_idx].id.clone(),
                            to: symbols[bound].id.clone(),
                            role: r.role,
                            confidence: Confidence::Scoped,
                            provenance: Provenance::SymbolTable,
                            occ: r.occ.clone(),
                        });
                    }
                    continue;
                }

                for &to_idx in targets.iter().filter(|&&i| {
                    i != from_idx
                        && !(r.role == RefRole::TypeRef
                            && r.type_ref_ctx.is_some()
                            && !is_type_definition(symbols[i].kind))
                }) {
                    // Decide per-edge confidence and provenance:
                    // - A reference derived from a secondary artifact embedded in
                    //   source (e.g. SQL inside a code string) is attributed to
                    //   Provenance::CrossArtifact and forced to Confidence::NameOnly
                    //   — a bare embedded name is inherently ambiguous, never
                    //   type/scope-precise, regardless of candidate count.
                    // - Otherwise, if Win-2 fired (import_bound == Some(to_idx)):
                    //   Scoped for the matched target, NameOnly for all others.
                    // - Otherwise fall back to Win-1: Scoped iff unique candidate.
                    let (confidence, provenance) = if r.cross_artifact {
                        (Confidence::NameOnly, Provenance::CrossArtifact)
                    } else if import_bound == Some(to_idx) {
                        (Confidence::Scoped, Provenance::SymbolTable)
                    } else if import_bound.is_some() {
                        // Win-2 fired but this is not the matched target.
                        (Confidence::NameOnly, Provenance::SymbolTable)
                    } else if non_self_count == 1 {
                        (Confidence::Scoped, Provenance::SymbolTable)
                    } else {
                        (Confidence::NameOnly, Provenance::SymbolTable)
                    };

                    edges.push(Edge {
                        from: symbols[from_idx].id.clone(),
                        to: symbols[to_idx].id.clone(),
                        role: r.role,
                        confidence,
                        provenance,
                        occ: r.occ.clone(),
                    });
                }
            }
        }

        Ok(CodeGraph { symbols, edges })
    }
}

#[cfg(all(
    test,
    any(
        feature = "rust",
        feature = "python",
        feature = "java",
        feature = "sql",
        feature = "hcl"
    )
))]
mod tests {
    use super::*;
    #[cfg(any(
        feature = "rust",
        feature = "python",
        feature = "java",
        feature = "sql",
        feature = "hcl"
    ))]
    use crate::extract::Extractor;
    #[cfg(feature = "java")]
    use crate::extract::JavaExtractor;
    #[cfg(feature = "rust")]
    use crate::extract::RustExtractor;

    /// A call whose leaf name is shared by MORE than `MAX_NAME_FANOUT`
    /// definitions is hopelessly ambiguous — the resolver drops it rather than
    /// emitting the combinatorial cross-product (the fix for the `O(refs × defs)`
    /// memory blowup on large real codebases).
    #[cfg(feature = "rust")]
    #[test]
    fn fan_out_beyond_cap_is_dropped() {
        let mut files: Vec<_> = (0..=MAX_NAME_FANOUT)
            .map(|i| {
                RustExtractor
                    .extract("pub fn hot() {}", &format!("src/def{i}.rs"))
                    .unwrap()
            })
            .collect();
        files.push(
            RustExtractor
                .extract("pub fn caller() { hot() }", "src/caller.rs")
                .unwrap(),
        );
        let graph = SymbolTableResolver.resolve(&files).unwrap();
        let call_edges = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Call)
            .count();
        assert_eq!(
            call_edges, 0,
            "a call whose name has > MAX_NAME_FANOUT ({MAX_NAME_FANOUT}) defs must be dropped, got {call_edges}"
        );
    }

    /// At or below the cap, the recall-first fan-out is preserved.
    #[cfg(feature = "rust")]
    #[test]
    fn fan_out_at_cap_is_kept() {
        let mut files: Vec<_> = (0..MAX_NAME_FANOUT)
            .map(|i| {
                RustExtractor
                    .extract("pub fn hot() {}", &format!("src/def{i}.rs"))
                    .unwrap()
            })
            .collect();
        files.push(
            RustExtractor
                .extract("pub fn caller() { hot() }", "src/caller.rs")
                .unwrap(),
        );
        let graph = SymbolTableResolver.resolve(&files).unwrap();
        let call_edges = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Call)
            .count();
        assert_eq!(
            call_edges, MAX_NAME_FANOUT,
            "a call at the cap must still fan out to all defs"
        );
    }

    #[cfg(feature = "rust")]
    #[test]
    fn resolves_cross_file_call() {
        let lib = RustExtractor
            .extract("pub fn helper() -> u32 { 1 }", "src/util.rs")
            .unwrap();
        let main = RustExtractor
            .extract("pub fn run() -> u32 { helper() }", "src/main.rs")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[lib, main]).unwrap();

        // one Call edge: run → helper
        let calls: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Call)
            .collect();
        assert_eq!(calls.len(), 1);
        let e = calls[0];
        assert!(e.from.to_scip_string().ends_with("run()."));
        assert!(e.to.to_scip_string().ends_with("util/helper()."));
        assert_eq!(e.confidence, Confidence::Scoped);
        // Provenance records the deriving analysis, independent of confidence.
        assert_eq!(e.provenance, Provenance::SymbolTable);
        assert_eq!(e.occ.file, "src/main.rs");
    }

    #[cfg(feature = "rust")]
    #[test]
    fn unresolved_calls_produce_no_edge() {
        let main = RustExtractor
            .extract("pub fn run() { nonexistent_fn() }", "src/main.rs")
            .unwrap();
        let graph = SymbolTableResolver.resolve(&[main]).unwrap();
        assert!(graph.edges.is_empty());
    }

    #[cfg(feature = "java")]
    #[test]
    fn resolves_cross_file_inheritance() {
        let base = JavaExtractor
            .extract("package p; public class Base {}", "src/p/Base.java")
            .unwrap();
        let sub = JavaExtractor
            .extract(
                "package p; public class Sub extends Base {}",
                "src/p/Sub.java",
            )
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[base, sub]).unwrap();

        // exactly one IsImplementation edge: Sub → Base
        let inherits: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::IsImplementation)
            .collect();
        assert_eq!(inherits.len(), 1);
        let e = inherits[0];
        assert!(
            e.from.to_scip_string().ends_with("p/Sub#"),
            "from was: {}",
            e.from.to_scip_string()
        );
        assert!(
            e.to.to_scip_string().ends_with("p/Base#"),
            "to was: {}",
            e.to.to_scip_string()
        );
        assert_eq!(e.confidence, Confidence::Scoped);
        assert_eq!(e.occ.file, "src/p/Sub.java");
    }

    #[cfg(feature = "rust")]
    #[test]
    fn resolves_cross_file_rust_trait_impl_inheritance() {
        // File A defines the trait.
        let greet = RustExtractor
            .extract("pub trait Greet {}", "src/greet.rs")
            .unwrap();
        // File B defines the struct + its trait impl.
        let p = RustExtractor
            .extract("pub struct P;\nimpl Greet for P {}", "src/p.rs")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[greet, p]).unwrap();

        // Exactly one IsImplementation edge: P → Greet
        let inherits: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::IsImplementation)
            .collect();
        assert_eq!(
            inherits.len(),
            1,
            "expected 1 IsImplementation edge, got {:?}",
            inherits.len()
        );
        let e = inherits[0];
        assert!(
            e.from.to_scip_string().ends_with("p/P#") || e.from.to_scip_string().ends_with("P#"),
            "unexpected from: {}",
            e.from.to_scip_string()
        );
        assert!(
            e.to.to_scip_string().ends_with("greet/Greet#")
                || e.to.to_scip_string().ends_with("Greet#"),
            "unexpected to: {}",
            e.to.to_scip_string()
        );
        assert_eq!(e.confidence, Confidence::Scoped);
        assert_eq!(e.occ.file, "src/p.rs");
    }

    #[cfg(feature = "rust")]
    #[test]
    fn rust_trait_impl_subject_prefers_the_definition_in_its_file() {
        let trait_facts = RustExtractor
            .extract("pub trait Draw {}", "src/draw.rs")
            .unwrap();
        let implemented = RustExtractor
            .extract("pub struct Point; impl Draw for Point {}", "src/a.rs")
            .unwrap();
        let same_named = RustExtractor
            .extract("pub struct Point;", "src/b.rs")
            .unwrap();

        let graph = SymbolTableResolver
            .resolve(&[trait_facts, implemented, same_named])
            .unwrap();
        let implementation = graph
            .edges
            .iter()
            .find(|edge| edge.role == RefRole::IsImplementation)
            .expect("implementation edge");
        assert!(implementation.from.to_scip_string().ends_with("a/Point#"));
    }

    #[cfg(feature = "python")]
    #[test]
    fn resolves_cross_file_python_import_edge() {
        use crate::extract::PythonExtractor;

        // File A: src/pkg/models.py defines class Config.
        let a = PythonExtractor
            .extract("class Config:\n    pass\n", "src/pkg/models.py")
            .unwrap();

        // File B: src/app.py imports Config from pkg.models.
        let b = PythonExtractor
            .extract("from pkg.models import Config\n", "src/app.py")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b]).unwrap();

        // Exactly one Import edge: module(app) → Config
        let imports: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Import)
            .collect();
        assert_eq!(
            imports.len(),
            1,
            "expected one Import edge, got {:?}",
            imports.len()
        );
        let e = imports[0];
        assert!(
            e.from.to_scip_string().ends_with("app/"),
            "from (module) was: {}",
            e.from.to_scip_string()
        );
        assert!(
            e.to.to_scip_string().ends_with("Config#"),
            "to was: {}",
            e.to.to_scip_string()
        );
        assert_eq!(e.confidence, Confidence::Scoped);
    }

    #[cfg(feature = "rust")]
    #[test]
    fn resolves_import_edge_from_module() {
        use crate::graph::types::{Occurrence, Reference};

        // File A defines `Config`.
        let a = RustExtractor
            .extract("pub struct Config {}", "src/conf.rs")
            .unwrap();

        // File B's module imports it. The extractor gives B a module symbol
        // spanning the whole file; we inject an Import reference whose byte sits
        // in the leading comment — inside the module span but not inside any
        // smaller symbol — so the resolver attributes the edge's source to the
        // module, exactly as a real top-level `use`/`import` would.
        let mut b = RustExtractor
            .extract("// uses Config\npub fn run() {}", "src/app.rs")
            .unwrap();
        b.references.push(Reference {
            name: "Config".to_owned(),
            occ: Occurrence {
                file: "src/app.rs".to_owned(),
                line: 1,
                col: 0,
                byte: 0,
            },
            role: RefRole::Import,
            source_module: None,
            from_path: None,
            is_reexport: false,
            imported_name: None,
            qualifier: None,
            scope: None,
            type_ref_ctx: None,
            cross_artifact: false,
            self_receiver: false,
        });

        let graph = SymbolTableResolver.resolve(&[a, b]).unwrap();

        // Exactly one Import edge: module(app) → Config
        let imports: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Import)
            .collect();
        assert_eq!(imports.len(), 1, "expected one Import edge");
        let e = imports[0];
        assert!(
            e.from.to_scip_string().ends_with("app/"),
            "from (module) was: {}",
            e.from.to_scip_string()
        );
        assert!(
            e.to.to_scip_string().ends_with("conf/Config#"),
            "to was: {}",
            e.to.to_scip_string()
        );
        assert_eq!(e.confidence, Confidence::Scoped);
    }

    #[cfg(feature = "rust")]
    #[test]
    fn ambiguous_name_fan_out_stays_name_only() {
        // Two files each define a function with the same leaf name "process".
        // A third file calls "process" — the resolver must emit edges to BOTH
        // definitions and tag them NameOnly (ambiguous fan-out, not Scoped).
        let a = RustExtractor
            .extract("pub fn process() -> u32 { 1 }", "src/mod_a.rs")
            .unwrap();
        let b = RustExtractor
            .extract("pub fn process() -> u32 { 2 }", "src/mod_b.rs")
            .unwrap();
        let caller = RustExtractor
            .extract("pub fn run() { process() }", "src/main.rs")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b, caller]).unwrap();

        // Filter to Call edges only (exclude any IsImplementation/Import noise).
        let calls: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Call)
            .collect();

        // Recall preserved: both definitions must be reachable.
        assert_eq!(
            calls.len(),
            2,
            "expected 2 fan-out edges, got {}",
            calls.len()
        );

        // Every fan-out edge must stay NameOnly — not promoted to Scoped.
        for e in &calls {
            assert_eq!(
                e.confidence,
                Confidence::NameOnly,
                "ambiguous fan-out edge should be NameOnly, got {:?}",
                e.confidence
            );
        }

        // Both targets should be the two "process" definitions.
        let targets: std::collections::HashSet<String> =
            calls.iter().map(|e| e.to.to_scip_string()).collect();
        assert!(
            targets.iter().any(|s| s.ends_with("mod_a/process().")),
            "missing mod_a target; got: {:?}",
            targets
        );
        assert!(
            targets.iter().any(|s| s.ends_with("mod_b/process().")),
            "missing mod_b target; got: {:?}",
            targets
        );
    }

    // ── Win-2: import-path disambiguation ────────────────────────────────────

    /// Two classes named `Config` in different Java packages; importer of one
    /// package gets `Scoped` for the matching def and `NameOnly` for the other.
    ///
    /// We use Java because its `package` declaration drives namespace derivation
    /// cleanly: `package com.example;` → namespaces `["com","example"]`, and
    /// `import com.example.Config` → `from_path = "com.example"`.  The suffix
    /// match is exact and unambiguous.
    #[cfg(feature = "java")]
    #[test]
    fn import_disambiguation_promotes_matching_package() {
        // File 1: com.example package defines Config.
        let a = JavaExtractor
            .extract(
                "package com.example;\npublic class Config {}",
                "src/com/example/Config.java",
            )
            .unwrap();

        // File 2: com.other package also defines Config (the decoy).
        let b = JavaExtractor
            .extract(
                "package com.other;\npublic class Config {}",
                "src/com/other/Config.java",
            )
            .unwrap();

        // File 3: imports Config specifically from com.example.
        let c = JavaExtractor
            .extract(
                "package app;\nimport com.example.Config;\npublic class App {}",
                "src/app/App.java",
            )
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b, c]).unwrap();

        let imports: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Import)
            .collect();

        // Recall preserved: BOTH Config defs must produce an edge.
        assert_eq!(
            imports.len(),
            2,
            "expected 2 Import edges (recall preserved), got {}: {:?}",
            imports.len(),
            imports
                .iter()
                .map(|e| e.to.to_scip_string())
                .collect::<Vec<_>>()
        );

        // Find the two edges by their SCIP `to` strings.
        let example_edge = imports
            .iter()
            .find(|e| e.to.to_scip_string().contains("com/example/Config"))
            .expect("expected edge to com.example.Config");
        let other_edge = imports
            .iter()
            .find(|e| e.to.to_scip_string().contains("com/other/Config"))
            .expect("expected edge to com.other.Config");

        // The matched package gets Scoped; the decoy stays NameOnly.
        assert_eq!(
            example_edge.confidence,
            Confidence::Scoped,
            "com.example.Config should be Scoped (from_path match), got {:?}",
            example_edge.confidence
        );
        assert_eq!(
            other_edge.confidence,
            Confidence::NameOnly,
            "com.other.Config should be NameOnly (no from_path match), got {:?}",
            other_edge.confidence
        );
    }

    /// Negative: `from_path` that matches no candidate's namespace leaves all
    /// edges at their existing Win-1 confidence (NameOnly for ambiguous fan-out).
    #[cfg(feature = "java")]
    #[test]
    fn import_disambiguation_no_match_leaves_fan_out_name_only() {
        // Two classes named `Config` in unrelated packages.
        let a = JavaExtractor
            .extract(
                "package com.alpha;\npublic class Config {}",
                "src/com/alpha/Config.java",
            )
            .unwrap();
        let b = JavaExtractor
            .extract(
                "package com.beta;\npublic class Config {}",
                "src/com/beta/Config.java",
            )
            .unwrap();

        // Importer whose from_path matches neither package ("com.gamma" is external).
        let c = JavaExtractor
            .extract(
                "package app;\nimport com.gamma.Config;\npublic class App {}",
                "src/app/App.java",
            )
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b, c]).unwrap();

        let imports: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Import)
            .collect();

        // Recall preserved: still two edges even though no path matches.
        assert_eq!(
            imports.len(),
            2,
            "expected 2 Import edges, got {}",
            imports.len()
        );

        // No promotion — both stay NameOnly (Win-1: non-unique candidate).
        for e in &imports {
            assert_eq!(
                e.confidence,
                Confidence::NameOnly,
                "unmatched import fan-out should stay NameOnly, got {:?} for {}",
                e.confidence,
                e.to.to_scip_string()
            );
        }
    }

    #[cfg(feature = "rust")]
    #[test]
    fn typeref_produces_typeref_edge() {
        // File A defines `Config`; file B uses it as a parameter type.
        // Tier-A resolves cross-file by name: one global candidate → Scoped (Win-1).
        // The key assertion is that `r.role` is copied onto the edge as TypeRef.
        let a = RustExtractor
            .extract("pub struct Config {}", "src/conf.rs")
            .unwrap();
        let b = RustExtractor
            .extract("pub fn run(cfg: Config) {}", "src/app.rs")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b]).unwrap();

        // Filter to TypeRef-role edges only.
        let typeref_edges: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::TypeRef)
            .collect();

        assert_eq!(
            typeref_edges.len(),
            1,
            "expected exactly one TypeRef edge, got {:?}: {:?}",
            typeref_edges.len(),
            typeref_edges
                .iter()
                .map(|e| format!(
                    "{}{} ({:?})",
                    e.from.to_scip_string(),
                    e.to.to_scip_string(),
                    e.confidence
                ))
                .collect::<Vec<_>>()
        );

        let e = typeref_edges[0];
        assert!(
            e.to.to_scip_string().ends_with("Config#"),
            "TypeRef edge to must end with 'Config#' (the struct def), got: {}",
            e.to.to_scip_string()
        );
        assert_eq!(
            e.confidence,
            Confidence::Scoped,
            "single global candidate → Win-1 Scoped, got: {:?}",
            e.confidence
        );
    }

    // ── SQL cross-artifact resolution tests ──────────────────────────────────

    /// Intra-SQL: a query file referencing a table defined in a schema file
    /// resolves to a TypeRef edge pointing at the table's SCIP symbol, Scoped
    /// (unique global candidate → Win-1).
    #[cfg(feature = "sql")]
    #[test]
    fn intra_sql_typeref_edge_from_query_to_table() {
        use crate::extract::SqlExtractor;

        // File A: defines the `users` table.
        let schema = SqlExtractor
            .extract("CREATE TABLE users (id INT);", "db/schema.sql")
            .unwrap();
        // File B: SELECT from `users` → emits a TypeRef reference.
        let query = SqlExtractor
            .extract("SELECT * FROM users;", "db/query.sql")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[schema, query]).unwrap();

        // Expect exactly one TypeRef edge whose `to` ends with `users#`.
        let typeref_edges: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::TypeRef && e.to.to_scip_string().ends_with("users#"))
            .collect();

        assert_eq!(
            typeref_edges.len(),
            1,
            "expected one intra-SQL TypeRef edge to 'users#', got {:?}: {:?}",
            typeref_edges.len(),
            graph
                .edges
                .iter()
                .map(|e| format!(
                    "{}{} ({:?}/{:?})",
                    e.from.to_scip_string(),
                    e.to.to_scip_string(),
                    e.role,
                    e.confidence
                ))
                .collect::<Vec<_>>()
        );

        let e = typeref_edges[0];
        // Unique global candidate → Win-1 Scoped.
        assert_eq!(
            e.confidence,
            Confidence::Scoped,
            "unique table candidate should be Scoped, got {:?}",
            e.confidence
        );
        assert_eq!(e.occ.file, "db/query.sql");
    }

    /// Code→SQL: a Rust file referencing the type name `users` resolves to the
    /// SQL `users` table definition.  Confidence is Scoped when `users` is the
    /// only global candidate (Win-1).
    #[cfg(all(feature = "rust", feature = "sql"))]
    #[test]
    fn code_to_sql_typeref_edge_rust_to_table() {
        use crate::extract::SqlExtractor;

        // SQL file: defines the `users` table.
        let schema = SqlExtractor
            .extract("CREATE TABLE users (id INT);", "db/schema.sql")
            .unwrap();

        // Rust file: references `users` as a type name in a function signature.
        // `users` is ≥3 chars so it passes the MIN_REF_LEN filter.
        let rust_file = RustExtractor
            .extract("pub fn run(u: users) {}", "src/app.rs")
            .unwrap();

        // Sanity-check: the Rust extractor must have captured a TypeRef for `users`.
        assert!(
            rust_file
                .references
                .iter()
                .any(|r| r.role == RefRole::TypeRef && r.name == "users"),
            "Rust extractor must emit a TypeRef ref for 'users'; refs: {:?}",
            rust_file.references
        );

        let graph = SymbolTableResolver.resolve(&[schema, rust_file]).unwrap();

        // The edge must resolve to the SQL table's SCIP string (ends with `users#`).
        let edges_to_sql_table: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::TypeRef && e.to.to_scip_string().ends_with("users#"))
            .collect();

        assert_eq!(
            edges_to_sql_table.len(),
            1,
            "expected one Code→SQL TypeRef edge to 'users#', got {:?}: {:?}",
            edges_to_sql_table.len(),
            graph
                .edges
                .iter()
                .map(|e| format!(
                    "{}{} ({:?}/{:?})",
                    e.from.to_scip_string(),
                    e.to.to_scip_string(),
                    e.role,
                    e.confidence
                ))
                .collect::<Vec<_>>()
        );

        let e = edges_to_sql_table[0];
        assert_eq!(
            e.confidence,
            Confidence::Scoped,
            "unique global candidate → Scoped (Win-1), got {:?}",
            e.confidence
        );
        assert_eq!(e.occ.file, "src/app.rs");
    }

    /// Code→SQL, marked cross-artifact: the same `users` TypeRef reference as
    /// [`code_to_sql_typeref_edge_rust_to_table`], but with `cross_artifact: true`
    /// set (as a future SQL-in-string extractor would). The resolver must
    /// override both provenance and confidence: `Provenance::CrossArtifact` and
    /// `Confidence::NameOnly`, regardless of the unique-candidate count that
    /// would otherwise yield `Scoped`.
    #[cfg(all(feature = "rust", feature = "sql"))]
    #[test]
    fn cross_artifact_reference_yields_cross_artifact_provenance_and_name_only_confidence() {
        use crate::extract::SqlExtractor;

        // SQL file: defines the `users` table.
        let schema = SqlExtractor
            .extract("CREATE TABLE users (id INT);", "db/schema.sql")
            .unwrap();

        // Rust file: references `users` as a type name in a function signature.
        let mut rust_file = RustExtractor
            .extract("pub fn run(u: users) {}", "src/app.rs")
            .unwrap();

        // Mark the `users` TypeRef reference as cross-artifact, simulating a
        // future extractor that derives it from an embedded secondary artifact
        // (e.g. a SQL string) rather than an ordinary code type reference.
        let marked = rust_file
            .references
            .iter_mut()
            .find(|r| r.role == RefRole::TypeRef && r.name == "users")
            .expect("Rust extractor must emit a TypeRef ref for 'users'");
        marked.cross_artifact = true;

        let graph = SymbolTableResolver.resolve(&[schema, rust_file]).unwrap();

        let edges_to_sql_table: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::TypeRef && e.to.to_scip_string().ends_with("users#"))
            .collect();

        assert_eq!(
            edges_to_sql_table.len(),
            1,
            "expected one Code→SQL TypeRef edge to 'users#', got {:?}: {:?}",
            edges_to_sql_table.len(),
            graph
                .edges
                .iter()
                .map(|e| format!(
                    "{}{} ({:?}/{:?}/{:?})",
                    e.from.to_scip_string(),
                    e.to.to_scip_string(),
                    e.role,
                    e.confidence,
                    e.provenance
                ))
                .collect::<Vec<_>>()
        );

        let e = edges_to_sql_table[0];
        assert_eq!(
            e.provenance,
            Provenance::CrossArtifact,
            "cross-artifact reference must yield Provenance::CrossArtifact, got {:?}",
            e.provenance
        );
        assert_eq!(
            e.confidence,
            Confidence::NameOnly,
            "cross-artifact reference must be forced to NameOnly regardless of candidate count, got {:?}",
            e.confidence
        );
        assert_eq!(e.occ.file, "src/app.rs");
    }

    // ── HCL cross-artifact resolution tests ──────────────────────────────────

    /// Intra-HCL: `resource "aws_subnet" "main" {}` defined in the same file as
    /// `resource "aws_instance" "web" { subnet_id = aws_subnet.main.id }`.
    /// The traversal emits a TypeRef ref (name `main`, qualifier `aws_subnet`).
    /// With `aws_subnet/main#` as the sole global candidate for name `main`,
    /// Win-1 fires → Confidence::Scoped.
    #[cfg(feature = "hcl")]
    #[test]
    fn intra_hcl_typeref_edge_from_instance_to_subnet() {
        use crate::extract::HclExtractor;

        // One file defines both resources.
        let hcl = HclExtractor
            .extract(
                r#"
resource "aws_subnet" "main" {}
resource "aws_instance" "web" { subnet_id = aws_subnet.main.id }
"#,
                // File stem deliberately NOT "main": the per-file module symbol is
                // named after the file stem and would otherwise collide in `by_name`
                // with the `aws_subnet."main"` resource (honest NameOnly fan-out).
                "infra/network.tf",
            )
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[hcl]).unwrap();

        // Expect exactly one TypeRef edge whose `to` ends with `aws_subnet/main#`.
        let typeref_edges: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| {
                e.role == RefRole::TypeRef && e.to.to_scip_string().ends_with("aws_subnet/main#")
            })
            .collect();

        assert_eq!(
            typeref_edges.len(),
            1,
            "expected one intra-HCL TypeRef edge to 'aws_subnet/main#', got {:?}: {:?}",
            typeref_edges.len(),
            graph
                .edges
                .iter()
                .map(|e| format!(
                    "{}{} ({:?}/{:?})",
                    e.from.to_scip_string(),
                    e.to.to_scip_string(),
                    e.role,
                    e.confidence
                ))
                .collect::<Vec<_>>()
        );

        let e = typeref_edges[0];
        // `main` is the only global candidate → Win-1 → Scoped.
        assert_eq!(
            e.confidence,
            Confidence::Scoped,
            "unique subnet candidate should be Scoped (Win-1), got {:?}",
            e.confidence
        );
        // `from` should be the aws_instance/web symbol.
        assert!(
            e.from.to_scip_string().ends_with("aws_instance/web#"),
            "edge `from` should be 'aws_instance/web#', got: {}",
            e.from.to_scip_string()
        );
        assert_eq!(e.occ.file, "infra/network.tf");
    }

    /// Intra-HCL: `module "vpc" {}` defined alongside
    /// `resource "aws_instance" "web" { x = module.vpc.id }`.
    /// Traversal → name `vpc`, qualifier `module`; `module/vpc#` is the sole
    /// candidate → Win-1 → Scoped.
    #[cfg(feature = "hcl")]
    #[test]
    fn intra_hcl_typeref_edge_from_resource_to_module() {
        use crate::extract::HclExtractor;

        let hcl = HclExtractor
            .extract(
                r#"
module "vpc" { source = "./vpc" }
resource "aws_instance" "web" { vpc_id = module.vpc.id }
"#,
                "infra/main.tf",
            )
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[hcl]).unwrap();

        let typeref_edges: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| {
                e.role == RefRole::TypeRef && e.to.to_scip_string().ends_with("module/vpc#")
            })
            .collect();

        assert_eq!(
            typeref_edges.len(),
            1,
            "expected one TypeRef edge to 'module/vpc#', got {:?}: {:?}",
            typeref_edges.len(),
            graph
                .edges
                .iter()
                .map(|e| format!(
                    "{}{} ({:?}/{:?})",
                    e.from.to_scip_string(),
                    e.to.to_scip_string(),
                    e.role,
                    e.confidence
                ))
                .collect::<Vec<_>>()
        );

        let e = typeref_edges[0];
        assert_eq!(
            e.confidence,
            Confidence::Scoped,
            "unique module/vpc candidate should be Scoped (Win-1), got {:?}",
            e.confidence
        );
        assert!(
            e.from.to_scip_string().ends_with("aws_instance/web#"),
            "edge `from` should be 'aws_instance/web#', got: {}",
            e.from.to_scip_string()
        );
    }

    /// Regression: single-candidate import (Win-1) remains Scoped with Win-2 in place.
    #[cfg(feature = "java")]
    #[test]
    fn import_disambiguation_single_candidate_stays_scoped() {
        // Identical to the existing Python single-candidate test, using Java.
        let a = JavaExtractor
            .extract(
                "package com.example;\npublic class Config {}",
                "src/com/example/Config.java",
            )
            .unwrap();
        let b = JavaExtractor
            .extract(
                "package app;\nimport com.example.Config;\npublic class App {}",
                "src/app/App.java",
            )
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b]).unwrap();

        let imports: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Import)
            .collect();

        assert_eq!(imports.len(), 1, "expected exactly one Import edge");
        // Win-2 fires (unique path match) → Scoped.
        assert_eq!(
            imports[0].confidence,
            Confidence::Scoped,
            "single-candidate import should be Scoped"
        );
    }

    #[cfg(feature = "rust")]
    #[test]
    fn ordinary_references_do_not_target_same_named_modules() {
        let lib = RustExtractor
            .extract(
                "mod helper;\nuse helper::helper;\npub fn run() { helper(); }",
                "src/lib.rs",
            )
            .unwrap();
        let helper = RustExtractor
            .extract("pub fn helper() {}", "src/helper.rs")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[lib, helper]).unwrap();
        let ordinary_roles = [
            RefRole::Call,
            RefRole::Import,
            RefRole::Read,
            RefRole::Write,
        ];
        let ordinary_targets: Vec<_> = graph
            .edges
            .iter()
            .filter(|edge| {
                ordinary_roles.contains(&edge.role) && edge.to.leaf_name() == Some("helper")
            })
            .collect();

        assert!(
            !ordinary_targets.is_empty(),
            "the callable helper must remain available to ordinary references"
        );
        assert!(
            ordinary_targets.iter().all(|edge| {
                graph
                    .symbols
                    .iter()
                    .find(|symbol| symbol.id == edge.to)
                    .is_some_and(|symbol| symbol.kind != SymbolKind::Module)
            }),
            "ordinary references must exclude a same-named module target"
        );

        let module_targets: Vec<_> = graph
            .edges
            .iter()
            .filter(|edge| edge.role == RefRole::ModuleRef)
            .collect();
        assert!(
            module_targets.iter().all(|edge| {
                graph
                    .symbols
                    .iter()
                    .find(|symbol| symbol.id == edge.to)
                    .is_some_and(|symbol| symbol.kind == SymbolKind::Module)
            }),
            "module references must target only module symbols"
        );
    }

    /// A Go/Java package spanning multiple files: every file emits its own
    /// namespace-only package/module `Symbol`, and files in the same package
    /// produce the SAME `SymbolId`. The merged graph must still contain exactly
    /// one node for that id — duplicates break downstream consumers that index
    /// a graph by `SymbolId` (e.g. `GraphIndex`).
    #[cfg(feature = "java")]
    #[test]
    fn duplicate_package_module_symbol_is_deduped() {
        use crate::extract::JavaExtractor;

        let a = JavaExtractor
            .extract("package p; public class A {}", "src/p/A.java")
            .unwrap();
        let b = JavaExtractor
            .extract("package p; public class B {}", "src/p/B.java")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[a, b]).unwrap();

        let module_ids: Vec<_> = graph
            .symbols
            .iter()
            .filter(|s| s.kind == SymbolKind::Module && s.name == "p")
            .map(|s| &s.id)
            .collect();
        assert_eq!(
            module_ids.len(),
            1,
            "expected exactly one package module symbol for `p`, got {module_ids:?}"
        );
    }
}