Skip to main content

arbor_graph/
builder.rs

1//! Graph builder for constructing the code graph from parsed nodes.
2//!
3//! Two-pass construction:
4//!   1. Add all nodes — populates symbol table and import map
5//!   2. Resolve edges — uses import context to create accurate edges
6
7use crate::edge::{Edge, EdgeKind};
8use crate::graph::{ArborGraph, NodeId};
9use crate::symbol_table::SymbolTable;
10use arbor_core::{
11    clean_type_name, field_type_ref, return_type_ref, type_relation_ref, typed_receiver, CodeNode,
12    NodeKind, TypeRelationKind,
13};
14use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
15use std::path::{Path, PathBuf};
16use tracing::debug;
17
18/// Beyond this many candidate definitions, a bare name carries no information
19/// and linking to all of them would swamp the graph with noise.
20const MAX_AMBIGUOUS_FANOUT: usize = 4;
21
22/// Tighter fan-out cap for calls whose receiver type is unknown.
23const MAX_UNKNOWN_RECEIVER_FANOUT: usize = 2;
24
25/// Confidence multiplier for a call on a receiver we could not type
26/// (`userService.findOne()`). The method name is real evidence, but which
27/// `findOne` it reaches is a guess.
28const UNKNOWN_RECEIVER_PENALTY: f32 = 0.55;
29
30/// Confidence for a call whose receiver's type was read from the code
31/// (`draft: &mut Draft`). Inferred, so a little below a written path.
32const TYPED_RECEIVER_CONFIDENCE: f32 = 0.9;
33
34/// How a call on a typed receiver (`.run_started@AppState.draft`) resolved.
35enum TypedReceiver {
36    /// The method on the receiver's type, or on each implementor of a trait.
37    Found(Vec<NodeId>),
38    /// The type isn't defined in this project (`reqwest::Client`): the
39    /// method is external too, and must not bind to a same-named project one.
40    External,
41    /// The type is known but its method isn't (a trait default elsewhere, a
42    /// `Deref` target, a struct from a macro). Fall back to the method name.
43    Unknown,
44}
45
46/// Builds an ArborGraph from parsed code nodes.
47pub struct GraphBuilder {
48    graph: ArborGraph,
49    symbol_table: SymbolTable,
50    name_to_id: HashMap<String, String>,
51
52    /// Per-file map of locally-bound name → source module specifier.
53    /// Built from Import nodes that carry their imported names in `references`.
54    ///
55    /// Example:
56    ///   `import { validate } from '@babel/types'`
57    ///   → import_map["file.ts"]["validate"] = "@babel/types"
58    ///
59    /// Used during edge resolution to verify that a direct call like `validate()`
60    /// is indeed an intentional import, not a same-name coincidence.
61    import_map: HashMap<String, HashMap<String, String>>,
62
63    /// Namespace import aliases: file → alias → source module.
64    ///
65    /// Example:
66    ///   `import * as types from '@babel/types'`
67    ///   → namespace_imports["file.ts"]["types"] = "@babel/types"
68    ///
69    /// Used to resolve calls like `types.validate()` — though since we now DROP
70    /// those calls at parse time, this is reserved for future use when we add
71    /// a richer call-site representation.
72    namespace_imports: HashMap<String, HashMap<String, String>>,
73}
74
75impl Default for GraphBuilder {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl GraphBuilder {
82    pub fn new() -> Self {
83        Self {
84            graph: ArborGraph::new(),
85            symbol_table: SymbolTable::new(),
86            name_to_id: HashMap::new(),
87            import_map: HashMap::new(),
88            namespace_imports: HashMap::new(),
89        }
90    }
91
92    /// Adds nodes from a parsed file to the graph.
93    ///
94    /// This pass does two things:
95    ///   - Adds real code entities (functions, classes, etc.) to the graph and symbol table
96    ///   - Processes Import nodes to build the per-file import map
97    ///
98    /// Call this for all files before calling `build()`.
99    pub fn add_nodes(&mut self, nodes: Vec<CodeNode>) {
100        for node in nodes {
101            // Import nodes carry the import map — process them but don't add to graph
102            // (they are not code entities we want in centrality analysis)
103            if node.kind == NodeKind::Import {
104                let file = node.file.clone();
105                let module = node.name.clone();
106
107                for imported_name in &node.references {
108                    if let Some(alias) = imported_name.strip_prefix("*as:") {
109                        // `import * as alias from 'module'`
110                        self.namespace_imports
111                            .entry(file.clone())
112                            .or_default()
113                            .insert(alias.to_string(), module.clone());
114                    } else {
115                        // `import { name } from 'module'` or `import DefaultName from 'module'`
116                        self.import_map
117                            .entry(file.clone())
118                            .or_default()
119                            .insert(imported_name.clone(), module.clone());
120                    }
121                }
122                // Import nodes are intentionally NOT added to the graph.
123                // They caused misleading centrality scores (e.g. "psycopg.types.range [Import]
124                // 330 callers") because every call to a symbol named after the import path
125                // was attributed to the import node itself.
126                continue;
127            }
128
129            let id_str = node.id.clone();
130            let name = node.name.clone();
131            let qualified = node.qualified_name.clone();
132            let file = PathBuf::from(&node.file);
133
134            let node_idx = self.graph.add_node(node);
135
136            if !qualified.is_empty() {
137                self.symbol_table
138                    .insert(qualified.clone(), node_idx, file.clone());
139            }
140
141            self.name_to_id.insert(name.clone(), id_str.clone());
142            self.name_to_id.insert(qualified, id_str);
143        }
144    }
145
146    /// Resolves references into actual graph edges.
147    ///
148    /// Each reference `R` from file `F` resolves through
149    /// [`SymbolTable::resolve_ref`], which reports *how* it matched. That
150    /// quality becomes the edge's confidence, so a downstream consumer can
151    /// distinguish a proven call from an educated guess instead of treating
152    /// every edge as fact.
153    ///
154    /// Ambiguous references (several equally-plausible definitions) produce a
155    /// low-confidence edge to each candidate, capped at
156    /// [`MAX_AMBIGUOUS_FANOUT`]. Dropping them outright would silently hide
157    /// real call paths; emitting them unlabelled would overstate certainty.
158    ///
159    /// References with no definition in the repository are dropped — they are
160    /// external or stdlib symbols.
161    pub fn resolve_edges(&mut self) {
162        let mut edges_to_add: Vec<(NodeId, NodeId, f32)> = Vec::new();
163
164        let node_indices: Vec<NodeId> = self.graph.node_indexes().collect();
165
166        for from_idx in node_indices {
167            let (references, from_file) = {
168                let node = self.graph.get(from_idx).unwrap();
169                (node.references.clone(), PathBuf::from(&node.file))
170            };
171
172            let from_file_str = from_file.to_string_lossy().to_string();
173
174            for reference in references {
175                // Inheritance is not a call. `extends:` / `implements:` and
176                // `self.method` / `super.method` are resolved in
177                // [`resolve_inheritance`](Self::resolve_inheritance), where an
178                // override can hide a base method. Falling through to a bare
179                // name here would attach the edge to the wrong definition.
180                if type_relation_ref(&reference).is_some()
181                    || receiver_method(&reference).is_some()
182                    || field_type_ref(&reference).is_some()
183                    || return_type_ref(&reference).is_some()
184                {
185                    continue;
186                }
187
188                // `.run_started@AppState.draft`: the receiver's type is known,
189                // so the call reaches that type's method and nothing else.
190                if let Some((method, receiver)) = typed_receiver(&reference) {
191                    match self.resolve_typed_receiver(method, receiver, &from_file) {
192                        TypedReceiver::Found(targets) => {
193                            for to_idx in targets {
194                                if to_idx != from_idx {
195                                    edges_to_add.push((
196                                        from_idx,
197                                        to_idx,
198                                        TYPED_RECEIVER_CONFIDENCE,
199                                    ));
200                                }
201                            }
202                            continue;
203                        }
204                        TypedReceiver::External => continue,
205                        TypedReceiver::Unknown => {}
206                    }
207                }
208
209                // A leading `.` marks a call on a receiver whose type we could
210                // not determine (`userService.findOne()`). Resolve it by method
211                // name, but never let it claim the confidence of a real match.
212                let (lookup, receiver_unknown) = match typed_receiver(&reference) {
213                    Some((method, _)) => (method, true),
214                    None => match reference.strip_prefix('.') {
215                        Some(method) => (method, true),
216                        None => (reference.as_str(), false),
217                    },
218                };
219
220                if lookup.is_empty() {
221                    continue;
222                }
223
224                // Hand the referencing file's imports to the resolver so a bare
225                // name that matches several modules can be pinned to the one
226                // the author actually imported. Without this the resolver
227                // falls through to SameDir and attaches the edge to whichever
228                // definition happens to sit in the caller's own directory.
229                let file_imports = self.import_map.get(&from_file_str);
230                // `jobs::enqueue` / `Provider::new` name where the definition
231                // lives; matching only the last segment would drop the call or
232                // bind it to a same-named function in the wrong module.
233                let resolution = if !receiver_unknown && lookup.contains("::") {
234                    self.symbol_table.resolve_path(lookup, &from_file)
235                } else {
236                    self.symbol_table
237                        .resolve_ref_with_imports(lookup, &from_file, file_imports)
238                };
239
240                if !resolution.is_resolved() {
241                    // The overwhelming majority of references are stdlib or
242                    // third-party and have no definition here. Expected, not
243                    // notable.
244                    debug!(
245                        "Unresolved reference '{}' in {} (likely external/stdlib)",
246                        reference,
247                        from_file.display()
248                    );
249                    continue;
250                }
251
252                let mut base_confidence = resolution.confidence();
253                if receiver_unknown {
254                    base_confidence *= UNKNOWN_RECEIVER_PENALTY;
255                }
256                let mut candidates = resolution.candidates();
257                // In Rust `x.f()` is always a method call (modules use `::`),
258                // so it can't reach a free function that shares the name:
259                // sqlx's `.bind(...)` is not a test helper called `bind`.
260                if receiver_unknown && from_file_str.ends_with(".rs") {
261                    candidates.retain(|id| {
262                        self.graph
263                            .get(*id)
264                            .is_some_and(|n| n.kind == NodeKind::Method)
265                    });
266                    if candidates.is_empty() {
267                        continue;
268                    }
269                }
270
271                // A receiver-unknown call to a name shared by many symbols
272                // (`get`, `run`, `execute`) is pure noise; hold it to a tighter
273                // fan-out than a properly-qualified reference.
274                let fanout_limit = if receiver_unknown {
275                    MAX_UNKNOWN_RECEIVER_FANOUT
276                } else {
277                    MAX_AMBIGUOUS_FANOUT
278                };
279
280                if candidates.len() > fanout_limit {
281                    // A name like `new`, `get`, or `run` with dozens of
282                    // definitions carries no information. Linking to all of
283                    // them would swamp the graph.
284                    // Routine on any real codebase — `.get`, `.encode`, `.match`
285                    // are shared by many types. Diagnostic, not a user problem.
286                    debug!(
287                        "Reference '{}' in {} has {} candidate definitions — too ambiguous to link",
288                        reference,
289                        from_file.display(),
290                        candidates.len()
291                    );
292                    continue;
293                }
294
295                for to_idx in candidates {
296                    if from_idx == to_idx {
297                        continue;
298                    }
299
300                    // Method names are never in the import map — importing
301                    // `UserService` does not import `findOne` — so import
302                    // validation only applies to bare and qualified references.
303                    let confidence = if receiver_unknown {
304                        base_confidence
305                    } else {
306                        self.apply_import_validation(
307                            &reference,
308                            &from_file,
309                            &from_file_str,
310                            to_idx,
311                            base_confidence,
312                        )
313                    };
314
315                    if confidence <= 0.0 {
316                        continue;
317                    }
318
319                    edges_to_add.push((from_idx, to_idx, confidence));
320                }
321            }
322        }
323
324        for (from_id, to_id, confidence) in edges_to_add {
325            self.graph.add_edge(
326                from_id,
327                to_id,
328                Edge::new(EdgeKind::Calls).with_confidence(confidence),
329            );
330        }
331    }
332
333    /// Downgrades (rather than drops) an edge whose name is not imported.
334    ///
335    /// If the referencing file declares imports and this bare name is not among
336    /// them, a cross-module match is probably a same-name coincidence. The old
337    /// behaviour dropped such edges unless the target was in the same directory
338    /// — which meant that in a flat `src/` layout, the common case for JS and
339    /// Python projects, the check never fired at all. Confidence-weighting
340    /// applies the same suspicion uniformly instead of exempting whole layouts.
341    ///
342    /// Returns `0.0` to drop the edge entirely.
343    fn apply_import_validation(
344        &self,
345        reference: &str,
346        from_file: &Path,
347        from_file_str: &str,
348        to_idx: NodeId,
349        base_confidence: f32,
350    ) -> f32 {
351        let Some(file_imports) = self.import_map.get(from_file_str) else {
352            return base_confidence;
353        };
354        if file_imports.is_empty() || reference.contains('.') || reference.contains("::") {
355            return base_confidence;
356        }
357        if file_imports.contains_key(reference) {
358            // Explicitly imported — the strongest possible corroboration.
359            return base_confidence.max(0.95);
360        }
361
362        let Some(to_node) = self.graph.get(to_idx) else {
363            return 0.0;
364        };
365        let to_file = PathBuf::from(&to_node.file);
366
367        if to_file == from_file {
368            // Defined in this very file; imports are irrelevant.
369            return base_confidence;
370        }
371
372        if to_file.parent() == from_file.parent() {
373            // Same directory but never imported. Plausible in languages with
374            // implicit module scope, suspicious everywhere else.
375            return base_confidence * 0.6;
376        }
377
378        // Different module and not imported: almost certainly a name collision.
379        debug!(
380            "Downgrading unimported cross-module reference '{}' in {} → {}",
381            reference,
382            from_file.display(),
383            to_file.display()
384        );
385        base_confidence * 0.3
386    }
387
388    /// Emits `extends` / `implements` edges and inherited-method reachability.
389    ///
390    /// A subclass reaches each base it names. A method the subclass does not
391    /// define is reachable from the subclass; an override blocks that path.
392    /// `self`/`this` calls bind to the nearest definition, including the
393    /// enclosing type. `super`/`base` calls start at the parents, so an
394    /// override that calls `super` still reaches the base method.
395    ///
396    /// These type edges are not `Calls`. PageRank stays on the call graph.
397    fn resolve_inheritance(&mut self) {
398        let indices: Vec<NodeId> = self.graph.node_indexes().collect();
399        let types = inherited_types(&self.graph, &indices);
400        let (methods_of, method_owner) = index_methods(&self.graph, &indices, &types);
401        let mut pending = Vec::new();
402        let parents = self.link_type_parents(&types, &mut pending);
403        link_inherited_methods(&types, &parents, &methods_of, &mut pending);
404        link_receiver_calls(
405            &self.graph,
406            &indices,
407            &method_owner,
408            &parents,
409            &methods_of,
410            &mut pending,
411        );
412        self.commit_inheritance_edges(pending);
413    }
414
415    /// Resolves each written base to a type node and records the parent list.
416    fn link_type_parents(
417        &self,
418        types: &[InheritedType],
419        pending: &mut Vec<PendingEdge>,
420    ) -> HashMap<NodeId, Vec<NodeId>> {
421        let mut parents: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
422        for ty in types {
423            let file = PathBuf::from(&ty.file);
424            let mut resolved = Vec::new();
425            let relations = ty
426                .extends
427                .iter()
428                .map(|name| (TypeRelationKind::Extends, name))
429                .chain(
430                    ty.implements
431                        .iter()
432                        .map(|name| (TypeRelationKind::Implements, name)),
433                );
434            for (recorded, name) in relations {
435                let Some(target) = self.resolve_type_name(name, &file) else {
436                    continue;
437                };
438                if target == ty.id || resolved.contains(&target) {
439                    continue;
440                }
441                resolved.push(target);
442                pending.push(type_edge(self, ty, recorded, target));
443            }
444            if !resolved.is_empty() {
445                parents.insert(ty.id, resolved);
446            }
447        }
448        parents
449    }
450
451    fn commit_inheritance_edges(&mut self, pending: Vec<PendingEdge>) {
452        let mut seen: HashSet<(NodeId, NodeId, u8)> = HashSet::new();
453        for (from, to, kind, confidence) in pending {
454            if from == to || !seen.insert((from, to, edge_tag(kind))) {
455                continue;
456            }
457            self.graph
458                .add_edge(from, to, Edge::new(kind).with_confidence(confidence));
459        }
460    }
461
462    /// Resolves a method call whose receiver type path the extractor read from
463    /// the code: `Draft`, `AppState.draft` for a field of an `AppState`, or
464    /// `prepare()` / `mac::Draft::capture().inner()` for what calls return.
465    fn resolve_typed_receiver(&self, method: &str, receiver: &str, file: &Path) -> TypedReceiver {
466        let mut segments = receiver.split('.');
467        let Some(base) = segments.next() else {
468            return TypedReceiver::Unknown;
469        };
470        let mut current = match base.strip_suffix("()") {
471            Some(callee) => match self.returned_type(self.callable(callee, file)) {
472                Ok(id) => id,
473                Err(outcome) => return outcome,
474            },
475            None => match self.type_named(base, file) {
476                Ok(id) => id,
477                Err(outcome) => return outcome,
478            },
479        };
480        for segment in segments {
481            let Some(node) = self.graph.get(current) else {
482                return TypedReceiver::Unknown;
483            };
484            let owner_file = PathBuf::from(&node.file);
485            if let Some(called) = segment.strip_suffix("()") {
486                // `draft.inner().run()`: whatever `Draft::inner` returns.
487                let path = format!("{}::{called}", node.name);
488                current = match self.returned_type(self.callable(&path, &owner_file)) {
489                    Ok(id) => id,
490                    Err(outcome) => return outcome,
491                };
492                continue;
493            }
494            let field_type = node
495                .references
496                .iter()
497                .filter_map(|reference| field_type_ref(reference))
498                .find(|(name, _)| *name == segment)
499                .map(|(_, type_name)| type_name.to_string());
500            let Some(field_type) = field_type else {
501                return TypedReceiver::Unknown;
502            };
503            current = match self.type_named(&field_type, &owner_file) {
504                Ok(id) => id,
505                Err(outcome) => return outcome,
506            };
507        }
508
509        let Some(owner) = self.graph.get(current) else {
510            return TypedReceiver::Unknown;
511        };
512        let owner_file = PathBuf::from(&owner.file);
513        let mut owners = vec![owner.name.clone()];
514        if owner.kind == NodeKind::Interface {
515            // `obs: &mut dyn RunObserver`: any implementor's method may run.
516            owners.extend(self.implementors(&owner.name, &owner_file));
517        } else {
518            // A method from a trait the type implements (a default body).
519            owners.extend(
520                owner.references.iter().filter_map(|reference| {
521                    match type_relation_ref(reference) {
522                        Some((TypeRelationKind::Implements, name)) => Some(name.to_string()),
523                        _ => None,
524                    }
525                }),
526            );
527        }
528        let mut targets = Vec::new();
529        for owner_name in owners {
530            let resolution = self
531                .symbol_table
532                .resolve_path(&format!("{owner_name}::{method}"), &owner_file);
533            for id in resolution.candidates() {
534                let is_method = self
535                    .graph
536                    .get(id)
537                    .is_some_and(|n| matches!(n.kind, NodeKind::Method | NodeKind::Function));
538                if is_method && !targets.contains(&id) {
539                    targets.push(id);
540                }
541            }
542        }
543        if targets.is_empty() || targets.len() > MAX_AMBIGUOUS_FANOUT {
544            TypedReceiver::Unknown
545        } else {
546            TypedReceiver::Found(targets)
547        }
548    }
549
550    /// One type node for `name`, or why there isn't one.
551    fn type_named(&self, name: &str, file: &Path) -> Result<NodeId, TypedReceiver> {
552        match self.resolve_type_name(name, file) {
553            Some(id) => Ok(id),
554            None if self.defines_type(name, file) => Err(TypedReceiver::Unknown),
555            None => Err(TypedReceiver::External),
556        }
557    }
558
559    /// The functions or methods a call path names: `prepare`, `drafts::load`,
560    /// `Draft::capture`.
561    fn callable(&self, path: &str, file: &Path) -> Vec<NodeId> {
562        let resolution = if path.contains("::") {
563            self.symbol_table.resolve_path(path, file)
564        } else {
565            let imports = self.import_map.get(&file.to_string_lossy().to_string());
566            self.symbol_table
567                .resolve_ref_with_imports(path, file, imports)
568        };
569        resolution
570            .candidates()
571            .into_iter()
572            .filter(|id| {
573                self.graph
574                    .get(*id)
575                    .is_some_and(|n| matches!(n.kind, NodeKind::Function | NodeKind::Method))
576            })
577            .collect()
578    }
579
580    /// The type node the given functions return, when they agree on one.
581    fn returned_type(&self, functions: Vec<NodeId>) -> Result<NodeId, TypedReceiver> {
582        let mut returned: Option<(String, PathBuf)> = None;
583        for id in functions {
584            let Some(function) = self.graph.get(id) else {
585                continue;
586            };
587            let Some(type_name) = function.references.iter().find_map(|r| return_type_ref(r))
588            else {
589                // Unit, a primitive, a tuple or an unbounded generic.
590                return Err(TypedReceiver::Unknown);
591            };
592            match &returned {
593                Some((seen, _)) if seen != type_name => return Err(TypedReceiver::Unknown),
594                Some(_) => {}
595                None => returned = Some((type_name.to_string(), PathBuf::from(&function.file))),
596            }
597        }
598        // No project function by that name: an external call, whose result
599        // may still be a project type (`serde_json::from_str::<Draft>`).
600        let Some((type_name, file)) = returned else {
601            return Err(TypedReceiver::Unknown);
602        };
603        self.type_named(&type_name, &file)
604    }
605
606    /// Whether any type in the file's language is called `name`, even if the
607    /// name is too ambiguous to pick one.
608    fn defines_type(&self, name: &str, file: &Path) -> bool {
609        self.symbol_table
610            .resolve_ref_with_imports(name, file, None)
611            .candidates()
612            .into_iter()
613            .any(|id| {
614                self.graph
615                    .get(id)
616                    .is_some_and(|node| is_inheritable_type(node.kind) && node.name == name)
617            })
618    }
619
620    /// Names of the types in `file`'s language that implement trait `name`.
621    fn implementors(&self, name: &str, file: &Path) -> Vec<String> {
622        let mut found = Vec::new();
623        for idx in self.graph.node_indexes() {
624            let Some(node) = self.graph.get(idx) else {
625                continue;
626            };
627            let implements = node.references.iter().any(|reference| {
628                matches!(type_relation_ref(reference),
629                    Some((TypeRelationKind::Implements, target)) if target == name)
630            });
631            if implements
632                && crate::symbol_table::same_language(file, Path::new(&node.file))
633                && !found.contains(&node.name)
634            {
635                found.push(node.name.clone());
636            }
637        }
638        found
639    }
640
641    /// Resolves a base or interface name to one type node.
642    ///
643    /// A path like `pkg.Base` is tried whole, then as its last segment, so a
644    /// class recorded under the simple name `Base` still matches. Several
645    /// equally plausible types are dropped rather than guessed.
646    fn resolve_type_name(&self, name: &str, file: &Path) -> Option<NodeId> {
647        let file_str = file.to_string_lossy().to_string();
648        let imports = self.import_map.get(&file_str);
649        let mut candidates_names = vec![name.to_string()];
650        if let Some(last) = name.rsplit(['.', ':']).find(|segment| !segment.is_empty()) {
651            if last != name {
652                candidates_names.push(last.to_string());
653            }
654        }
655
656        for candidate in &candidates_names {
657            let resolution = self
658                .symbol_table
659                .resolve_ref_with_imports(candidate, file, imports);
660            let type_ids: Vec<NodeId> = resolution
661                .candidates()
662                .into_iter()
663                .filter(|id| {
664                    self.graph
665                        .get(*id)
666                        .is_some_and(|node| is_inheritable_type(node.kind))
667                })
668                .collect();
669            if type_ids.len() == 1 {
670                return Some(type_ids[0]);
671            }
672            let same_file: Vec<NodeId> = type_ids
673                .into_iter()
674                .filter(|id| {
675                    self.graph
676                        .get(*id)
677                        .is_some_and(|node| Path::new(&node.file) == file)
678                })
679                .collect();
680            if same_file.len() == 1 {
681                return Some(same_file[0]);
682            }
683        }
684        None
685    }
686
687    /// Finishes building and returns the graph.
688    pub fn build(mut self) -> ArborGraph {
689        self.resolve_edges();
690        self.resolve_inheritance();
691        self.graph
692    }
693
694    /// Builds without resolving edges (for incremental updates).
695    pub fn build_without_resolve(self) -> ArborGraph {
696        self.graph
697    }
698}
699
700struct InheritedType {
701    id: NodeId,
702    file: String,
703    /// Length of the raw qualified name. Tie-breaking uses this, not the cleaned form.
704    qualified_len: usize,
705    clean_name: String,
706    clean_qualified: String,
707    extends: Vec<String>,
708    implements: Vec<String>,
709}
710
711type PendingEdge = (NodeId, NodeId, EdgeKind, f32);
712
713fn inherited_types(graph: &ArborGraph, indices: &[NodeId]) -> Vec<InheritedType> {
714    let mut types = Vec::new();
715    for id in indices {
716        let Some(node) = graph.get(*id) else {
717            continue;
718        };
719        if !is_inheritable_type(node.kind) {
720            continue;
721        }
722        let mut extends = Vec::new();
723        let mut implements = Vec::new();
724        for reference in &node.references {
725            if let Some((kind, name)) = type_relation_ref(reference) {
726                match kind {
727                    TypeRelationKind::Extends => extends.push(name.to_string()),
728                    TypeRelationKind::Implements => implements.push(name.to_string()),
729                }
730            }
731        }
732        types.push(InheritedType {
733            id: *id,
734            file: node.file.clone(),
735            qualified_len: node.qualified_name.len(),
736            clean_name: clean_type_name(&node.name),
737            clean_qualified: clean_type_name(&node.qualified_name),
738            extends,
739            implements,
740        });
741    }
742    types
743}
744
745fn index_methods(
746    graph: &ArborGraph,
747    indices: &[NodeId],
748    types: &[InheritedType],
749) -> (
750    HashMap<NodeId, BTreeMap<String, NodeId>>,
751    HashMap<NodeId, NodeId>,
752) {
753    let mut types_by_file: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
754    let mut rust_types_by_name: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
755    for ty in types {
756        types_by_file.entry(ty.file.as_str()).or_default().push(ty);
757        if ty.file.ends_with(".rs") {
758            rust_types_by_name
759                .entry(ty.clean_name.as_str())
760                .or_default()
761                .push(ty);
762        }
763    }
764
765    let mut methods_of: HashMap<NodeId, BTreeMap<String, NodeId>> = HashMap::new();
766    let mut method_owner: HashMap<NodeId, NodeId> = HashMap::new();
767    for id in indices {
768        let Some(node) = graph.get(*id) else {
769            continue;
770        };
771        if node.kind != NodeKind::Method {
772            continue;
773        }
774        let Some((parent, method_name)) = split_owner(&node.qualified_name) else {
775            continue;
776        };
777        let parent = clean_type_name(parent);
778        if parent.is_empty() || method_name.is_empty() {
779            continue;
780        }
781        let file_types = types_by_file
782            .get(node.file.as_str())
783            .map(Vec::as_slice)
784            .unwrap_or_default();
785        let owners: Vec<NodeId> = file_types
786            .iter()
787            .filter(|ty| ty.clean_name == parent || ty.clean_qualified == parent)
788            .map(|ty| ty.id)
789            .collect();
790        let owner = unique_owner(&owners, |id| {
791            file_types
792                .iter()
793                .find(|ty| ty.id == id)
794                .map(|ty| ty.qualified_len)
795                .unwrap_or(0)
796        })
797        .or_else(|| {
798            // A Rust `impl Provider` block may sit in any file of the crate,
799            // far from `struct Provider`. Without this its methods have no
800            // owner, and every `self.method()` call inside them is lost.
801            // Look where Rust puts it: the impl file's own module directory
802            // first, then its parents. Tests often declare their own mock
803            // `struct Provider`, so a repo-wide unique name is too strict.
804            if !node.file.ends_with(".rs") || !owners.is_empty() {
805                return None;
806            }
807            let candidates = rust_types_by_name.get(parent.as_str())?;
808            let mut dir = Path::new(&node.file).parent();
809            while let Some(current) = dir {
810                let here: Vec<NodeId> = candidates
811                    .iter()
812                    .filter(|ty| Path::new(&ty.file).parent() == Some(current))
813                    .map(|ty| ty.id)
814                    .collect();
815                match here.as_slice() {
816                    [] => dir = current.parent(),
817                    [only] => return Some(*only),
818                    _ => return None,
819                }
820            }
821            None
822        });
823        let Some(owner) = owner else {
824            continue;
825        };
826        methods_of
827            .entry(owner)
828            .or_default()
829            .entry(method_name.to_string())
830            .or_insert(*id);
831        method_owner.insert(*id, owner);
832    }
833    (methods_of, method_owner)
834}
835
836fn type_edge(
837    builder: &GraphBuilder,
838    ty: &InheritedType,
839    recorded: TypeRelationKind,
840    target: NodeId,
841) -> PendingEdge {
842    let target_kind = builder.graph.get(target).map(|node| node.kind);
843    let edge_kind = match (recorded, target_kind) {
844        (TypeRelationKind::Implements, _) | (_, Some(NodeKind::Interface)) => EdgeKind::Implements,
845        _ => EdgeKind::Extends,
846    };
847    let same_file = builder
848        .graph
849        .get(target)
850        .is_some_and(|node| node.file == ty.file);
851    let confidence = if same_file { 0.95 } else { 0.85 };
852    (ty.id, target, edge_kind, confidence)
853}
854
855fn link_inherited_methods(
856    types: &[InheritedType],
857    parents: &HashMap<NodeId, Vec<NodeId>>,
858    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
859    pending: &mut Vec<PendingEdge>,
860) {
861    for ty in types {
862        let own = methods_of.get(&ty.id);
863        for (name, method_id) in inherited_methods(ty.id, parents, methods_of) {
864            if own.and_then(|methods| methods.get(&name)).is_some() {
865                continue;
866            }
867            pending.push((ty.id, method_id, EdgeKind::References, 0.9));
868        }
869    }
870}
871
872fn link_receiver_calls(
873    graph: &ArborGraph,
874    indices: &[NodeId],
875    method_owner: &HashMap<NodeId, NodeId>,
876    parents: &HashMap<NodeId, Vec<NodeId>>,
877    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
878    pending: &mut Vec<PendingEdge>,
879) {
880    for id in indices {
881        let Some(node) = graph.get(*id) else {
882            continue;
883        };
884        if node.kind != NodeKind::Method {
885            continue;
886        }
887        let Some(&owner) = method_owner.get(id) else {
888            continue;
889        };
890        for reference in &node.references {
891            let Some((is_super, method_name)) = receiver_method(reference) else {
892                continue;
893            };
894            let Some(target) = nearest_method(owner, method_name, is_super, parents, methods_of)
895            else {
896                continue;
897            };
898            if target != *id {
899                pending.push((*id, target, EdgeKind::Calls, 0.95));
900            }
901        }
902    }
903}
904
905fn is_inheritable_type(kind: NodeKind) -> bool {
906    matches!(
907        kind,
908        NodeKind::Class | NodeKind::Struct | NodeKind::Interface | NodeKind::Enum
909    )
910}
911
912/// `Class.method` or `Class::method` → `("Class", "method")`.
913///
914/// When both separators appear, the later one wins, so `mod.Class::method`
915/// is `("mod.Class", "method")`.
916fn split_owner(qualified: &str) -> Option<(&str, &str)> {
917    let dot = qualified.rfind('.');
918    let colon = qualified.rfind("::");
919    match (dot, colon) {
920        (Some(dot_at), Some(colon_at)) if colon_at > dot_at => {
921            Some((&qualified[..colon_at], &qualified[colon_at + 2..]))
922        }
923        (Some(dot_at), _) => Some((&qualified[..dot_at], &qualified[dot_at + 1..])),
924        (None, Some(colon_at)) => Some((&qualified[..colon_at], &qualified[colon_at + 2..])),
925        (None, None) => None,
926    }
927}
928
929fn unique_owner(owners: &[NodeId], qualified_len: impl Fn(NodeId) -> usize) -> Option<NodeId> {
930    match owners {
931        [] => None,
932        [only] => Some(*only),
933        _ => {
934            let mut best_len = 0usize;
935            let mut best: Option<NodeId> = None;
936            let mut tied = false;
937            for id in owners {
938                let len = qualified_len(*id);
939                if len > best_len {
940                    best_len = len;
941                    best = Some(*id);
942                    tied = false;
943                } else if len == best_len {
944                    tied = true;
945                }
946            }
947            if tied {
948                None
949            } else {
950                best
951            }
952        }
953    }
954}
955
956/// Breadth-first, nearest base wins. This approximates C3 linearization and
957/// agrees with it for single inheritance and simple diamonds.
958fn inherited_methods(
959    start: NodeId,
960    parents: &HashMap<NodeId, Vec<NodeId>>,
961    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
962) -> BTreeMap<String, NodeId> {
963    let mut found = BTreeMap::new();
964    let mut seen = HashSet::new();
965    let mut queue = VecDeque::new();
966    if let Some(bases) = parents.get(&start) {
967        queue.extend(bases.iter().copied());
968    }
969    while let Some(current) = queue.pop_front() {
970        if !seen.insert(current) {
971            continue;
972        }
973        if let Some(methods) = methods_of.get(&current) {
974            for (name, id) in methods {
975                found.entry(name.clone()).or_insert(*id);
976            }
977        }
978        if let Some(bases) = parents.get(&current) {
979            for base in bases {
980                if !seen.contains(base) {
981                    queue.push_back(*base);
982                }
983            }
984        }
985    }
986    found
987}
988
989/// Same nearest-base walk as [`inherited_methods`].
990fn nearest_method(
991    start: NodeId,
992    name: &str,
993    skip_self: bool,
994    parents: &HashMap<NodeId, Vec<NodeId>>,
995    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
996) -> Option<NodeId> {
997    let own = if skip_self {
998        None
999    } else {
1000        methods_of.get(&start).and_then(|methods| methods.get(name))
1001    };
1002    if let Some(id) = own {
1003        return Some(*id);
1004    }
1005    let mut seen = HashSet::new();
1006    let mut queue = VecDeque::new();
1007    if let Some(bases) = parents.get(&start) {
1008        queue.extend(bases.iter().copied());
1009    }
1010    while let Some(current) = queue.pop_front() {
1011        if !seen.insert(current) {
1012            continue;
1013        }
1014        if let Some(id) = methods_of
1015            .get(&current)
1016            .and_then(|methods| methods.get(name))
1017        {
1018            return Some(*id);
1019        }
1020        if let Some(bases) = parents.get(&current) {
1021            for base in bases {
1022                if !seen.contains(base) {
1023                    queue.push_back(*base);
1024                }
1025            }
1026        }
1027    }
1028    None
1029}
1030
1031/// `self.compute` / `this.compute` search from the enclosing type.
1032/// `super().compute` / `super.compute` / `base.compute` start at the parents.
1033fn receiver_method(reference: &str) -> Option<(bool, &str)> {
1034    const SUPER_PREFIXES: &[&str] = &["super().", "super.", "base."];
1035    const SAME_PREFIXES: &[&str] = &["self.", "this->", "this.", "Self::"];
1036    let reference = reference.trim();
1037    for prefix in SUPER_PREFIXES {
1038        if let Some(method) = reference.strip_prefix(prefix) {
1039            if is_plain_method(method) {
1040                return Some((true, method));
1041            }
1042        }
1043    }
1044    for prefix in SAME_PREFIXES {
1045        if let Some(method) = reference.strip_prefix(prefix) {
1046            if is_plain_method(method) {
1047                return Some((false, method));
1048            }
1049        }
1050    }
1051    None
1052}
1053
1054fn is_plain_method(name: &str) -> bool {
1055    !name.is_empty()
1056        && name
1057            .chars()
1058            .next()
1059            .is_some_and(|c| c.is_alphabetic() || c == '_')
1060        && name.chars().all(|c| c.is_alphanumeric() || c == '_')
1061}
1062
1063fn edge_tag(kind: EdgeKind) -> u8 {
1064    match kind {
1065        EdgeKind::Calls => 1,
1066        EdgeKind::Extends => 2,
1067        EdgeKind::Implements => 3,
1068        EdgeKind::References => 4,
1069        EdgeKind::Imports => 5,
1070        EdgeKind::UsesType => 6,
1071        EdgeKind::Contains => 7,
1072        EdgeKind::FlowsTo => 8,
1073        EdgeKind::DataDependency => 9,
1074    }
1075}
1076
1077#[cfg(test)]
1078mod tests {
1079    use super::*;
1080    use arbor_core::NodeKind;
1081    use petgraph::visit::{EdgeRef, IntoEdgeReferences};
1082
1083    #[test]
1084    fn test_builder_adds_nodes() {
1085        let mut builder = GraphBuilder::new();
1086        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
1087        let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "test.rs");
1088        builder.add_nodes(vec![node1, node2]);
1089        let graph = builder.build();
1090        assert_eq!(graph.node_count(), 2);
1091    }
1092
1093    #[test]
1094    fn test_builder_resolves_edges() {
1095        let mut builder = GraphBuilder::new();
1096        let caller = CodeNode::new("caller", "caller", NodeKind::Function, "test.rs")
1097            .with_references(vec!["callee".to_string()]);
1098        let callee = CodeNode::new("callee", "callee", NodeKind::Function, "test.rs");
1099        builder.add_nodes(vec![caller, callee]);
1100        let graph = builder.build();
1101        assert_eq!(graph.node_count(), 2);
1102        assert_eq!(graph.edge_count(), 1);
1103    }
1104
1105    #[test]
1106    fn test_cross_file_resolution() {
1107        let mut builder = GraphBuilder::new();
1108        let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
1109            .with_references(vec!["pkg.Utils.helper".to_string()]);
1110        let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
1111        callee.qualified_name = "pkg.Utils.helper".to_string();
1112        builder.add_nodes(vec![caller]);
1113        builder.add_nodes(vec![callee]);
1114        let graph = builder.build();
1115        assert_eq!(graph.node_count(), 2);
1116        assert_eq!(
1117            graph.edge_count(),
1118            1,
1119            "Should resolve cross-file edge via FQN"
1120        );
1121    }
1122
1123    #[test]
1124    fn test_unresolved_references_no_false_edges() {
1125        let mut builder = GraphBuilder::new();
1126        let node = CodeNode::new("caller", "caller", NodeKind::Function, "a.rs")
1127            .with_references(vec!["nonexistent_function".to_string()]);
1128        builder.add_nodes(vec![node]);
1129        let graph = builder.build();
1130        assert_eq!(graph.node_count(), 1);
1131        assert_eq!(
1132            graph.edge_count(),
1133            0,
1134            "Unresolved references must not create edges"
1135        );
1136    }
1137
1138    #[test]
1139    fn test_import_nodes_not_added_to_graph() {
1140        let mut builder = GraphBuilder::new();
1141        let import_node = CodeNode::new("./utils", "./utils", NodeKind::Import, "main.ts")
1142            .with_references(vec!["validate".to_string()]);
1143        let func = CodeNode::new("main", "main", NodeKind::Function, "main.ts");
1144        builder.add_nodes(vec![import_node, func]);
1145        let graph = builder.build();
1146        // Only the function should be in the graph, not the import node
1147        assert_eq!(graph.node_count(), 1);
1148    }
1149
1150    #[test]
1151    fn test_import_map_built_correctly() {
1152        let mut builder = GraphBuilder::new();
1153        let import_node =
1154            CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
1155                .with_references(vec!["validate".to_string(), "clone".to_string()]);
1156        builder.add_nodes(vec![import_node]);
1157        assert_eq!(
1158            builder
1159                .import_map
1160                .get("file.ts")
1161                .and_then(|m| m.get("validate")),
1162            Some(&"@babel/types".to_string())
1163        );
1164        assert_eq!(
1165            builder
1166                .import_map
1167                .get("file.ts")
1168                .and_then(|m| m.get("clone")),
1169            Some(&"@babel/types".to_string())
1170        );
1171    }
1172
1173    #[test]
1174    fn test_namespace_import_map() {
1175        let mut builder = GraphBuilder::new();
1176        let import_node =
1177            CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
1178                .with_references(vec!["*as:types".to_string()]);
1179        builder.add_nodes(vec![import_node]);
1180        assert_eq!(
1181            builder
1182                .namespace_imports
1183                .get("file.ts")
1184                .and_then(|m| m.get("types")),
1185            Some(&"@babel/types".to_string())
1186        );
1187    }
1188
1189    #[test]
1190    fn test_build_empty_graph() {
1191        let builder = GraphBuilder::new();
1192        let graph = builder.build();
1193        assert_eq!(graph.node_count(), 0);
1194        assert_eq!(graph.edge_count(), 0);
1195    }
1196
1197    /// Confidence of the single edge in the graph.
1198    fn only_edge_confidence(graph: &ArborGraph) -> f32 {
1199        let edges = graph.export_edges();
1200        assert_eq!(edges.len(), 1, "expected exactly one edge");
1201        graph
1202            .graph
1203            .edge_weights()
1204            .next()
1205            .expect("edge weight")
1206            .confidence
1207    }
1208
1209    #[test]
1210    fn exact_fqn_match_is_full_confidence() {
1211        let mut b = GraphBuilder::new();
1212        let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
1213            .with_references(vec!["pkg.Utils.helper".to_string()]);
1214        let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
1215        callee.qualified_name = "pkg.Utils.helper".to_string();
1216        b.add_nodes(vec![caller, callee]);
1217        let graph = b.build();
1218
1219        assert_eq!(only_edge_confidence(&graph), 1.0);
1220    }
1221
1222    #[test]
1223    fn unknown_receiver_call_creates_a_weak_edge() {
1224        // `.findOne` — the shape the TS parser used to discard entirely.
1225        let mut b = GraphBuilder::new();
1226        let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1227            .with_references(vec![".findOne".to_string()]);
1228        let callee = CodeNode::new("findOne", "UserRepo.findOne", NodeKind::Method, "repo.ts");
1229        b.add_nodes(vec![caller, callee]);
1230        let graph = b.build();
1231
1232        let confidence = only_edge_confidence(&graph);
1233        assert!(
1234            confidence > 0.0 && confidence < Edge::CONFIDENT_THRESHOLD,
1235            "edge should exist but not be treated as proven, got {confidence}"
1236        );
1237    }
1238
1239    /// `run_started` on three types, plus a trait two of them implement.
1240    fn receiver_fixture(caller_refs: &[&str]) -> ArborGraph {
1241        let mut b = GraphBuilder::new();
1242        let mut nodes = vec![
1243            CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs")
1244                .with_references(caller_refs.iter().map(|r| r.to_string()).collect()),
1245            CodeNode::new("AppState", "AppState", NodeKind::Struct, "src/state.rs")
1246                .with_references(vec![arbor_core::field_ref("draft", "Draft")]),
1247            CodeNode::new("Draft", "Draft", NodeKind::Struct, "src/draft.rs"),
1248            CodeNode::new(
1249                "Telemetry",
1250                "Telemetry",
1251                NodeKind::Struct,
1252                "src/telemetry.rs",
1253            ),
1254            CodeNode::new("Logger", "Logger", NodeKind::Struct, "src/observer.rs"),
1255            CodeNode::new(
1256                "RunObserver",
1257                "RunObserver",
1258                NodeKind::Interface,
1259                "src/observer.rs",
1260            ),
1261        ];
1262        nodes[4].add_type_relation(TypeRelationKind::Implements, "RunObserver");
1263        nodes[3].add_type_relation(TypeRelationKind::Implements, "RunObserver");
1264        for (owner, file) in [
1265            ("Draft", "src/draft.rs"),
1266            ("Telemetry", "src/telemetry.rs"),
1267            ("Logger", "src/observer.rs"),
1268        ] {
1269            nodes.push(CodeNode::new(
1270                "run_started",
1271                format!("{owner}.run_started"),
1272                NodeKind::Method,
1273                file,
1274            ));
1275        }
1276        b.add_nodes(nodes);
1277        b.build()
1278    }
1279
1280    fn callees(graph: &ArborGraph) -> Vec<String> {
1281        use petgraph::visit::EdgeRef;
1282        let mut names: Vec<String> = graph
1283            .graph
1284            .edge_references()
1285            .filter(|edge| edge.weight().kind == EdgeKind::Calls)
1286            .filter_map(|edge| graph.get(edge.target()).map(|n| n.qualified_name.clone()))
1287            .collect();
1288        names.sort();
1289        names
1290    }
1291
1292    #[test]
1293    fn typed_receiver_reaches_only_its_own_type() {
1294        // Name-based resolution sees three `run_started` and links none.
1295        assert!(callees(&receiver_fixture(&[".run_started"])).is_empty());
1296        let graph = receiver_fixture(&[".run_started@Draft"]);
1297        assert_eq!(callees(&graph), ["Draft.run_started"]);
1298        let call = graph
1299            .graph
1300            .edge_weights()
1301            .find(|edge| edge.kind == EdgeKind::Calls)
1302            .expect("the call edge");
1303        assert!((call.confidence - TYPED_RECEIVER_CONFIDENCE).abs() < 1e-6);
1304    }
1305
1306    #[test]
1307    fn typed_receiver_follows_fields_into_other_files() {
1308        let graph = receiver_fixture(&[".run_started@AppState.draft"]);
1309        assert_eq!(callees(&graph), ["Draft.run_started"]);
1310    }
1311
1312    #[test]
1313    fn trait_typed_receiver_reaches_each_implementor() {
1314        let graph = receiver_fixture(&[".run_started@RunObserver"]);
1315        assert_eq!(
1316            callees(&graph),
1317            ["Logger.run_started", "Telemetry.run_started"]
1318        );
1319    }
1320
1321    #[test]
1322    fn external_receiver_never_binds_to_a_project_method() {
1323        // `client.run_started()` on `reqwest::Client` is not Draft's method.
1324        assert!(callees(&receiver_fixture(&[".run_started@Client"])).is_empty());
1325    }
1326
1327    #[test]
1328    fn project_type_without_the_method_falls_back_to_the_name() {
1329        // A field this struct doesn't declare: the type is no longer known,
1330        // so the call is resolved by name (here: too ambiguous to link).
1331        assert!(callees(&receiver_fixture(&[".run_started@AppState.missing"])).is_empty());
1332        let mut b = GraphBuilder::new();
1333        b.add_nodes(vec![
1334            CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs")
1335                .with_references(vec![".flush@Draft".to_string()]),
1336            CodeNode::new("Draft", "Draft", NodeKind::Struct, "src/draft.rs"),
1337            CodeNode::new("flush", "Buffer.flush", NodeKind::Method, "src/buffer.rs"),
1338        ]);
1339        let graph = b.build();
1340        // Draft has no `flush` (a Deref target might): a weak name-based edge.
1341        assert_eq!(callees(&graph), ["Buffer.flush"]);
1342        assert!(only_edge_confidence(&graph) < TYPED_RECEIVER_CONFIDENCE);
1343    }
1344
1345    #[test]
1346    fn typed_receiver_follows_return_types() {
1347        let mut b = GraphBuilder::new();
1348        let mut prepare = CodeNode::new("prepare", "prepare", NodeKind::Function, "src/lib.rs")
1349            .with_references(vec![arbor_core::returns_ref("Prepared")]);
1350        prepare.line_end = 0;
1351        b.add_nodes(vec![
1352            CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs").with_references(
1353                vec![
1354                    ".run_started@prepare()".to_string(),
1355                    ".flush@mac::Prepared::capture().buffer()".to_string(),
1356                ],
1357            ),
1358            prepare,
1359            CodeNode::new("Prepared", "Prepared", NodeKind::Struct, "src/mac.rs"),
1360            CodeNode::new("Buffer", "Buffer", NodeKind::Struct, "src/buffer.rs"),
1361            CodeNode::new(
1362                "capture",
1363                "Prepared.capture",
1364                NodeKind::Method,
1365                "src/mac.rs",
1366            )
1367            .with_references(vec![arbor_core::returns_ref("Prepared")]),
1368            CodeNode::new("buffer", "Prepared.buffer", NodeKind::Method, "src/mac.rs")
1369                .with_references(vec![arbor_core::returns_ref("Buffer")]),
1370            CodeNode::new(
1371                "run_started",
1372                "Prepared.run_started",
1373                NodeKind::Method,
1374                "src/mac.rs",
1375            ),
1376            CodeNode::new(
1377                "run_started",
1378                "Other.run_started",
1379                NodeKind::Method,
1380                "src/other.rs",
1381            ),
1382            CodeNode::new(
1383                "run_started",
1384                "Third.run_started",
1385                NodeKind::Method,
1386                "src/third.rs",
1387            ),
1388            CodeNode::new("flush", "Buffer.flush", NodeKind::Method, "src/buffer.rs"),
1389            CodeNode::new("flush", "Pipe.flush", NodeKind::Method, "src/pipe.rs"),
1390            CodeNode::new("flush", "Sink.flush", NodeKind::Method, "src/sink.rs"),
1391        ]);
1392        let graph = b.build();
1393        assert_eq!(callees(&graph), ["Buffer.flush", "Prepared.run_started"]);
1394    }
1395
1396    #[test]
1397    fn field_types_are_not_calls() {
1398        assert!(
1399            callees(&receiver_fixture(&[])).is_empty(),
1400            "a field: reference is not a call"
1401        );
1402    }
1403
1404    #[test]
1405    fn unknown_receiver_with_many_candidates_is_not_linked() {
1406        // `.get` defined on three different types is noise, not evidence.
1407        let mut b = GraphBuilder::new();
1408        let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1409            .with_references(vec![".get".to_string()]);
1410        b.add_nodes(vec![caller]);
1411        for (i, owner) in ["Cache", "Store", "Config"].iter().enumerate() {
1412            b.add_nodes(vec![CodeNode::new(
1413                "get",
1414                format!("{owner}.get"),
1415                NodeKind::Method,
1416                format!("m{i}.ts"),
1417            )]);
1418        }
1419        let graph = b.build();
1420
1421        assert_eq!(
1422            graph.edge_count(),
1423            0,
1424            "over the fan-out cap, so no edge should be guessed"
1425        );
1426    }
1427
1428    #[test]
1429    fn colliding_symbols_both_remain_reachable() {
1430        // The old table overwrote one of these, orphaning it with zero callers.
1431        let mut b = GraphBuilder::new();
1432        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.py")
1433            .with_references(vec!["process".to_string()]);
1434        b.add_nodes(vec![caller]);
1435        b.add_nodes(vec![CodeNode::new(
1436            "process",
1437            "process",
1438            NodeKind::Function,
1439            "src/utils.py",
1440        )]);
1441        b.add_nodes(vec![CodeNode::new(
1442            "process",
1443            "process",
1444            NodeKind::Function,
1445            "src/helpers.py",
1446        )]);
1447        let graph = b.build();
1448
1449        // Both candidates are linked, each flagged as uncertain.
1450        assert_eq!(graph.edge_count(), 2);
1451        for weight in graph.graph.edge_weights() {
1452            assert!(
1453                !weight.is_confident(),
1454                "ambiguous resolution must not claim certainty"
1455            );
1456        }
1457    }
1458
1459    #[test]
1460    fn unimported_cross_module_reference_is_downgraded_not_dropped() {
1461        let mut b = GraphBuilder::new();
1462        let import = CodeNode::new("./other", "./other", NodeKind::Import, "src/a/main.ts")
1463            .with_references(vec!["somethingElse".to_string()]);
1464        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1465            .with_references(vec!["validate".to_string()]);
1466        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1467        b.add_nodes(vec![import, caller, callee]);
1468        let graph = b.build();
1469
1470        let confidence = only_edge_confidence(&graph);
1471        assert!(
1472            confidence > 0.0 && confidence < 0.5,
1473            "not imported and in another module — weak, got {confidence}"
1474        );
1475    }
1476
1477    #[test]
1478    fn explicitly_imported_reference_is_strong() {
1479        let mut b = GraphBuilder::new();
1480        let import = CodeNode::new("./far", "./far", NodeKind::Import, "src/a/main.ts")
1481            .with_references(vec!["validate".to_string()]);
1482        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1483            .with_references(vec!["validate".to_string()]);
1484        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1485        b.add_nodes(vec![import, caller, callee]);
1486        let graph = b.build();
1487
1488        assert!(
1489            only_edge_confidence(&graph) >= Edge::CONFIDENT_THRESHOLD,
1490            "an explicit import is strong corroboration"
1491        );
1492    }
1493
1494    #[test]
1495    fn same_dir_unimported_reference_is_no_longer_a_free_pass() {
1496        // Flat `src/` layouts made the old filter a no-op, so same-name
1497        // collisions sailed through at full strength.
1498        let mut b = GraphBuilder::new();
1499        let import = CodeNode::new("./x", "./x", NodeKind::Import, "src/main.ts")
1500            .with_references(vec!["other".to_string()]);
1501        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
1502            .with_references(vec!["validate".to_string()]);
1503        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/sibling.ts");
1504        b.add_nodes(vec![import, caller, callee]);
1505        let graph = b.build();
1506
1507        let confidence = only_edge_confidence(&graph);
1508        assert!(
1509            confidence < Edge::CONFIDENT_THRESHOLD,
1510            "same-dir but unimported should carry doubt, got {confidence}"
1511        );
1512    }
1513
1514    #[test]
1515    fn build_is_deterministic_across_insertion_orders() {
1516        let make = |reverse: bool| {
1517            let mut b = GraphBuilder::new();
1518            let mut defs = vec![
1519                CodeNode::new("run", "A.run", NodeKind::Method, "src/a/a.ts"),
1520                CodeNode::new("run", "B.run", NodeKind::Method, "src/b/b.ts"),
1521            ];
1522            if reverse {
1523                defs.reverse();
1524            }
1525            b.add_nodes(vec![CodeNode::new(
1526                "main",
1527                "main",
1528                NodeKind::Function,
1529                "src/c/main.ts",
1530            )
1531            .with_references(vec!["run".to_string()])]);
1532            b.add_nodes(defs);
1533            let graph = b.build();
1534            let mut sig: Vec<String> = graph
1535                .export_edges()
1536                .into_iter()
1537                .map(|e| format!("{}->{}", e.source, e.target))
1538                .collect();
1539            sig.sort();
1540            sig
1541        };
1542
1543        assert_eq!(make(false), make(true));
1544    }
1545
1546    #[test]
1547    fn test_qualified_static_call_resolves_to_correct_class() {
1548        // Regression: `MathUtils.add()` in Calc must link to MathUtils.add, NOT to a
1549        // same-named `add` on a sibling class. Relies on the parser keeping the class
1550        // qualifier so the builder gets an exact FQN match.
1551        let mut b = GraphBuilder::new();
1552        let caller = CodeNode::new("compute", "Calc.compute", NodeKind::Method, "src/Calc.java")
1553            .with_references(vec!["MathUtils.add".to_string()]);
1554        // Same-dir sibling with a colliding bare name — the old bug linked here.
1555        let sibling = CodeNode::new("add", "Sibling.add", NodeKind::Method, "src/Sibling.java");
1556        let target = CodeNode::new(
1557            "add",
1558            "MathUtils.add",
1559            NodeKind::Method,
1560            "src/util/MathUtils.java",
1561        );
1562        b.add_nodes(vec![caller, sibling, target]);
1563        let graph = b.build();
1564
1565        let compute_idx = graph
1566            .node_indexes()
1567            .find(|&i| graph.get(i).unwrap().name == "compute")
1568            .unwrap();
1569        let callees = graph.get_callees(compute_idx);
1570        assert_eq!(callees.len(), 1, "exactly one resolved callee");
1571        assert_eq!(
1572            callees[0].qualified_name, "MathUtils.add",
1573            "static call must resolve to the qualified class, not a same-named sibling"
1574        );
1575    }
1576
1577    fn kinds_between(graph: &ArborGraph, from_q: &str, to_q: &str) -> Vec<EdgeKind> {
1578        let mut kinds = Vec::new();
1579        for edge in graph.graph.edge_references() {
1580            let source = graph.get(edge.source()).unwrap();
1581            let target = graph.get(edge.target()).unwrap();
1582            if source.qualified_name == from_q && target.qualified_name == to_q {
1583                kinds.push(edge.weight().kind);
1584            }
1585        }
1586        kinds
1587    }
1588
1589    fn inheritance_fixture() -> ArborGraph {
1590        let file = "hard/inheritance.py";
1591        let mut b = GraphBuilder::new();
1592        b.add_nodes(vec![
1593            CodeNode::new("Base", "Base", NodeKind::Class, file),
1594            CodeNode::new("compute", "Base.compute", NodeKind::Method, file),
1595            CodeNode::new("shared", "Base.shared", NodeKind::Method, file),
1596            CodeNode::new("Middle", "Middle", NodeKind::Class, file).with_extends(["Base"]),
1597            CodeNode::new("compute", "Middle.compute", NodeKind::Method, file)
1598                .with_references(vec!["super().compute".to_string()]),
1599            CodeNode::new("Derived", "Derived", NodeKind::Class, file).with_extends(["Middle"]),
1600            CodeNode::new("shared", "Derived.shared", NodeKind::Method, file),
1601            CodeNode::new("Leaf", "Leaf", NodeKind::Class, file).with_extends(["Derived"]),
1602            CodeNode::new("run", "Leaf.run", NodeKind::Method, file).with_references(vec![
1603                "self.compute".to_string(),
1604                "self.shared".to_string(),
1605                "len".to_string(),
1606            ]),
1607            // Same simple name, no superclass. Must not become an extender.
1608            CodeNode::new("UserService", "UserService", NodeKind::Class, file),
1609        ]);
1610        b.build()
1611    }
1612
1613    #[test]
1614    fn subclass_extends_its_base() {
1615        let graph = inheritance_fixture();
1616        assert_eq!(
1617            kinds_between(&graph, "Middle", "Base"),
1618            vec![EdgeKind::Extends]
1619        );
1620        assert_eq!(
1621            kinds_between(&graph, "Derived", "Middle"),
1622            vec![EdgeKind::Extends]
1623        );
1624        assert_eq!(
1625            kinds_between(&graph, "Leaf", "Derived"),
1626            vec![EdgeKind::Extends]
1627        );
1628        assert!(
1629            kinds_between(&graph, "UserService", "Base").is_empty(),
1630            "a class with no base is not an extender"
1631        );
1632
1633        let base = graph
1634            .node_indexes()
1635            .find(|&id| graph.get(id).unwrap().qualified_name == "Base")
1636            .unwrap();
1637        let reachers: Vec<_> = graph
1638            .direct_dependents(base)
1639            .into_iter()
1640            .map(|node| node.qualified_name.as_str())
1641            .collect();
1642        assert!(
1643            reachers.contains(&"Middle"),
1644            "Base is reached by Middle, got {reachers:?}"
1645        );
1646        assert!(graph.get_callers(base).is_empty(), "extends is not a call");
1647    }
1648
1649    #[test]
1650    fn inherited_method_reaches_the_defining_class_until_overridden() {
1651        let graph = inheritance_fixture();
1652
1653        // Leaf.run's self.compute binds to Middle.compute, not Base.compute.
1654        assert_eq!(
1655            kinds_between(&graph, "Leaf.run", "Middle.compute"),
1656            vec![EdgeKind::Calls]
1657        );
1658        assert!(kinds_between(&graph, "Leaf.run", "Base.compute").is_empty());
1659
1660        // super() in the override still reaches the base method.
1661        assert_eq!(
1662            kinds_between(&graph, "Middle.compute", "Base.compute"),
1663            vec![EdgeKind::Calls]
1664        );
1665
1666        // Leaf inherits compute from Middle (the nearest definition).
1667        assert_eq!(
1668            kinds_between(&graph, "Leaf", "Middle.compute"),
1669            vec![EdgeKind::References]
1670        );
1671        assert!(kinds_between(&graph, "Leaf", "Base.compute").is_empty());
1672
1673        // Derived overrides shared, so neither Derived nor Leaf reaches Base.shared.
1674        assert!(kinds_between(&graph, "Derived", "Base.shared").is_empty());
1675        assert!(kinds_between(&graph, "Leaf", "Base.shared").is_empty());
1676        assert_eq!(
1677            kinds_between(&graph, "Leaf.run", "Derived.shared"),
1678            vec![EdgeKind::Calls]
1679        );
1680        assert!(kinds_between(&graph, "Leaf.run", "Base.shared").is_empty());
1681
1682        // Middle does not override shared, so it reaches Base.shared.
1683        assert_eq!(
1684            kinds_between(&graph, "Middle", "Base.shared"),
1685            vec![EdgeKind::References]
1686        );
1687
1688        let base_compute = graph
1689            .node_indexes()
1690            .find(|&id| graph.get(id).unwrap().qualified_name == "Base.compute")
1691            .unwrap();
1692        let impact = graph.analyze_impact(base_compute, 5);
1693        let upstream: Vec<_> = impact
1694            .upstream
1695            .iter()
1696            .map(|node| node.node_info.qualified_name.as_str())
1697            .collect();
1698        assert!(
1699            upstream.contains(&"Leaf"),
1700            "changing Base.compute must reach Leaf, got {upstream:?}"
1701        );
1702
1703        let base_shared = graph
1704            .node_indexes()
1705            .find(|&id| graph.get(id).unwrap().qualified_name == "Base.shared")
1706            .unwrap();
1707        let shared_impact = graph.analyze_impact(base_shared, 5);
1708        let direct: Vec<_> = shared_impact
1709            .direct_only()
1710            .into_iter()
1711            .map(|node| node.node_info.qualified_name.clone())
1712            .collect();
1713        assert!(
1714            direct.iter().any(|name| name == "Middle"),
1715            "Middle inherits shared, got {direct:?}"
1716        );
1717        assert!(
1718            direct
1719                .iter()
1720                .all(|name| name != "Derived" && name != "Leaf" && name != "Leaf.run"),
1721            "Derived's override must not make Base.shared a direct dependency, got {direct:?}"
1722        );
1723    }
1724
1725    #[test]
1726    fn diamond_inherits_the_nearest_override() {
1727        let file = "diamond.py";
1728        let mut b = GraphBuilder::new();
1729        b.add_nodes(vec![
1730            CodeNode::new("A", "A", NodeKind::Class, file),
1731            CodeNode::new("f", "A.f", NodeKind::Method, file),
1732            CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
1733            CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["A"]),
1734            CodeNode::new("f", "C.f", NodeKind::Method, file),
1735            CodeNode::new("D", "D", NodeKind::Class, file).with_extends(["B", "C"]),
1736        ]);
1737        let graph = b.build();
1738        assert_eq!(
1739            kinds_between(&graph, "D", "C.f"),
1740            vec![EdgeKind::References],
1741            "D(B, C) sees C.f before A.f"
1742        );
1743        assert!(kinds_between(&graph, "D", "A.f").is_empty());
1744    }
1745
1746    #[test]
1747    fn super_stops_at_the_intermediate_override() {
1748        let file = "super_chain.py";
1749        let mut b = GraphBuilder::new();
1750        b.add_nodes(vec![
1751            CodeNode::new("A", "A", NodeKind::Class, file),
1752            CodeNode::new("foo", "A.foo", NodeKind::Method, file),
1753            CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
1754            CodeNode::new("foo", "B.foo", NodeKind::Method, file),
1755            CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["B"]),
1756            CodeNode::new("foo", "C.foo", NodeKind::Method, file)
1757                .with_references(vec!["super().foo".to_string()]),
1758        ]);
1759        let graph = b.build();
1760        assert_eq!(
1761            kinds_between(&graph, "C.foo", "B.foo"),
1762            vec![EdgeKind::Calls],
1763            "super() in C must reach B's override"
1764        );
1765        assert!(
1766            kinds_between(&graph, "C.foo", "A.foo").is_empty(),
1767            "super() must not skip B and land on A"
1768        );
1769    }
1770}
1771
1772#[cfg(test)]
1773mod rust_path_tests {
1774    use super::*;
1775    use arbor_core::NodeKind;
1776
1777    fn function(name: &str, file: &str, calls: &[&str]) -> CodeNode {
1778        CodeNode::new(name, name, NodeKind::Function, file)
1779            .with_references(calls.iter().map(|c| c.to_string()).collect())
1780    }
1781
1782    fn method(owner: &str, name: &str, file: &str, calls: &[&str]) -> CodeNode {
1783        CodeNode::new(name, format!("{owner}.{name}"), NodeKind::Method, file)
1784            .with_references(calls.iter().map(|c| c.to_string()).collect())
1785    }
1786
1787    fn callers_of(graph: &ArborGraph, name: &str, file: &str) -> Vec<String> {
1788        let id = graph
1789            .node_indexes()
1790            .find(|id| {
1791                graph
1792                    .get(*id)
1793                    .is_some_and(|n| n.name == name && n.file == file)
1794            })
1795            .unwrap_or_else(|| panic!("no {name} in {file}"));
1796        let mut names: Vec<String> = graph
1797            .get_callers(id)
1798            .into_iter()
1799            .map(|n| n.name.clone())
1800            .collect();
1801        names.sort();
1802        names
1803    }
1804
1805    #[test]
1806    fn module_paths_resolve_to_the_named_module_and_never_across_languages() {
1807        let mut b = GraphBuilder::new();
1808        b.add_nodes(vec![
1809            function("enqueue", "src/app/jobs.rs", &[]),
1810            function("enqueue", "src/billing/jobs_old.rs", &[]),
1811            function("enqueue", "web/src/components/Toast.tsx", &[]),
1812            function("dispatch", "src/app/dispatch.rs", &["jobs::enqueue"]),
1813            function("start", "web/src/lib/bridge.ts", &["enqueue"]),
1814        ]);
1815        let graph = b.build();
1816        assert_eq!(
1817            callers_of(&graph, "enqueue", "src/app/jobs.rs"),
1818            vec!["dispatch"]
1819        );
1820        assert!(callers_of(&graph, "enqueue", "src/billing/jobs_old.rs").is_empty());
1821        // The TypeScript call binds to the TypeScript definition only.
1822        assert_eq!(
1823            callers_of(&graph, "enqueue", "web/src/components/Toast.tsx"),
1824            vec!["start"]
1825        );
1826    }
1827
1828    #[test]
1829    fn mod_rs_crate_prefixes_and_re_exports_resolve() {
1830        let mut b = GraphBuilder::new();
1831        b.add_nodes(vec![
1832            function("create_project", "src/app/mod.rs", &[]),
1833            function("record", "src/app/audit/writer.rs", &[]),
1834            function(
1835                "handler",
1836                "src/routes/mod.rs",
1837                &["app::create_project", "app::audit::record"],
1838            ),
1839            function(
1840                "persistence_test",
1841                "tests/integration.rs",
1842                &["my_app::app::create_project", "app::record"],
1843            ),
1844        ]);
1845        let graph = b.build();
1846        assert_eq!(
1847            callers_of(&graph, "create_project", "src/app/mod.rs"),
1848            vec!["handler", "persistence_test"]
1849        );
1850        // `app::record` is a `pub use audit::writer::record` re-export.
1851        assert_eq!(
1852            callers_of(&graph, "record", "src/app/audit/writer.rs"),
1853            vec!["handler", "persistence_test"]
1854        );
1855    }
1856
1857    #[test]
1858    fn external_crate_paths_do_not_bind_to_local_names() {
1859        let mut b = GraphBuilder::new();
1860        b.add_nodes(vec![
1861            function("query", "src/db/queries.rs", &[]),
1862            function("load", "src/routes/mod.rs", &["sqlx::query"]),
1863        ]);
1864        let graph = b.build();
1865        assert!(callers_of(&graph, "query", "src/db/queries.rs").is_empty());
1866    }
1867
1868    #[test]
1869    fn type_paths_resolve_to_the_types_method() {
1870        let mut b = GraphBuilder::new();
1871        b.add_nodes(vec![
1872            CodeNode::new(
1873                "Provider",
1874                "Provider",
1875                NodeKind::Struct,
1876                "src/billing/mod.rs",
1877            ),
1878            method("Provider", "new", "src/billing/mod.rs", &[]),
1879            method("Fixture", "new", "tests/fixture.rs", &[]),
1880            function("boot", "src/main.rs", &["Provider::new"]),
1881        ]);
1882        let graph = b.build();
1883        assert_eq!(
1884            callers_of(&graph, "new", "src/billing/mod.rs"),
1885            vec!["boot"]
1886        );
1887        assert!(callers_of(&graph, "new", "tests/fixture.rs").is_empty());
1888    }
1889
1890    #[test]
1891    fn a_mock_struct_with_the_same_name_does_not_hide_the_real_owner() {
1892        let mut b = GraphBuilder::new();
1893        b.add_nodes(vec![
1894            CodeNode::new(
1895                "Provider",
1896                "Provider",
1897                NodeKind::Struct,
1898                "src/payments/mod.rs",
1899            ),
1900            CodeNode::new("Provider", "Provider", NodeKind::Struct, "tests/mocks.rs"),
1901            method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
1902            method(
1903                "Provider",
1904                "order_history",
1905                "src/payments/cancellation.rs",
1906                &["self.owner_of", ".bind"],
1907            ),
1908            function("bind", "src/payments/tests.rs", &[]),
1909        ]);
1910        let graph = b.build();
1911        assert_eq!(
1912            callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
1913            vec!["order_history"]
1914        );
1915        // `.bind(...)` is a method call; it can't reach a free function.
1916        assert!(callers_of(&graph, "bind", "src/payments/tests.rs").is_empty());
1917    }
1918
1919    #[test]
1920    fn self_calls_reach_methods_whose_impl_is_in_another_file() {
1921        let mut b = GraphBuilder::new();
1922        b.add_nodes(vec![
1923            CodeNode::new(
1924                "Provider",
1925                "Provider",
1926                NodeKind::Struct,
1927                "src/payments/mod.rs",
1928            ),
1929            method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
1930            method(
1931                "Provider",
1932                "order_history",
1933                "src/payments/cancellation.rs",
1934                &["self.owner_of"],
1935            ),
1936        ]);
1937        let graph = b.build();
1938        assert_eq!(
1939            callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
1940            vec!["order_history"]
1941        );
1942    }
1943}