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::{Resolution, SymbolTable};
10use arbor_core::{
11    clean_type_name, field_type_ref, import_alias, local_binding, return_type_ref, runtime_binding,
12    type_relation_ref, typed_receiver, CodeNode, NodeKind, TypeRelationKind, MODULE_FILE_REF,
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    /// Aliased imports: file → local name → the name the module defines.
75    ///
76    /// Example:
77    ///   `from money import money_to_minor_units as to_minor`
78    ///   → import_aliases["orders.py"]["to_minor"] = "money_to_minor_units"
79    ///
80    /// The module is in `import_map` under the same local name.
81    import_aliases: HashMap<String, HashMap<String, String>>,
82
83    /// Go package clause per file. The parser stores `package name` as a
84    /// `Module` node, and a bare call is visible only inside that package.
85    go_packages: HashMap<String, String>,
86
87    /// Every import node added, handed to the graph by `build`, so a graph
88    /// rebuilt from this one keeps each file's imports.
89    import_nodes: Vec<CodeNode>,
90
91    /// JavaScript and TypeScript files that are modules: a top-level `import`
92    /// or `export` statement, or a top-level CommonJS `module.exports` /
93    /// `exports.f` assignment. A file that isn't one, and binds nothing from
94    /// another module, may be a classic script.
95    module_files: HashSet<String>,
96
97    /// Names a JavaScript or TypeScript file binds from a value one of its
98    /// project modules produced: file → local name → (name to look for,
99    /// module). `const { setFilters } = useListFilters()` after importing the
100    /// hook from `./hooks` → `("setFilters", "./hooks")`.
101    runtime_bindings: HashMap<String, HashMap<String, (String, String)>>,
102
103    /// Names a JavaScript or TypeScript file binds itself: variables,
104    /// parameters, destructured values. A call to one may reach whatever
105    /// function the value holds.
106    local_bindings: HashMap<String, HashSet<String>>,
107
108    /// Names a JavaScript or TypeScript file binds from two different modules
109    /// (in two function scopes), which one file-level map can't hold. They
110    /// are treated as local bindings, never as imports.
111    conflicting_bindings: HashMap<String, HashSet<String>>,
112}
113
114impl Default for GraphBuilder {
115    fn default() -> Self {
116        Self::new()
117    }
118}
119
120impl GraphBuilder {
121    pub fn new() -> Self {
122        Self {
123            graph: ArborGraph::new(),
124            symbol_table: SymbolTable::new(),
125            name_to_id: HashMap::new(),
126            import_map: HashMap::new(),
127            namespace_imports: HashMap::new(),
128            import_aliases: HashMap::new(),
129            go_packages: HashMap::new(),
130            import_nodes: Vec::new(),
131            module_files: HashSet::new(),
132            runtime_bindings: HashMap::new(),
133            local_bindings: HashMap::new(),
134            conflicting_bindings: HashMap::new(),
135        }
136    }
137
138    /// Adds nodes from a parsed file to the graph.
139    ///
140    /// This pass does two things:
141    ///   - Adds real code entities (functions, classes, etc.) to the graph and symbol table
142    ///   - Processes Import nodes to build the per-file import map
143    ///
144    /// Call this for all files before calling `build()`.
145    pub fn add_nodes(&mut self, nodes: Vec<CodeNode>) {
146        for node in nodes {
147            // A Go file's package clause decides which bare calls it can see.
148            if node.kind == NodeKind::Module && is_go_file(Path::new(&node.file)) {
149                self.go_packages
150                    .entry(node.file.clone())
151                    .or_insert_with(|| node.name.clone());
152            }
153
154            // Import nodes carry the import map — process them but don't add to graph
155            // (they are not code entities we want in centrality analysis)
156            if node.kind == NodeKind::Import {
157                let file = node.file.clone();
158                let module = node.name.clone();
159                let js = is_js_family_file(Path::new(&file));
160
161                for imported_name in &node.references {
162                    if imported_name == MODULE_FILE_REF {
163                        self.module_files.insert(file.clone());
164                        continue;
165                    }
166                    if let Some(name) = local_binding(imported_name) {
167                        self.local_bindings
168                            .entry(file.clone())
169                            .or_default()
170                            .insert(name.to_string());
171                        continue;
172                    }
173                    if let Some((local, name)) = runtime_binding(imported_name) {
174                        self.bind_at_run_time(&file, local, name, &module);
175                        continue;
176                    }
177                    let local = import_alias(imported_name)
178                        .map_or(imported_name.as_str(), |(local, _)| local);
179                    if js && local != "*" && !imported_name.starts_with("*as:") {
180                        if self.binds_from_another_module(&file, local, &module) {
181                            self.mark_conflicting(&file, local);
182                            continue;
183                        }
184                        // An import of the name outranks a run-time binding.
185                        if let Some(bindings) = self.runtime_bindings.get_mut(&file) {
186                            bindings.remove(local);
187                        }
188                    }
189                    if let Some(alias) = imported_name.strip_prefix("*as:") {
190                        // `import * as alias from 'module'`
191                        self.namespace_imports
192                            .entry(file.clone())
193                            .or_default()
194                            .insert(alias.to_string(), module.clone());
195                    } else if let Some((local, imported)) = import_alias(imported_name) {
196                        // `from money import money_to_minor_units as to_minor`:
197                        // calls use `to_minor`, the module defines the other.
198                        self.import_map
199                            .entry(file.clone())
200                            .or_default()
201                            .insert(local.to_string(), module.clone());
202                        self.import_aliases
203                            .entry(file.clone())
204                            .or_default()
205                            .insert(local.to_string(), imported.to_string());
206                    } else {
207                        // `import { name } from 'module'` or `import DefaultName from 'module'`
208                        self.import_map
209                            .entry(file.clone())
210                            .or_default()
211                            .insert(imported_name.clone(), module.clone());
212                        // A later plain import of the same name rebinds it.
213                        if let Some(aliases) = self.import_aliases.get_mut(&file) {
214                            aliases.remove(imported_name);
215                        }
216                    }
217                }
218                // Import nodes are intentionally NOT added to the graph.
219                // They caused misleading centrality scores (e.g. "psycopg.types.range [Import]
220                // 330 callers") because every call to a symbol named after the import path
221                // was attributed to the import node itself. They are kept
222                // beside it instead (`ArborGraph::import_nodes`).
223                self.import_nodes.push(node);
224                continue;
225            }
226
227            let id_str = node.id.clone();
228            let name = node.name.clone();
229            let qualified = node.qualified_name.clone();
230            let file = PathBuf::from(&node.file);
231
232            let node_idx = self.graph.add_node(node);
233
234            if !qualified.is_empty() {
235                self.symbol_table
236                    .insert(qualified.clone(), node_idx, file.clone());
237            }
238
239            self.name_to_id.insert(name.clone(), id_str.clone());
240            self.name_to_id.insert(qualified, id_str);
241        }
242    }
243
244    /// Resolves references into actual graph edges.
245    ///
246    /// Each reference `R` from file `F` resolves through
247    /// [`SymbolTable::resolve_ref`], which reports *how* it matched. That
248    /// quality becomes the edge's confidence, so a downstream consumer can
249    /// distinguish a proven call from an educated guess instead of treating
250    /// every edge as fact.
251    ///
252    /// Ambiguous references (several equally-plausible definitions) produce a
253    /// low-confidence edge to each candidate, capped at
254    /// [`MAX_AMBIGUOUS_FANOUT`]. Dropping them outright would silently hide
255    /// real call paths; emitting them unlabelled would overstate certainty.
256    ///
257    /// References with no definition in the repository are dropped — they are
258    /// external or stdlib symbols.
259    pub fn resolve_edges(&mut self) {
260        let mut edges_to_add: Vec<(NodeId, NodeId, f32)> = Vec::new();
261
262        let node_indices: Vec<NodeId> = self.graph.node_indexes().collect();
263
264        for from_idx in node_indices {
265            let (references, from_file) = {
266                let node = self.graph.get(from_idx).unwrap();
267                (node.references.clone(), PathBuf::from(&node.file))
268            };
269
270            let from_file_str = from_file.to_string_lossy().to_string();
271
272            for reference in references {
273                // Inheritance is not a call. `extends:` / `implements:` and
274                // `self.method` / `super.method` are resolved in
275                // [`resolve_inheritance`](Self::resolve_inheritance), where an
276                // override can hide a base method. Falling through to a bare
277                // name here would attach the edge to the wrong definition.
278                if type_relation_ref(&reference).is_some()
279                    || receiver_method(&reference).is_some()
280                    || field_type_ref(&reference).is_some()
281                    || return_type_ref(&reference).is_some()
282                {
283                    continue;
284                }
285
286                // `.run_started@AppState.draft`: the receiver's type is known,
287                // so the call reaches that type's method and nothing else.
288                if let Some((method, receiver)) = typed_receiver(&reference) {
289                    match self.resolve_typed_receiver(method, receiver, &from_file) {
290                        TypedReceiver::Found(targets) => {
291                            for to_idx in targets {
292                                if to_idx != from_idx {
293                                    edges_to_add.push((
294                                        from_idx,
295                                        to_idx,
296                                        TYPED_RECEIVER_CONFIDENCE,
297                                    ));
298                                }
299                            }
300                            continue;
301                        }
302                        TypedReceiver::External => continue,
303                        TypedReceiver::Unknown => {}
304                    }
305                }
306
307                // A leading `.` marks a call on a receiver whose type we could
308                // not determine (`userService.findOne()`). Resolve it by method
309                // name, but never let it claim the confidence of a real match.
310                let (lookup, receiver_unknown) = match typed_receiver(&reference) {
311                    Some((method, _)) => (method, true),
312                    None => match reference.strip_prefix('.') {
313                        Some(method) => (method, true),
314                        None => (reference.as_str(), false),
315                    },
316                };
317
318                if lookup.is_empty() {
319                    continue;
320                }
321
322                // Hand the referencing file's imports to the resolver so a bare
323                // name that matches several modules can be pinned to the one
324                // the author actually imported. Without this the resolver
325                // falls through to SameDir and attaches the edge to whichever
326                // definition happens to sit in the caller's own directory.
327                let file_imports = self.import_map.get(&from_file_str);
328                // `to_minor()` after `from money import money_to_minor_units
329                // as to_minor` calls money's function. Nothing is named
330                // `to_minor`, so looking it up finds nothing, or a same-named
331                // function in another module.
332                let alias = if receiver_unknown {
333                    None
334                } else {
335                    self.resolve_alias(lookup, &from_file, &from_file_str)
336                };
337                // `setFilters()` after `const { setFilters } = useListFilters()`
338                // reaches the hook module's function when that module has one.
339                let runtime = if receiver_unknown || alias.is_some() {
340                    None
341                } else {
342                    self.resolve_runtime_binding(lookup, &from_file, &from_file_str)
343                };
344                let bound_at_run_time = runtime.is_some();
345                // `jobs::enqueue` / `Provider::new` name where the definition
346                // lives; matching only the last segment would drop the call or
347                // bind it to a same-named function in the wrong module.
348                let resolution = match alias.or(runtime) {
349                    Some(resolution) => resolution,
350                    None if !receiver_unknown && lookup.contains("::") => {
351                        self.symbol_table.resolve_path(lookup, &from_file)
352                    }
353                    None => {
354                        self.symbol_table
355                            .resolve_ref_with_imports(lookup, &from_file, file_imports)
356                    }
357                };
358
359                if !resolution.is_resolved() {
360                    // The overwhelming majority of references are stdlib or
361                    // third-party and have no definition here. Expected, not
362                    // notable.
363                    debug!(
364                        "Unresolved reference '{}' in {} (likely external/stdlib)",
365                        reference,
366                        from_file.display()
367                    );
368                    continue;
369                }
370
371                let mut base_confidence = resolution.confidence();
372                if receiver_unknown {
373                    base_confidence *= UNKNOWN_RECEIVER_PENALTY;
374                }
375                let mut candidates = resolution.candidates();
376                // In Rust `x.f()` is always a method call (modules use `::`),
377                // so it can't reach a free function that shares the name:
378                // sqlx's `.bind(...)` is not a test helper called `bind`.
379                if receiver_unknown && from_file_str.ends_with(".rs") {
380                    candidates.retain(|id| {
381                        self.graph
382                            .get(*id)
383                            .is_some_and(|n| n.kind == NodeKind::Method)
384                    });
385                    if candidates.is_empty() {
386                        continue;
387                    }
388                }
389
390                // A receiver-unknown call to a name shared by many symbols
391                // (`get`, `run`, `execute`) is pure noise; hold it to a tighter
392                // fan-out than a properly-qualified reference.
393                let fanout_limit = if receiver_unknown {
394                    MAX_UNKNOWN_RECEIVER_FANOUT
395                } else {
396                    MAX_AMBIGUOUS_FANOUT
397                };
398
399                if candidates.len() > fanout_limit {
400                    // A name like `new`, `get`, or `run` with dozens of
401                    // definitions carries no information. Linking to all of
402                    // them would swamp the graph.
403                    // Routine on any real codebase — `.get`, `.encode`, `.match`
404                    // are shared by many types. Diagnostic, not a user problem.
405                    debug!(
406                        "Reference '{}' in {} has {} candidate definitions — too ambiguous to link",
407                        reference,
408                        from_file.display(),
409                        candidates.len()
410                    );
411                    continue;
412                }
413
414                for to_idx in candidates {
415                    if from_idx == to_idx {
416                        continue;
417                    }
418
419                    // Method names are never in the import map — importing
420                    // `UserService` does not import `findOne` — so import
421                    // validation only applies to bare and qualified references.
422                    // A run-time binding was found in its own module, which
423                    // is all the corroboration it can get.
424                    let confidence = if receiver_unknown || bound_at_run_time {
425                        base_confidence
426                    } else {
427                        self.apply_import_validation(
428                            &reference,
429                            &from_file,
430                            &from_file_str,
431                            to_idx,
432                            base_confidence,
433                        )
434                    };
435
436                    if confidence <= 0.0 {
437                        continue;
438                    }
439
440                    edges_to_add.push((from_idx, to_idx, confidence));
441                }
442            }
443        }
444
445        for (from_id, to_id, confidence) in edges_to_add {
446            self.graph.add_edge(
447                from_id,
448                to_id,
449                Edge::new(EdgeKind::Calls).with_confidence(confidence),
450            );
451        }
452    }
453
454    /// Resolves `reference` through the caller file's aliased import of it.
455    ///
456    /// `None` when the name is not an alias there, or when the caller's own
457    /// file defines it: a local definition shadows an import, aliased or not.
458    fn resolve_alias(
459        &self,
460        reference: &str,
461        from_file: &Path,
462        from_file_str: &str,
463    ) -> Option<Resolution> {
464        let imported = self.import_aliases.get(from_file_str)?.get(reference)?;
465        let module = self.import_map.get(from_file_str)?.get(reference)?;
466        let defined_here = self
467            .symbol_table
468            .get_file_exports(&from_file.to_path_buf())
469            .is_some_and(|fqns| fqns.iter().any(|fqn| fqn == reference));
470        if defined_here {
471            return None;
472        }
473        Some(
474            self.symbol_table
475                .resolve_imported(imported, module, from_file),
476        )
477    }
478
479    /// Resolves `reference` inside the module a run-time binding of it came
480    /// from: `setFilters()` after `const { setFilters } = useListFilters()`
481    /// reaches the hook module's `setFilters`.
482    ///
483    /// `None` when the name is no such binding, when the caller's own file
484    /// defines it, or when that module defines no such name (a hook kept apart
485    /// from the provider whose function it returns). The call then resolves
486    /// as any other local binding does.
487    fn resolve_runtime_binding(
488        &self,
489        reference: &str,
490        from_file: &Path,
491        from_file_str: &str,
492    ) -> Option<Resolution> {
493        let (name, module) = self.runtime_bindings.get(from_file_str)?.get(reference)?;
494        let defined_here = self
495            .symbol_table
496            .get_file_exports(&from_file.to_path_buf())
497            .is_some_and(|fqns| fqns.iter().any(|fqn| fqn == reference));
498        if defined_here {
499            return None;
500        }
501        Some(
502            self.symbol_table
503                .resolve_in_module_file(name, module, from_file),
504        )
505        .filter(Resolution::is_resolved)
506    }
507
508    /// Records `local` as bound from a value `module` produced, unless the
509    /// file imports that name from the same module (an import says more) or
510    /// binds it from another module (then the name conflicts).
511    fn bind_at_run_time(&mut self, file: &str, local: &str, name: &str, module: &str) {
512        if self.binds_from_another_module(file, local, module) {
513            self.mark_conflicting(file, local);
514            return;
515        }
516        if self
517            .import_map
518            .get(file)
519            .is_some_and(|imports| imports.contains_key(local))
520        {
521            return;
522        }
523        self.runtime_bindings
524            .entry(file.to_string())
525            .or_default()
526            .insert(local.to_string(), (name.to_string(), module.to_string()));
527    }
528
529    /// Does `file` already bind `local` from a module other than `module`, or
530    /// has the name already conflicted?
531    fn binds_from_another_module(&self, file: &str, local: &str, module: &str) -> bool {
532        self.import_map
533            .get(file)
534            .and_then(|imports| imports.get(local))
535            .is_some_and(|bound| bound != module)
536            || self
537                .runtime_bindings
538                .get(file)
539                .and_then(|bindings| bindings.get(local))
540                .is_some_and(|(_, bound)| bound != module)
541            || self
542                .conflicting_bindings
543                .get(file)
544                .is_some_and(|names| names.contains(local))
545    }
546
547    /// Stops treating `local` as an import or a run-time binding in `file`.
548    fn mark_conflicting(&mut self, file: &str, local: &str) {
549        if let Some(imports) = self.import_map.get_mut(file) {
550            imports.remove(local);
551        }
552        if let Some(aliases) = self.import_aliases.get_mut(file) {
553            aliases.remove(local);
554        }
555        if let Some(bindings) = self.runtime_bindings.get_mut(file) {
556            bindings.remove(local);
557        }
558        self.conflicting_bindings
559            .entry(file.to_string())
560            .or_default()
561            .insert(local.to_string());
562    }
563
564    /// Does this JavaScript or TypeScript file bind `name` itself, so that a
565    /// call to it may reach whatever function the value holds?
566    fn binds_locally(&self, file: &str, name: &str) -> bool {
567        let has = |names: Option<&HashSet<String>>| names.is_some_and(|n| n.contains(name));
568        has(self.local_bindings.get(file))
569            || has(self.conflicting_bindings.get(file))
570            || self
571                .runtime_bindings
572                .get(file)
573                .is_some_and(|bindings| bindings.contains_key(name))
574    }
575
576    /// Is this a JavaScript or TypeScript file with no top-level `import`,
577    /// `export` or CommonJS export that binds nothing from another module?
578    ///
579    /// Such a file may be a classic script, whose top-level functions are
580    /// globals shared with every other script on the page, including files
581    /// whose code sits only in `namespace` blocks (a member's `export` is
582    /// not a module export). Python has no globals shared across modules, so
583    /// a Python file never qualifies.
584    fn is_possible_script(&self, file: &str) -> bool {
585        is_js_family_file(Path::new(file))
586            && !self.module_files.contains(file)
587            && self.import_map.get(file).is_none_or(HashMap::is_empty)
588            && self
589                .namespace_imports
590                .get(file)
591                .is_none_or(HashMap::is_empty)
592            && self
593                .runtime_bindings
594                .get(file)
595                .is_none_or(HashMap::is_empty)
596    }
597
598    /// Decides whether a resolved reference may become an edge.
599    ///
600    /// Python and JavaScript/TypeScript bare names are file-scoped: a cross-file
601    /// call is kept only when this file defines the name or its import map
602    /// contains that local name (or `*`, at the downgrade). JavaScript and
603    /// TypeScript also keep the downgrade for a name the file binds itself
604    /// and for a classic script's function, see
605    /// [`Self::validate_bare_import_visibility`]. A Go bare name is kept
606    /// across files only inside the caller's package (same directory and the
607    /// same package clause). Other languages keep the confidence downgrade.
608    ///
609    /// Dotted references are not bare-name visibility. Returns `0.0` to drop.
610    fn apply_import_validation(
611        &self,
612        reference: &str,
613        from_file: &Path,
614        from_file_str: &str,
615        to_idx: NodeId,
616        base_confidence: f32,
617    ) -> f32 {
618        if reference.contains('.') || reference.contains("::") {
619            return base_confidence;
620        }
621
622        if is_go_file(from_file) {
623            return self.validate_go_package_visibility(
624                reference,
625                from_file,
626                from_file_str,
627                to_idx,
628                base_confidence,
629            );
630        }
631
632        if bare_name_requires_import(from_file) {
633            return self.validate_bare_import_visibility(
634                reference,
635                from_file,
636                from_file_str,
637                to_idx,
638                base_confidence,
639            );
640        }
641
642        let Some(file_imports) = self.import_map.get(from_file_str) else {
643            return base_confidence;
644        };
645        if file_imports.is_empty() {
646            return base_confidence;
647        }
648        if file_imports.contains_key(reference) {
649            // Explicitly imported — the strongest possible corroboration.
650            return base_confidence.max(0.95);
651        }
652
653        let Some(to_node) = self.graph.get(to_idx) else {
654            return 0.0;
655        };
656        let to_file = PathBuf::from(&to_node.file);
657
658        if to_file == from_file {
659            // Defined in this very file; imports are irrelevant.
660            return base_confidence;
661        }
662
663        debug!(
664            "Downgrading unimported cross-module reference '{}' in {} → {}",
665            reference,
666            from_file.display(),
667            to_file.display()
668        );
669        unimported_confidence(from_file, &to_file, base_confidence)
670    }
671
672    /// Drops a bare cross-file name the caller cannot see.
673    ///
674    /// Same-file definitions stay. An import-map entry for the local name stays,
675    /// boosted the same way an explicit import always was. `*` (`from m import *`)
676    /// keeps the downgrade an unimported name gets, because the map does not
677    /// say which names the star brought in.
678    ///
679    /// In JavaScript and TypeScript a bare name resolves to a binding of the
680    /// file or to a global. So a name the file binds itself (a variable, a
681    /// parameter, a destructured value, a run-time binding its module didn't
682    /// define) keeps the downgrade: the value may hold any function. A
683    /// classic script's function is a global, and keeps it too; between two
684    /// possible scripts the call keeps its full confidence, as before. A
685    /// global can't be another module's private function, so that edge is
686    /// dropped; an exported one keeps the downgrade, since build tools inject
687    /// imports for exports (Nuxt's `composables/`, unplugin-auto-import).
688    fn validate_bare_import_visibility(
689        &self,
690        reference: &str,
691        from_file: &Path,
692        from_file_str: &str,
693        to_idx: NodeId,
694        base_confidence: f32,
695    ) -> f32 {
696        let Some(to_node) = self.graph.get(to_idx) else {
697            return 0.0;
698        };
699        let to_file = PathBuf::from(&to_node.file);
700        if to_file == from_file {
701            return base_confidence;
702        }
703
704        if let Some(file_imports) = self.import_map.get(from_file_str) {
705            if file_imports.contains_key(reference) {
706                return base_confidence.max(0.95);
707            }
708            if file_imports.contains_key("*") {
709                return unimported_confidence(from_file, &to_file, base_confidence);
710            }
711        }
712
713        if is_js_family_file(from_file) {
714            let to_script = self.is_possible_script(&to_node.file);
715            if to_script && self.is_possible_script(from_file_str) {
716                return base_confidence;
717            }
718            if to_script || to_node.is_exported || self.binds_locally(from_file_str, reference) {
719                debug!(
720                    "Downgrading unimported reference '{}' in {} → {}, a local binding or a script's global",
721                    reference,
722                    from_file.display(),
723                    to_file.display()
724                );
725                return unimported_confidence(from_file, &to_file, base_confidence);
726            }
727        }
728
729        debug!(
730            "Dropping unimported cross-file reference '{}' in {} → {}",
731            reference,
732            from_file.display(),
733            to_file.display()
734        );
735        0.0
736    }
737
738    /// Keeps a bare Go call that stays inside the caller's package.
739    ///
740    /// The parser records `package name` as a `Module` node in that file, not
741    /// as a field on the function. Same package means that clause matches and
742    /// the files share a directory. A matching clause in another directory
743    /// (`package main` in two commands) is a different package.
744    fn validate_go_package_visibility(
745        &self,
746        reference: &str,
747        from_file: &Path,
748        from_file_str: &str,
749        to_idx: NodeId,
750        base_confidence: f32,
751    ) -> f32 {
752        let Some(to_node) = self.graph.get(to_idx) else {
753            return 0.0;
754        };
755        let to_file = PathBuf::from(&to_node.file);
756        if to_file == from_file {
757            return base_confidence;
758        }
759
760        let to_file_str = to_file.to_string_lossy().to_string();
761        let same_package = self
762            .go_packages
763            .get(from_file_str)
764            .zip(self.go_packages.get(&to_file_str))
765            .is_some_and(|(caller_pkg, callee_pkg)| {
766                caller_pkg == callee_pkg && to_file.parent() == from_file.parent()
767            });
768        if same_package {
769            return base_confidence;
770        }
771
772        debug!(
773            "Dropping bare Go reference '{}' in {} → {}",
774            reference,
775            from_file.display(),
776            to_file.display()
777        );
778        0.0
779    }
780
781    /// Emits `extends` / `implements` edges and inherited-method reachability.
782    ///
783    /// A subclass reaches each base it names. A method the subclass does not
784    /// define is reachable from the subclass; an override blocks that path.
785    /// `self`/`this` calls bind to the nearest definition, including the
786    /// enclosing type. `super`/`base` calls start at the parents, so an
787    /// override that calls `super` still reaches the base method.
788    ///
789    /// These type edges are not `Calls`. PageRank stays on the call graph.
790    fn resolve_inheritance(&mut self) {
791        let indices: Vec<NodeId> = self.graph.node_indexes().collect();
792        let types = inherited_types(&self.graph, &indices);
793        let (methods_of, method_owner) = index_methods(&self.graph, &indices, &types);
794        let mut pending = Vec::new();
795        let parents = self.link_type_parents(&types, &mut pending);
796        link_inherited_methods(&types, &parents, &methods_of, &mut pending);
797        link_receiver_calls(
798            &self.graph,
799            &indices,
800            &method_owner,
801            &parents,
802            &methods_of,
803            &mut pending,
804        );
805        self.commit_inheritance_edges(pending);
806    }
807
808    /// Resolves each written base to a type node and records the parent list.
809    fn link_type_parents(
810        &self,
811        types: &[InheritedType],
812        pending: &mut Vec<PendingEdge>,
813    ) -> HashMap<NodeId, Vec<NodeId>> {
814        let mut parents: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
815        for ty in types {
816            let file = PathBuf::from(&ty.file);
817            let mut resolved = Vec::new();
818            let relations = ty
819                .extends
820                .iter()
821                .map(|name| (TypeRelationKind::Extends, name))
822                .chain(
823                    ty.implements
824                        .iter()
825                        .map(|name| (TypeRelationKind::Implements, name)),
826                );
827            for (recorded, name) in relations {
828                let Some(target) = self.resolve_type_name(name, &file) else {
829                    continue;
830                };
831                if target == ty.id || resolved.contains(&target) {
832                    continue;
833                }
834                resolved.push(target);
835                pending.push(type_edge(self, ty, recorded, target));
836            }
837            if !resolved.is_empty() {
838                parents.insert(ty.id, resolved);
839            }
840        }
841        parents
842    }
843
844    fn commit_inheritance_edges(&mut self, pending: Vec<PendingEdge>) {
845        let mut seen: HashSet<(NodeId, NodeId, u8)> = HashSet::new();
846        for (from, to, kind, confidence) in pending {
847            if from == to || !seen.insert((from, to, edge_tag(kind))) {
848                continue;
849            }
850            self.graph
851                .add_edge(from, to, Edge::new(kind).with_confidence(confidence));
852        }
853    }
854
855    /// Resolves a method call whose receiver type path the extractor read from
856    /// the code: `Draft`, `AppState.draft` for a field of an `AppState`, or
857    /// `prepare()` / `mac::Draft::capture().inner()` for what calls return.
858    fn resolve_typed_receiver(&self, method: &str, receiver: &str, file: &Path) -> TypedReceiver {
859        let mut segments = receiver.split('.');
860        let Some(base) = segments.next() else {
861            return TypedReceiver::Unknown;
862        };
863        let mut current = match base.strip_suffix("()") {
864            Some(callee) => match self.returned_type(self.callable(callee, file)) {
865                Ok(id) => id,
866                Err(outcome) => return outcome,
867            },
868            None => match self.type_named(base, file) {
869                Ok(id) => id,
870                Err(outcome) => return outcome,
871            },
872        };
873        for segment in segments {
874            let Some(node) = self.graph.get(current) else {
875                return TypedReceiver::Unknown;
876            };
877            let owner_file = PathBuf::from(&node.file);
878            if let Some(called) = segment.strip_suffix("()") {
879                // `draft.inner().run()`: whatever `Draft::inner` returns.
880                let path = format!("{}::{called}", node.name);
881                current = match self.returned_type(self.callable(&path, &owner_file)) {
882                    Ok(id) => id,
883                    Err(outcome) => return outcome,
884                };
885                continue;
886            }
887            let field_type = node
888                .references
889                .iter()
890                .filter_map(|reference| field_type_ref(reference))
891                .find(|(name, _)| *name == segment)
892                .map(|(_, type_name)| type_name.to_string());
893            let Some(field_type) = field_type else {
894                return TypedReceiver::Unknown;
895            };
896            current = match self.type_named(&field_type, &owner_file) {
897                Ok(id) => id,
898                Err(outcome) => return outcome,
899            };
900        }
901
902        let Some(owner) = self.graph.get(current) else {
903            return TypedReceiver::Unknown;
904        };
905        let owner_file = PathBuf::from(&owner.file);
906        let mut owners = vec![owner.name.clone()];
907        if owner.kind == NodeKind::Interface {
908            // `obs: &mut dyn RunObserver`: any implementor's method may run.
909            owners.extend(self.implementors(&owner.name, &owner_file));
910        } else {
911            // A method from a trait the type implements (a default body).
912            owners.extend(
913                owner.references.iter().filter_map(|reference| {
914                    match type_relation_ref(reference) {
915                        Some((TypeRelationKind::Implements, name)) => Some(name.to_string()),
916                        _ => None,
917                    }
918                }),
919            );
920        }
921        let mut targets = Vec::new();
922        for owner_name in owners {
923            let resolution = self
924                .symbol_table
925                .resolve_path(&format!("{owner_name}::{method}"), &owner_file);
926            for id in resolution.candidates() {
927                let is_method = self
928                    .graph
929                    .get(id)
930                    .is_some_and(|n| matches!(n.kind, NodeKind::Method | NodeKind::Function));
931                if is_method && !targets.contains(&id) {
932                    targets.push(id);
933                }
934            }
935        }
936        if targets.is_empty() || targets.len() > MAX_AMBIGUOUS_FANOUT {
937            TypedReceiver::Unknown
938        } else {
939            TypedReceiver::Found(targets)
940        }
941    }
942
943    /// One type node for `name`, or why there isn't one.
944    fn type_named(&self, name: &str, file: &Path) -> Result<NodeId, TypedReceiver> {
945        match self.resolve_type_name(name, file) {
946            Some(id) => Ok(id),
947            None if self.defines_type(name, file) => Err(TypedReceiver::Unknown),
948            None => Err(TypedReceiver::External),
949        }
950    }
951
952    /// The functions or methods a call path names: `prepare`, `drafts::load`,
953    /// `Draft::capture`.
954    fn callable(&self, path: &str, file: &Path) -> Vec<NodeId> {
955        let resolution = if path.contains("::") {
956            self.symbol_table.resolve_path(path, file)
957        } else {
958            let imports = self.import_map.get(&file.to_string_lossy().to_string());
959            self.symbol_table
960                .resolve_ref_with_imports(path, file, imports)
961        };
962        resolution
963            .candidates()
964            .into_iter()
965            .filter(|id| {
966                self.graph
967                    .get(*id)
968                    .is_some_and(|n| matches!(n.kind, NodeKind::Function | NodeKind::Method))
969            })
970            .collect()
971    }
972
973    /// The type node the given functions return, when they agree on one.
974    fn returned_type(&self, functions: Vec<NodeId>) -> Result<NodeId, TypedReceiver> {
975        let mut returned: Option<(String, PathBuf)> = None;
976        for id in functions {
977            let Some(function) = self.graph.get(id) else {
978                continue;
979            };
980            let Some(type_name) = function.references.iter().find_map(|r| return_type_ref(r))
981            else {
982                // Unit, a primitive, a tuple or an unbounded generic.
983                return Err(TypedReceiver::Unknown);
984            };
985            match &returned {
986                Some((seen, _)) if seen != type_name => return Err(TypedReceiver::Unknown),
987                Some(_) => {}
988                None => returned = Some((type_name.to_string(), PathBuf::from(&function.file))),
989            }
990        }
991        // No project function by that name: an external call, whose result
992        // may still be a project type (`serde_json::from_str::<Draft>`).
993        let Some((type_name, file)) = returned else {
994            return Err(TypedReceiver::Unknown);
995        };
996        self.type_named(&type_name, &file)
997    }
998
999    /// Whether any type in the file's language is called `name`, even if the
1000    /// name is too ambiguous to pick one.
1001    fn defines_type(&self, name: &str, file: &Path) -> bool {
1002        self.symbol_table
1003            .resolve_ref_with_imports(name, file, None)
1004            .candidates()
1005            .into_iter()
1006            .any(|id| {
1007                self.graph
1008                    .get(id)
1009                    .is_some_and(|node| is_inheritable_type(node.kind) && node.name == name)
1010            })
1011    }
1012
1013    /// Names of the types in `file`'s language that implement trait `name`.
1014    fn implementors(&self, name: &str, file: &Path) -> Vec<String> {
1015        let mut found = Vec::new();
1016        for idx in self.graph.node_indexes() {
1017            let Some(node) = self.graph.get(idx) else {
1018                continue;
1019            };
1020            let implements = node.references.iter().any(|reference| {
1021                matches!(type_relation_ref(reference),
1022                    Some((TypeRelationKind::Implements, target)) if target == name)
1023            });
1024            if implements
1025                && crate::symbol_table::same_language(file, Path::new(&node.file))
1026                && !found.contains(&node.name)
1027            {
1028                found.push(node.name.clone());
1029            }
1030        }
1031        found
1032    }
1033
1034    /// Resolves a base or interface name to one type node.
1035    ///
1036    /// A path like `pkg.Base` is tried whole, then as its last segment, so a
1037    /// class recorded under the simple name `Base` still matches. Several
1038    /// equally plausible types are dropped rather than guessed.
1039    fn resolve_type_name(&self, name: &str, file: &Path) -> Option<NodeId> {
1040        let file_str = file.to_string_lossy().to_string();
1041        let imports = self.import_map.get(&file_str);
1042        let mut candidates_names = vec![name.to_string()];
1043        if let Some(last) = name.rsplit(['.', ':']).find(|segment| !segment.is_empty()) {
1044            if last != name {
1045                candidates_names.push(last.to_string());
1046            }
1047        }
1048
1049        for candidate in &candidates_names {
1050            let resolution = self
1051                .symbol_table
1052                .resolve_ref_with_imports(candidate, file, imports);
1053            let type_ids: Vec<NodeId> = resolution
1054                .candidates()
1055                .into_iter()
1056                .filter(|id| {
1057                    self.graph
1058                        .get(*id)
1059                        .is_some_and(|node| is_inheritable_type(node.kind))
1060                })
1061                .collect();
1062            if type_ids.len() == 1 {
1063                return Some(type_ids[0]);
1064            }
1065            let same_file: Vec<NodeId> = type_ids
1066                .into_iter()
1067                .filter(|id| {
1068                    self.graph
1069                        .get(*id)
1070                        .is_some_and(|node| Path::new(&node.file) == file)
1071                })
1072                .collect();
1073            if same_file.len() == 1 {
1074                return Some(same_file[0]);
1075            }
1076        }
1077        None
1078    }
1079
1080    /// Finishes building and returns the graph.
1081    pub fn build(mut self) -> ArborGraph {
1082        self.resolve_edges();
1083        self.resolve_inheritance();
1084        self.graph.set_import_nodes(self.import_nodes);
1085        self.graph
1086    }
1087
1088    /// Builds without resolving edges (for incremental updates).
1089    pub fn build_without_resolve(mut self) -> ArborGraph {
1090        self.graph.set_import_nodes(self.import_nodes);
1091        self.graph
1092    }
1093}
1094
1095/// The confidence of a bare cross-file call the caller never imported, where
1096/// the call is kept: plausible in the same directory (languages with
1097/// implicit module scope), most likely a name collision anywhere else.
1098fn unimported_confidence(from_file: &Path, to_file: &Path, base_confidence: f32) -> f32 {
1099    if to_file.parent() == from_file.parent() {
1100        base_confidence * 0.6
1101    } else {
1102        base_confidence * 0.3
1103    }
1104}
1105
1106/// Go files: a bare call is visible inside the caller's package.
1107fn is_go_file(file: &Path) -> bool {
1108    file.extension()
1109        .and_then(|ext| ext.to_str())
1110        .is_some_and(|ext| ext.eq_ignore_ascii_case("go"))
1111}
1112
1113/// Languages whose parsers record imported local names.
1114///
1115/// A bare call in one of these files is visible only when the file defines
1116/// the name or imports it; JavaScript and TypeScript add local bindings and
1117/// globals, see `GraphBuilder::validate_bare_import_visibility`.
1118fn bare_name_requires_import(file: &Path) -> bool {
1119    let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
1120        return false;
1121    };
1122    matches!(
1123        ext.to_ascii_lowercase().as_str(),
1124        "py" | "pyi" | "ts" | "tsx" | "js" | "jsx" | "mts" | "cts" | "mjs" | "cjs"
1125    )
1126}
1127
1128/// JavaScript and TypeScript, which share one parser.
1129fn is_js_family_file(file: &Path) -> bool {
1130    let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
1131        return false;
1132    };
1133    matches!(
1134        ext.to_ascii_lowercase().as_str(),
1135        "ts" | "tsx" | "js" | "jsx" | "mts" | "cts" | "mjs" | "cjs"
1136    )
1137}
1138
1139struct InheritedType {
1140    id: NodeId,
1141    file: String,
1142    /// Length of the raw qualified name. Tie-breaking uses this, not the cleaned form.
1143    qualified_len: usize,
1144    clean_name: String,
1145    clean_qualified: String,
1146    extends: Vec<String>,
1147    implements: Vec<String>,
1148}
1149
1150type PendingEdge = (NodeId, NodeId, EdgeKind, f32);
1151
1152fn inherited_types(graph: &ArborGraph, indices: &[NodeId]) -> Vec<InheritedType> {
1153    let mut types = Vec::new();
1154    for id in indices {
1155        let Some(node) = graph.get(*id) else {
1156            continue;
1157        };
1158        if !is_inheritable_type(node.kind) {
1159            continue;
1160        }
1161        let mut extends = Vec::new();
1162        let mut implements = Vec::new();
1163        for reference in &node.references {
1164            if let Some((kind, name)) = type_relation_ref(reference) {
1165                match kind {
1166                    TypeRelationKind::Extends => extends.push(name.to_string()),
1167                    TypeRelationKind::Implements => implements.push(name.to_string()),
1168                }
1169            }
1170        }
1171        types.push(InheritedType {
1172            id: *id,
1173            file: node.file.clone(),
1174            qualified_len: node.qualified_name.len(),
1175            clean_name: clean_type_name(&node.name),
1176            clean_qualified: clean_type_name(&node.qualified_name),
1177            extends,
1178            implements,
1179        });
1180    }
1181    types
1182}
1183
1184fn index_methods(
1185    graph: &ArborGraph,
1186    indices: &[NodeId],
1187    types: &[InheritedType],
1188) -> (
1189    HashMap<NodeId, BTreeMap<String, NodeId>>,
1190    HashMap<NodeId, NodeId>,
1191) {
1192    let mut types_by_file: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
1193    let mut rust_types_by_name: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
1194    for ty in types {
1195        types_by_file.entry(ty.file.as_str()).or_default().push(ty);
1196        if ty.file.ends_with(".rs") {
1197            rust_types_by_name
1198                .entry(ty.clean_name.as_str())
1199                .or_default()
1200                .push(ty);
1201        }
1202    }
1203
1204    let mut methods_of: HashMap<NodeId, BTreeMap<String, NodeId>> = HashMap::new();
1205    let mut method_owner: HashMap<NodeId, NodeId> = HashMap::new();
1206    for id in indices {
1207        let Some(node) = graph.get(*id) else {
1208            continue;
1209        };
1210        if node.kind != NodeKind::Method {
1211            continue;
1212        }
1213        let Some((parent, method_name)) = split_owner(&node.qualified_name) else {
1214            continue;
1215        };
1216        let parent = clean_type_name(parent);
1217        if parent.is_empty() || method_name.is_empty() {
1218            continue;
1219        }
1220        let file_types = types_by_file
1221            .get(node.file.as_str())
1222            .map(Vec::as_slice)
1223            .unwrap_or_default();
1224        let owners: Vec<NodeId> = file_types
1225            .iter()
1226            .filter(|ty| ty.clean_name == parent || ty.clean_qualified == parent)
1227            .map(|ty| ty.id)
1228            .collect();
1229        let owner = unique_owner(&owners, |id| {
1230            file_types
1231                .iter()
1232                .find(|ty| ty.id == id)
1233                .map(|ty| ty.qualified_len)
1234                .unwrap_or(0)
1235        })
1236        .or_else(|| {
1237            // A Rust `impl Provider` block may sit in any file of the crate,
1238            // far from `struct Provider`. Without this its methods have no
1239            // owner, and every `self.method()` call inside them is lost.
1240            // Look where Rust puts it: the impl file's own module directory
1241            // first, then its parents. Tests often declare their own mock
1242            // `struct Provider`, so a repo-wide unique name is too strict.
1243            if !node.file.ends_with(".rs") || !owners.is_empty() {
1244                return None;
1245            }
1246            let candidates = rust_types_by_name.get(parent.as_str())?;
1247            let mut dir = Path::new(&node.file).parent();
1248            while let Some(current) = dir {
1249                let here: Vec<NodeId> = candidates
1250                    .iter()
1251                    .filter(|ty| Path::new(&ty.file).parent() == Some(current))
1252                    .map(|ty| ty.id)
1253                    .collect();
1254                match here.as_slice() {
1255                    [] => dir = current.parent(),
1256                    [only] => return Some(*only),
1257                    _ => return None,
1258                }
1259            }
1260            None
1261        });
1262        let Some(owner) = owner else {
1263            continue;
1264        };
1265        methods_of
1266            .entry(owner)
1267            .or_default()
1268            .entry(method_name.to_string())
1269            .or_insert(*id);
1270        method_owner.insert(*id, owner);
1271    }
1272    (methods_of, method_owner)
1273}
1274
1275fn type_edge(
1276    builder: &GraphBuilder,
1277    ty: &InheritedType,
1278    recorded: TypeRelationKind,
1279    target: NodeId,
1280) -> PendingEdge {
1281    let target_kind = builder.graph.get(target).map(|node| node.kind);
1282    let edge_kind = match (recorded, target_kind) {
1283        (TypeRelationKind::Implements, _) | (_, Some(NodeKind::Interface)) => EdgeKind::Implements,
1284        _ => EdgeKind::Extends,
1285    };
1286    let same_file = builder
1287        .graph
1288        .get(target)
1289        .is_some_and(|node| node.file == ty.file);
1290    let confidence = if same_file { 0.95 } else { 0.85 };
1291    (ty.id, target, edge_kind, confidence)
1292}
1293
1294fn link_inherited_methods(
1295    types: &[InheritedType],
1296    parents: &HashMap<NodeId, Vec<NodeId>>,
1297    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1298    pending: &mut Vec<PendingEdge>,
1299) {
1300    for ty in types {
1301        let own = methods_of.get(&ty.id);
1302        for (name, method_id) in inherited_methods(ty.id, parents, methods_of) {
1303            if own.and_then(|methods| methods.get(&name)).is_some() {
1304                continue;
1305            }
1306            pending.push((ty.id, method_id, EdgeKind::References, 0.9));
1307        }
1308    }
1309}
1310
1311fn link_receiver_calls(
1312    graph: &ArborGraph,
1313    indices: &[NodeId],
1314    method_owner: &HashMap<NodeId, NodeId>,
1315    parents: &HashMap<NodeId, Vec<NodeId>>,
1316    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1317    pending: &mut Vec<PendingEdge>,
1318) {
1319    for id in indices {
1320        let Some(node) = graph.get(*id) else {
1321            continue;
1322        };
1323        if node.kind != NodeKind::Method {
1324            continue;
1325        }
1326        let Some(&owner) = method_owner.get(id) else {
1327            continue;
1328        };
1329        for reference in &node.references {
1330            let Some((is_super, method_name)) = receiver_method(reference) else {
1331                continue;
1332            };
1333            let Some(target) = nearest_method(owner, method_name, is_super, parents, methods_of)
1334            else {
1335                continue;
1336            };
1337            if target != *id {
1338                pending.push((*id, target, EdgeKind::Calls, 0.95));
1339            }
1340        }
1341    }
1342}
1343
1344fn is_inheritable_type(kind: NodeKind) -> bool {
1345    matches!(
1346        kind,
1347        NodeKind::Class | NodeKind::Struct | NodeKind::Interface | NodeKind::Enum
1348    )
1349}
1350
1351/// `Class.method` or `Class::method` → `("Class", "method")`.
1352///
1353/// When both separators appear, the later one wins, so `mod.Class::method`
1354/// is `("mod.Class", "method")`.
1355fn split_owner(qualified: &str) -> Option<(&str, &str)> {
1356    let dot = qualified.rfind('.');
1357    let colon = qualified.rfind("::");
1358    match (dot, colon) {
1359        (Some(dot_at), Some(colon_at)) if colon_at > dot_at => {
1360            Some((&qualified[..colon_at], &qualified[colon_at + 2..]))
1361        }
1362        (Some(dot_at), _) => Some((&qualified[..dot_at], &qualified[dot_at + 1..])),
1363        (None, Some(colon_at)) => Some((&qualified[..colon_at], &qualified[colon_at + 2..])),
1364        (None, None) => None,
1365    }
1366}
1367
1368fn unique_owner(owners: &[NodeId], qualified_len: impl Fn(NodeId) -> usize) -> Option<NodeId> {
1369    match owners {
1370        [] => None,
1371        [only] => Some(*only),
1372        _ => {
1373            let mut best_len = 0usize;
1374            let mut best: Option<NodeId> = None;
1375            let mut tied = false;
1376            for id in owners {
1377                let len = qualified_len(*id);
1378                if len > best_len {
1379                    best_len = len;
1380                    best = Some(*id);
1381                    tied = false;
1382                } else if len == best_len {
1383                    tied = true;
1384                }
1385            }
1386            if tied {
1387                None
1388            } else {
1389                best
1390            }
1391        }
1392    }
1393}
1394
1395/// Breadth-first, nearest base wins. This approximates C3 linearization and
1396/// agrees with it for single inheritance and simple diamonds.
1397fn inherited_methods(
1398    start: NodeId,
1399    parents: &HashMap<NodeId, Vec<NodeId>>,
1400    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1401) -> BTreeMap<String, NodeId> {
1402    let mut found = BTreeMap::new();
1403    let mut seen = HashSet::new();
1404    let mut queue = VecDeque::new();
1405    if let Some(bases) = parents.get(&start) {
1406        queue.extend(bases.iter().copied());
1407    }
1408    while let Some(current) = queue.pop_front() {
1409        if !seen.insert(current) {
1410            continue;
1411        }
1412        if let Some(methods) = methods_of.get(&current) {
1413            for (name, id) in methods {
1414                found.entry(name.clone()).or_insert(*id);
1415            }
1416        }
1417        if let Some(bases) = parents.get(&current) {
1418            for base in bases {
1419                if !seen.contains(base) {
1420                    queue.push_back(*base);
1421                }
1422            }
1423        }
1424    }
1425    found
1426}
1427
1428/// Same nearest-base walk as [`inherited_methods`].
1429fn nearest_method(
1430    start: NodeId,
1431    name: &str,
1432    skip_self: bool,
1433    parents: &HashMap<NodeId, Vec<NodeId>>,
1434    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1435) -> Option<NodeId> {
1436    let own = if skip_self {
1437        None
1438    } else {
1439        methods_of.get(&start).and_then(|methods| methods.get(name))
1440    };
1441    if let Some(id) = own {
1442        return Some(*id);
1443    }
1444    let mut seen = HashSet::new();
1445    let mut queue = VecDeque::new();
1446    if let Some(bases) = parents.get(&start) {
1447        queue.extend(bases.iter().copied());
1448    }
1449    while let Some(current) = queue.pop_front() {
1450        if !seen.insert(current) {
1451            continue;
1452        }
1453        if let Some(id) = methods_of
1454            .get(&current)
1455            .and_then(|methods| methods.get(name))
1456        {
1457            return Some(*id);
1458        }
1459        if let Some(bases) = parents.get(&current) {
1460            for base in bases {
1461                if !seen.contains(base) {
1462                    queue.push_back(*base);
1463                }
1464            }
1465        }
1466    }
1467    None
1468}
1469
1470/// `self.compute` / `this.compute` search from the enclosing type.
1471/// `super().compute` / `super.compute` / `base.compute` start at the parents.
1472fn receiver_method(reference: &str) -> Option<(bool, &str)> {
1473    const SUPER_PREFIXES: &[&str] = &["super().", "super.", "base."];
1474    const SAME_PREFIXES: &[&str] = &["self.", "this->", "this.", "Self::"];
1475    let reference = reference.trim();
1476    for prefix in SUPER_PREFIXES {
1477        if let Some(method) = reference.strip_prefix(prefix) {
1478            if is_plain_method(method) {
1479                return Some((true, method));
1480            }
1481        }
1482    }
1483    for prefix in SAME_PREFIXES {
1484        if let Some(method) = reference.strip_prefix(prefix) {
1485            if is_plain_method(method) {
1486                return Some((false, method));
1487            }
1488        }
1489    }
1490    None
1491}
1492
1493fn is_plain_method(name: &str) -> bool {
1494    !name.is_empty()
1495        && name
1496            .chars()
1497            .next()
1498            .is_some_and(|c| c.is_alphabetic() || c == '_')
1499        && name.chars().all(|c| c.is_alphanumeric() || c == '_')
1500}
1501
1502fn edge_tag(kind: EdgeKind) -> u8 {
1503    match kind {
1504        EdgeKind::Calls => 1,
1505        EdgeKind::Extends => 2,
1506        EdgeKind::Implements => 3,
1507        EdgeKind::References => 4,
1508        EdgeKind::Imports => 5,
1509        EdgeKind::UsesType => 6,
1510        EdgeKind::Contains => 7,
1511        EdgeKind::FlowsTo => 8,
1512        EdgeKind::DataDependency => 9,
1513    }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518    use super::*;
1519    use arbor_core::NodeKind;
1520    use petgraph::visit::{EdgeRef, IntoEdgeReferences};
1521    use std::path::Path;
1522
1523    #[test]
1524    fn test_builder_adds_nodes() {
1525        let mut builder = GraphBuilder::new();
1526        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
1527        let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "test.rs");
1528        builder.add_nodes(vec![node1, node2]);
1529        let graph = builder.build();
1530        assert_eq!(graph.node_count(), 2);
1531    }
1532
1533    #[test]
1534    fn test_builder_resolves_edges() {
1535        let mut builder = GraphBuilder::new();
1536        let caller = CodeNode::new("caller", "caller", NodeKind::Function, "test.rs")
1537            .with_references(vec!["callee".to_string()]);
1538        let callee = CodeNode::new("callee", "callee", NodeKind::Function, "test.rs");
1539        builder.add_nodes(vec![caller, callee]);
1540        let graph = builder.build();
1541        assert_eq!(graph.node_count(), 2);
1542        assert_eq!(graph.edge_count(), 1);
1543    }
1544
1545    #[test]
1546    fn test_cross_file_resolution() {
1547        let mut builder = GraphBuilder::new();
1548        let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
1549            .with_references(vec!["pkg.Utils.helper".to_string()]);
1550        let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
1551        callee.qualified_name = "pkg.Utils.helper".to_string();
1552        builder.add_nodes(vec![caller]);
1553        builder.add_nodes(vec![callee]);
1554        let graph = builder.build();
1555        assert_eq!(graph.node_count(), 2);
1556        assert_eq!(
1557            graph.edge_count(),
1558            1,
1559            "Should resolve cross-file edge via FQN"
1560        );
1561    }
1562
1563    #[test]
1564    fn test_unresolved_references_no_false_edges() {
1565        let mut builder = GraphBuilder::new();
1566        let node = CodeNode::new("caller", "caller", NodeKind::Function, "a.rs")
1567            .with_references(vec!["nonexistent_function".to_string()]);
1568        builder.add_nodes(vec![node]);
1569        let graph = builder.build();
1570        assert_eq!(graph.node_count(), 1);
1571        assert_eq!(
1572            graph.edge_count(),
1573            0,
1574            "Unresolved references must not create edges"
1575        );
1576    }
1577
1578    #[test]
1579    fn test_import_nodes_not_added_to_graph() {
1580        let mut builder = GraphBuilder::new();
1581        let import_node = CodeNode::new("./utils", "./utils", NodeKind::Import, "main.ts")
1582            .with_references(vec!["validate".to_string()]);
1583        let func = CodeNode::new("main", "main", NodeKind::Function, "main.ts");
1584        builder.add_nodes(vec![import_node, func]);
1585        let graph = builder.build();
1586        // Only the function should be in the graph, not the import node
1587        assert_eq!(graph.node_count(), 1);
1588    }
1589
1590    #[test]
1591    fn test_import_map_built_correctly() {
1592        let mut builder = GraphBuilder::new();
1593        let import_node =
1594            CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
1595                .with_references(vec!["validate".to_string(), "clone".to_string()]);
1596        builder.add_nodes(vec![import_node]);
1597        assert_eq!(
1598            builder
1599                .import_map
1600                .get("file.ts")
1601                .and_then(|m| m.get("validate")),
1602            Some(&"@babel/types".to_string())
1603        );
1604        assert_eq!(
1605            builder
1606                .import_map
1607                .get("file.ts")
1608                .and_then(|m| m.get("clone")),
1609            Some(&"@babel/types".to_string())
1610        );
1611    }
1612
1613    #[test]
1614    fn test_namespace_import_map() {
1615        let mut builder = GraphBuilder::new();
1616        let import_node =
1617            CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
1618                .with_references(vec!["*as:types".to_string()]);
1619        builder.add_nodes(vec![import_node]);
1620        assert_eq!(
1621            builder
1622                .namespace_imports
1623                .get("file.ts")
1624                .and_then(|m| m.get("types")),
1625            Some(&"@babel/types".to_string())
1626        );
1627    }
1628
1629    #[test]
1630    fn test_alias_import_map() {
1631        let mut builder = GraphBuilder::new();
1632        let import_node = CodeNode::new("money", "money", NodeKind::Import, "orders.py")
1633            .with_references(vec!["alias:to_minor:money_to_minor_units".to_string()]);
1634        builder.add_nodes(vec![import_node]);
1635        assert_eq!(
1636            builder
1637                .import_map
1638                .get("orders.py")
1639                .and_then(|m| m.get("to_minor")),
1640            Some(&"money".to_string())
1641        );
1642        assert_eq!(
1643            builder
1644                .import_aliases
1645                .get("orders.py")
1646                .and_then(|m| m.get("to_minor")),
1647            Some(&"money_to_minor_units".to_string())
1648        );
1649    }
1650
1651    #[test]
1652    fn aliased_call_reaches_the_imported_name_with_import_confidence() {
1653        let mut builder = GraphBuilder::new();
1654        let import = CodeNode::new("money", "money", NodeKind::Import, "orders.py")
1655            .with_references(vec!["alias:to_minor:money_to_minor_units".to_string()]);
1656        let caller = CodeNode::new(
1657            "total_cents",
1658            "total_cents",
1659            NodeKind::Function,
1660            "orders.py",
1661        )
1662        .with_references(vec!["to_minor".to_string()]);
1663        let callee = CodeNode::new(
1664            "money_to_minor_units",
1665            "money_to_minor_units",
1666            NodeKind::Function,
1667            "money.py",
1668        );
1669        builder.add_nodes(vec![import, caller, callee]);
1670        let graph = builder.build();
1671        assert!(
1672            only_edge_confidence(&graph) >= 0.95,
1673            "an aliased import is as strong as an unaliased one"
1674        );
1675    }
1676
1677    /// `from a import x as y` then `from b import y`: the last binding wins.
1678    #[test]
1679    fn a_plain_import_rebinds_an_earlier_alias() {
1680        let mut builder = GraphBuilder::new();
1681        let aliased = CodeNode::new("a", "a", NodeKind::Import, "main.py")
1682            .with_references(vec!["alias:y:x".to_string()]);
1683        let plain = CodeNode::new("b", "b", NodeKind::Import, "main.py")
1684            .with_references(vec!["y".to_string()]);
1685        let caller = CodeNode::new("run", "run", NodeKind::Function, "main.py")
1686            .with_references(vec!["y".to_string()]);
1687        let x = CodeNode::new("x", "x", NodeKind::Function, "a.py");
1688        let y = CodeNode::new("y", "y", NodeKind::Function, "b.py");
1689        builder.add_nodes(vec![aliased, plain, caller, x, y]);
1690        let graph = builder.build();
1691        let edges = graph.export_edges();
1692        assert_eq!(edges.len(), 1, "{edges:?}");
1693        let target = graph.get_index(&edges[0].target).expect("target");
1694        assert_eq!(graph.get(target).unwrap().file, "b.py");
1695    }
1696
1697    #[test]
1698    fn test_build_empty_graph() {
1699        let builder = GraphBuilder::new();
1700        let graph = builder.build();
1701        assert_eq!(graph.node_count(), 0);
1702        assert_eq!(graph.edge_count(), 0);
1703    }
1704
1705    /// Confidence of the single edge in the graph.
1706    fn only_edge_confidence(graph: &ArborGraph) -> f32 {
1707        let edges = graph.export_edges();
1708        assert_eq!(edges.len(), 1, "expected exactly one edge");
1709        graph
1710            .graph
1711            .edge_weights()
1712            .next()
1713            .expect("edge weight")
1714            .confidence
1715    }
1716
1717    #[test]
1718    fn exact_fqn_match_is_full_confidence() {
1719        let mut b = GraphBuilder::new();
1720        let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
1721            .with_references(vec!["pkg.Utils.helper".to_string()]);
1722        let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
1723        callee.qualified_name = "pkg.Utils.helper".to_string();
1724        b.add_nodes(vec![caller, callee]);
1725        let graph = b.build();
1726
1727        assert_eq!(only_edge_confidence(&graph), 1.0);
1728    }
1729
1730    #[test]
1731    fn unknown_receiver_call_creates_a_weak_edge() {
1732        // `.findOne` — the shape the TS parser used to discard entirely.
1733        let mut b = GraphBuilder::new();
1734        let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1735            .with_references(vec![".findOne".to_string()]);
1736        let callee = CodeNode::new("findOne", "UserRepo.findOne", NodeKind::Method, "repo.ts");
1737        b.add_nodes(vec![caller, callee]);
1738        let graph = b.build();
1739
1740        let confidence = only_edge_confidence(&graph);
1741        assert!(
1742            confidence > 0.0 && confidence < Edge::CONFIDENT_THRESHOLD,
1743            "edge should exist but not be treated as proven, got {confidence}"
1744        );
1745    }
1746
1747    /// `run_started` on three types, plus a trait two of them implement.
1748    fn receiver_fixture(caller_refs: &[&str]) -> ArborGraph {
1749        let mut b = GraphBuilder::new();
1750        let mut nodes = vec![
1751            CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs")
1752                .with_references(caller_refs.iter().map(|r| r.to_string()).collect()),
1753            CodeNode::new("AppState", "AppState", NodeKind::Struct, "src/state.rs")
1754                .with_references(vec![arbor_core::field_ref("draft", "Draft")]),
1755            CodeNode::new("Draft", "Draft", NodeKind::Struct, "src/draft.rs"),
1756            CodeNode::new(
1757                "Telemetry",
1758                "Telemetry",
1759                NodeKind::Struct,
1760                "src/telemetry.rs",
1761            ),
1762            CodeNode::new("Logger", "Logger", NodeKind::Struct, "src/observer.rs"),
1763            CodeNode::new(
1764                "RunObserver",
1765                "RunObserver",
1766                NodeKind::Interface,
1767                "src/observer.rs",
1768            ),
1769        ];
1770        nodes[4].add_type_relation(TypeRelationKind::Implements, "RunObserver");
1771        nodes[3].add_type_relation(TypeRelationKind::Implements, "RunObserver");
1772        for (owner, file) in [
1773            ("Draft", "src/draft.rs"),
1774            ("Telemetry", "src/telemetry.rs"),
1775            ("Logger", "src/observer.rs"),
1776        ] {
1777            nodes.push(CodeNode::new(
1778                "run_started",
1779                format!("{owner}.run_started"),
1780                NodeKind::Method,
1781                file,
1782            ));
1783        }
1784        b.add_nodes(nodes);
1785        b.build()
1786    }
1787
1788    fn callees(graph: &ArborGraph) -> Vec<String> {
1789        use petgraph::visit::EdgeRef;
1790        let mut names: Vec<String> = graph
1791            .graph
1792            .edge_references()
1793            .filter(|edge| edge.weight().kind == EdgeKind::Calls)
1794            .filter_map(|edge| graph.get(edge.target()).map(|n| n.qualified_name.clone()))
1795            .collect();
1796        names.sort();
1797        names
1798    }
1799
1800    #[test]
1801    fn typed_receiver_reaches_only_its_own_type() {
1802        // Name-based resolution sees three `run_started` and links none.
1803        assert!(callees(&receiver_fixture(&[".run_started"])).is_empty());
1804        let graph = receiver_fixture(&[".run_started@Draft"]);
1805        assert_eq!(callees(&graph), ["Draft.run_started"]);
1806        let call = graph
1807            .graph
1808            .edge_weights()
1809            .find(|edge| edge.kind == EdgeKind::Calls)
1810            .expect("the call edge");
1811        assert!((call.confidence - TYPED_RECEIVER_CONFIDENCE).abs() < 1e-6);
1812    }
1813
1814    #[test]
1815    fn typed_receiver_follows_fields_into_other_files() {
1816        let graph = receiver_fixture(&[".run_started@AppState.draft"]);
1817        assert_eq!(callees(&graph), ["Draft.run_started"]);
1818    }
1819
1820    #[test]
1821    fn trait_typed_receiver_reaches_each_implementor() {
1822        let graph = receiver_fixture(&[".run_started@RunObserver"]);
1823        assert_eq!(
1824            callees(&graph),
1825            ["Logger.run_started", "Telemetry.run_started"]
1826        );
1827    }
1828
1829    #[test]
1830    fn external_receiver_never_binds_to_a_project_method() {
1831        // `client.run_started()` on `reqwest::Client` is not Draft's method.
1832        assert!(callees(&receiver_fixture(&[".run_started@Client"])).is_empty());
1833    }
1834
1835    #[test]
1836    fn project_type_without_the_method_falls_back_to_the_name() {
1837        // A field this struct doesn't declare: the type is no longer known,
1838        // so the call is resolved by name (here: too ambiguous to link).
1839        assert!(callees(&receiver_fixture(&[".run_started@AppState.missing"])).is_empty());
1840        let mut b = GraphBuilder::new();
1841        b.add_nodes(vec![
1842            CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs")
1843                .with_references(vec![".flush@Draft".to_string()]),
1844            CodeNode::new("Draft", "Draft", NodeKind::Struct, "src/draft.rs"),
1845            CodeNode::new("flush", "Buffer.flush", NodeKind::Method, "src/buffer.rs"),
1846        ]);
1847        let graph = b.build();
1848        // Draft has no `flush` (a Deref target might): a weak name-based edge.
1849        assert_eq!(callees(&graph), ["Buffer.flush"]);
1850        assert!(only_edge_confidence(&graph) < TYPED_RECEIVER_CONFIDENCE);
1851    }
1852
1853    #[test]
1854    fn typed_receiver_follows_return_types() {
1855        let mut b = GraphBuilder::new();
1856        let mut prepare = CodeNode::new("prepare", "prepare", NodeKind::Function, "src/lib.rs")
1857            .with_references(vec![arbor_core::returns_ref("Prepared")]);
1858        prepare.line_end = 0;
1859        b.add_nodes(vec![
1860            CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs").with_references(
1861                vec![
1862                    ".run_started@prepare()".to_string(),
1863                    ".flush@mac::Prepared::capture().buffer()".to_string(),
1864                ],
1865            ),
1866            prepare,
1867            CodeNode::new("Prepared", "Prepared", NodeKind::Struct, "src/mac.rs"),
1868            CodeNode::new("Buffer", "Buffer", NodeKind::Struct, "src/buffer.rs"),
1869            CodeNode::new(
1870                "capture",
1871                "Prepared.capture",
1872                NodeKind::Method,
1873                "src/mac.rs",
1874            )
1875            .with_references(vec![arbor_core::returns_ref("Prepared")]),
1876            CodeNode::new("buffer", "Prepared.buffer", NodeKind::Method, "src/mac.rs")
1877                .with_references(vec![arbor_core::returns_ref("Buffer")]),
1878            CodeNode::new(
1879                "run_started",
1880                "Prepared.run_started",
1881                NodeKind::Method,
1882                "src/mac.rs",
1883            ),
1884            CodeNode::new(
1885                "run_started",
1886                "Other.run_started",
1887                NodeKind::Method,
1888                "src/other.rs",
1889            ),
1890            CodeNode::new(
1891                "run_started",
1892                "Third.run_started",
1893                NodeKind::Method,
1894                "src/third.rs",
1895            ),
1896            CodeNode::new("flush", "Buffer.flush", NodeKind::Method, "src/buffer.rs"),
1897            CodeNode::new("flush", "Pipe.flush", NodeKind::Method, "src/pipe.rs"),
1898            CodeNode::new("flush", "Sink.flush", NodeKind::Method, "src/sink.rs"),
1899        ]);
1900        let graph = b.build();
1901        assert_eq!(callees(&graph), ["Buffer.flush", "Prepared.run_started"]);
1902    }
1903
1904    #[test]
1905    fn field_types_are_not_calls() {
1906        assert!(
1907            callees(&receiver_fixture(&[])).is_empty(),
1908            "a field: reference is not a call"
1909        );
1910    }
1911
1912    #[test]
1913    fn unknown_receiver_with_many_candidates_is_not_linked() {
1914        // `.get` defined on three different types is noise, not evidence.
1915        let mut b = GraphBuilder::new();
1916        let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1917            .with_references(vec![".get".to_string()]);
1918        b.add_nodes(vec![caller]);
1919        for (i, owner) in ["Cache", "Store", "Config"].iter().enumerate() {
1920            b.add_nodes(vec![CodeNode::new(
1921                "get",
1922                format!("{owner}.get"),
1923                NodeKind::Method,
1924                format!("m{i}.ts"),
1925            )]);
1926        }
1927        let graph = b.build();
1928
1929        assert_eq!(
1930            graph.edge_count(),
1931            0,
1932            "over the fan-out cap, so no edge should be guessed"
1933        );
1934    }
1935
1936    #[test]
1937    fn unimported_python_bare_call_links_neither_definition() {
1938        let mut b = GraphBuilder::new();
1939        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.py")
1940            .with_references(vec!["process".to_string()]);
1941        b.add_nodes(vec![caller]);
1942        b.add_nodes(vec![CodeNode::new(
1943            "process",
1944            "process",
1945            NodeKind::Function,
1946            "src/utils.py",
1947        )]);
1948        b.add_nodes(vec![CodeNode::new(
1949            "process",
1950            "process",
1951            NodeKind::Function,
1952            "src/helpers.py",
1953        )]);
1954        let graph = b.build();
1955
1956        assert_eq!(graph.node_count(), 3, "both definitions stay in the graph");
1957        assert_eq!(
1958            graph.edge_count(),
1959            0,
1960            "an unimported bare call links to neither"
1961        );
1962    }
1963
1964    /// `far.ts` imports something, so it is a module, and its unexported
1965    /// `validate` can't be called from another file by a bare name.
1966    #[test]
1967    fn unimported_ts_cross_file_call_to_a_private_function_is_dropped() {
1968        let mut b = GraphBuilder::new();
1969        let import = CodeNode::new("./other", "./other", NodeKind::Import, "src/a/main.ts")
1970            .with_references(vec!["somethingElse".to_string()]);
1971        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1972            .with_references(vec!["validate".to_string()]);
1973        let callee_import = CodeNode::new("./util", "./util", NodeKind::Import, "src/z/far.ts")
1974            .with_references(vec!["util".to_string()]);
1975        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1976        b.add_nodes(vec![import, caller, callee_import, callee]);
1977        let graph = b.build();
1978
1979        assert_eq!(graph.edge_count(), 0);
1980    }
1981
1982    #[test]
1983    fn explicitly_imported_reference_is_strong() {
1984        let mut b = GraphBuilder::new();
1985        let import = CodeNode::new("./far", "./far", NodeKind::Import, "src/a/main.ts")
1986            .with_references(vec!["validate".to_string()]);
1987        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1988            .with_references(vec!["validate".to_string()]);
1989        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1990        b.add_nodes(vec![import, caller, callee]);
1991        let graph = b.build();
1992
1993        assert!(
1994            only_edge_confidence(&graph) >= Edge::CONFIDENT_THRESHOLD,
1995            "an explicit import is strong corroboration"
1996        );
1997    }
1998
1999    #[test]
2000    fn unimported_ts_same_dir_call_to_a_private_function_is_dropped() {
2001        let mut b = GraphBuilder::new();
2002        let import = CodeNode::new("./x", "./x", NodeKind::Import, "src/main.ts")
2003            .with_references(vec!["other".to_string()]);
2004        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
2005            .with_references(vec!["validate".to_string()]);
2006        let callee_import = CodeNode::new("./util", "./util", NodeKind::Import, "src/sibling.ts")
2007            .with_references(vec!["util".to_string()]);
2008        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/sibling.ts");
2009        b.add_nodes(vec![import, caller, callee_import, callee]);
2010        let graph = b.build();
2011
2012        assert_eq!(graph.edge_count(), 0);
2013    }
2014
2015    #[test]
2016    fn ts_same_file_bare_call_binds() {
2017        let mut b = GraphBuilder::new();
2018        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/main.ts");
2019        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
2020            .with_references(vec!["validate".to_string()]);
2021        b.add_nodes(vec![callee, caller]);
2022        let graph = b.build();
2023
2024        assert_eq!(graph.edge_count(), 1);
2025    }
2026
2027    #[test]
2028    fn build_is_deterministic_across_insertion_orders() {
2029        let make = |reverse: bool| {
2030            let mut b = GraphBuilder::new();
2031            let mut defs = vec![
2032                CodeNode::new("run", "A.run", NodeKind::Method, "src/a/a.ts"),
2033                CodeNode::new("run", "B.run", NodeKind::Method, "src/b/b.ts"),
2034            ];
2035            if reverse {
2036                defs.reverse();
2037            }
2038            b.add_nodes(vec![CodeNode::new(
2039                "main",
2040                "main",
2041                NodeKind::Function,
2042                "src/c/main.ts",
2043            )
2044            .with_references(vec!["run".to_string()])]);
2045            b.add_nodes(defs);
2046            let graph = b.build();
2047            let mut sig: Vec<String> = graph
2048                .export_edges()
2049                .into_iter()
2050                .map(|e| format!("{}->{}", e.source, e.target))
2051                .collect();
2052            sig.sort();
2053            sig
2054        };
2055
2056        assert_eq!(make(false), make(true));
2057    }
2058
2059    #[test]
2060    fn test_qualified_static_call_resolves_to_correct_class() {
2061        // Regression: `MathUtils.add()` in Calc must link to MathUtils.add, NOT to a
2062        // same-named `add` on a sibling class. Relies on the parser keeping the class
2063        // qualifier so the builder gets an exact FQN match.
2064        let mut b = GraphBuilder::new();
2065        let caller = CodeNode::new("compute", "Calc.compute", NodeKind::Method, "src/Calc.java")
2066            .with_references(vec!["MathUtils.add".to_string()]);
2067        // Same-dir sibling with a colliding bare name — the old bug linked here.
2068        let sibling = CodeNode::new("add", "Sibling.add", NodeKind::Method, "src/Sibling.java");
2069        let target = CodeNode::new(
2070            "add",
2071            "MathUtils.add",
2072            NodeKind::Method,
2073            "src/util/MathUtils.java",
2074        );
2075        b.add_nodes(vec![caller, sibling, target]);
2076        let graph = b.build();
2077
2078        let compute_idx = graph
2079            .node_indexes()
2080            .find(|&i| graph.get(i).unwrap().name == "compute")
2081            .unwrap();
2082        let callees = graph.get_callees(compute_idx);
2083        assert_eq!(callees.len(), 1, "exactly one resolved callee");
2084        assert_eq!(
2085            callees[0].qualified_name, "MathUtils.add",
2086            "static call must resolve to the qualified class, not a same-named sibling"
2087        );
2088    }
2089
2090    fn kinds_between(graph: &ArborGraph, from_q: &str, to_q: &str) -> Vec<EdgeKind> {
2091        let mut kinds = Vec::new();
2092        for edge in graph.graph.edge_references() {
2093            let source = graph.get(edge.source()).unwrap();
2094            let target = graph.get(edge.target()).unwrap();
2095            if source.qualified_name == from_q && target.qualified_name == to_q {
2096                kinds.push(edge.weight().kind);
2097            }
2098        }
2099        kinds
2100    }
2101
2102    fn inheritance_fixture() -> ArborGraph {
2103        let file = "hard/inheritance.py";
2104        let mut b = GraphBuilder::new();
2105        b.add_nodes(vec![
2106            CodeNode::new("Base", "Base", NodeKind::Class, file),
2107            CodeNode::new("compute", "Base.compute", NodeKind::Method, file),
2108            CodeNode::new("shared", "Base.shared", NodeKind::Method, file),
2109            CodeNode::new("Middle", "Middle", NodeKind::Class, file).with_extends(["Base"]),
2110            CodeNode::new("compute", "Middle.compute", NodeKind::Method, file)
2111                .with_references(vec!["super().compute".to_string()]),
2112            CodeNode::new("Derived", "Derived", NodeKind::Class, file).with_extends(["Middle"]),
2113            CodeNode::new("shared", "Derived.shared", NodeKind::Method, file),
2114            CodeNode::new("Leaf", "Leaf", NodeKind::Class, file).with_extends(["Derived"]),
2115            CodeNode::new("run", "Leaf.run", NodeKind::Method, file).with_references(vec![
2116                "self.compute".to_string(),
2117                "self.shared".to_string(),
2118                "len".to_string(),
2119            ]),
2120            // Same simple name, no superclass. Must not become an extender.
2121            CodeNode::new("UserService", "UserService", NodeKind::Class, file),
2122        ]);
2123        b.build()
2124    }
2125
2126    #[test]
2127    fn subclass_extends_its_base() {
2128        let graph = inheritance_fixture();
2129        assert_eq!(
2130            kinds_between(&graph, "Middle", "Base"),
2131            vec![EdgeKind::Extends]
2132        );
2133        assert_eq!(
2134            kinds_between(&graph, "Derived", "Middle"),
2135            vec![EdgeKind::Extends]
2136        );
2137        assert_eq!(
2138            kinds_between(&graph, "Leaf", "Derived"),
2139            vec![EdgeKind::Extends]
2140        );
2141        assert!(
2142            kinds_between(&graph, "UserService", "Base").is_empty(),
2143            "a class with no base is not an extender"
2144        );
2145
2146        let base = graph
2147            .node_indexes()
2148            .find(|&id| graph.get(id).unwrap().qualified_name == "Base")
2149            .unwrap();
2150        let reachers: Vec<_> = graph
2151            .direct_dependents(base)
2152            .into_iter()
2153            .map(|node| node.qualified_name.as_str())
2154            .collect();
2155        assert!(
2156            reachers.contains(&"Middle"),
2157            "Base is reached by Middle, got {reachers:?}"
2158        );
2159        assert!(graph.get_callers(base).is_empty(), "extends is not a call");
2160    }
2161
2162    #[test]
2163    fn inherited_method_reaches_the_defining_class_until_overridden() {
2164        let graph = inheritance_fixture();
2165
2166        // Leaf.run's self.compute binds to Middle.compute, not Base.compute.
2167        assert_eq!(
2168            kinds_between(&graph, "Leaf.run", "Middle.compute"),
2169            vec![EdgeKind::Calls]
2170        );
2171        assert!(kinds_between(&graph, "Leaf.run", "Base.compute").is_empty());
2172
2173        // super() in the override still reaches the base method.
2174        assert_eq!(
2175            kinds_between(&graph, "Middle.compute", "Base.compute"),
2176            vec![EdgeKind::Calls]
2177        );
2178
2179        // Leaf inherits compute from Middle (the nearest definition).
2180        assert_eq!(
2181            kinds_between(&graph, "Leaf", "Middle.compute"),
2182            vec![EdgeKind::References]
2183        );
2184        assert!(kinds_between(&graph, "Leaf", "Base.compute").is_empty());
2185
2186        // Derived overrides shared, so neither Derived nor Leaf reaches Base.shared.
2187        assert!(kinds_between(&graph, "Derived", "Base.shared").is_empty());
2188        assert!(kinds_between(&graph, "Leaf", "Base.shared").is_empty());
2189        assert_eq!(
2190            kinds_between(&graph, "Leaf.run", "Derived.shared"),
2191            vec![EdgeKind::Calls]
2192        );
2193        assert!(kinds_between(&graph, "Leaf.run", "Base.shared").is_empty());
2194
2195        // Middle does not override shared, so it reaches Base.shared.
2196        assert_eq!(
2197            kinds_between(&graph, "Middle", "Base.shared"),
2198            vec![EdgeKind::References]
2199        );
2200
2201        let base_compute = graph
2202            .node_indexes()
2203            .find(|&id| graph.get(id).unwrap().qualified_name == "Base.compute")
2204            .unwrap();
2205        let impact = graph.analyze_impact(base_compute, 5);
2206        let upstream: Vec<_> = impact
2207            .upstream
2208            .iter()
2209            .map(|node| node.node_info.qualified_name.as_str())
2210            .collect();
2211        assert!(
2212            upstream.contains(&"Leaf"),
2213            "changing Base.compute must reach Leaf, got {upstream:?}"
2214        );
2215
2216        let base_shared = graph
2217            .node_indexes()
2218            .find(|&id| graph.get(id).unwrap().qualified_name == "Base.shared")
2219            .unwrap();
2220        let shared_impact = graph.analyze_impact(base_shared, 5);
2221        let direct: Vec<_> = shared_impact
2222            .direct_only()
2223            .into_iter()
2224            .map(|node| node.node_info.qualified_name.clone())
2225            .collect();
2226        assert!(
2227            direct.iter().any(|name| name == "Middle"),
2228            "Middle inherits shared, got {direct:?}"
2229        );
2230        assert!(
2231            direct
2232                .iter()
2233                .all(|name| name != "Derived" && name != "Leaf" && name != "Leaf.run"),
2234            "Derived's override must not make Base.shared a direct dependency, got {direct:?}"
2235        );
2236    }
2237
2238    #[test]
2239    fn diamond_inherits_the_nearest_override() {
2240        let file = "diamond.py";
2241        let mut b = GraphBuilder::new();
2242        b.add_nodes(vec![
2243            CodeNode::new("A", "A", NodeKind::Class, file),
2244            CodeNode::new("f", "A.f", NodeKind::Method, file),
2245            CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
2246            CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["A"]),
2247            CodeNode::new("f", "C.f", NodeKind::Method, file),
2248            CodeNode::new("D", "D", NodeKind::Class, file).with_extends(["B", "C"]),
2249        ]);
2250        let graph = b.build();
2251        assert_eq!(
2252            kinds_between(&graph, "D", "C.f"),
2253            vec![EdgeKind::References],
2254            "D(B, C) sees C.f before A.f"
2255        );
2256        assert!(kinds_between(&graph, "D", "A.f").is_empty());
2257    }
2258
2259    #[test]
2260    fn super_stops_at_the_intermediate_override() {
2261        let file = "super_chain.py";
2262        let mut b = GraphBuilder::new();
2263        b.add_nodes(vec![
2264            CodeNode::new("A", "A", NodeKind::Class, file),
2265            CodeNode::new("foo", "A.foo", NodeKind::Method, file),
2266            CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
2267            CodeNode::new("foo", "B.foo", NodeKind::Method, file),
2268            CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["B"]),
2269            CodeNode::new("foo", "C.foo", NodeKind::Method, file)
2270                .with_references(vec!["super().foo".to_string()]),
2271        ]);
2272        let graph = b.build();
2273        assert_eq!(
2274            kinds_between(&graph, "C.foo", "B.foo"),
2275            vec![EdgeKind::Calls],
2276            "super() in C must reach B's override"
2277        );
2278        assert!(
2279            kinds_between(&graph, "C.foo", "A.foo").is_empty(),
2280            "super() must not skip B and land on A"
2281        );
2282    }
2283
2284    #[test]
2285    fn python_unimported_len_has_no_callers() {
2286        let mut b = GraphBuilder::new();
2287        b.add_nodes(vec![CodeNode::new(
2288            "len",
2289            "len",
2290            NodeKind::Function,
2291            "hard/stdlib_shadow.py",
2292        )]);
2293        b.add_nodes(vec![CodeNode::new(
2294            "process",
2295            "process",
2296            NodeKind::Function,
2297            "hard/shadowed.py",
2298        )
2299        .with_references(vec!["len".to_string()])]);
2300        let import = CodeNode::new(
2301            "app.core.db",
2302            "app.core.db",
2303            NodeKind::Import,
2304            "app/services/auth.py",
2305        )
2306        .with_references(vec!["connect".to_string()]);
2307        let verify = CodeNode::new(
2308            "verify_token",
2309            "verify_token",
2310            NodeKind::Function,
2311            "app/services/auth.py",
2312        )
2313        .with_references(vec!["len".to_string()]);
2314        b.add_nodes(vec![import, verify]);
2315        let graph = b.build();
2316
2317        assert!(
2318            callers_of(&graph, "len", "stdlib_shadow.py").is_empty(),
2319            "a user len must not absorb builtin-shaped calls"
2320        );
2321    }
2322
2323    #[test]
2324    fn python_local_len_binds_to_its_own_definition() {
2325        let mut b = GraphBuilder::new();
2326        let len_def = CodeNode::new("len", "len", NodeKind::Function, "hard/stdlib_shadow.py");
2327        let uses = CodeNode::new(
2328            "uses_len",
2329            "uses_len",
2330            NodeKind::Function,
2331            "hard/stdlib_shadow.py",
2332        )
2333        .with_references(vec!["len".to_string()]);
2334        b.add_nodes(vec![len_def, uses]);
2335        let graph = b.build();
2336
2337        let callers = callers_of(&graph, "len", "stdlib_shadow.py");
2338        assert_eq!(callers.len(), 1);
2339        assert_eq!(callers[0].name, "uses_len");
2340    }
2341
2342    #[test]
2343    fn python_imported_len_binds_to_the_imported_definition() {
2344        let mut b = GraphBuilder::new();
2345        b.add_nodes(vec![CodeNode::new(
2346            "len",
2347            "len",
2348            NodeKind::Function,
2349            "hard/stdlib_shadow.py",
2350        )]);
2351        let import = CodeNode::new(
2352            "hard.stdlib_shadow",
2353            "hard.stdlib_shadow",
2354            NodeKind::Import,
2355            "app/caller.py",
2356        )
2357        .with_references(vec!["len".to_string()]);
2358        let caller = CodeNode::new("use", "use", NodeKind::Function, "app/caller.py")
2359            .with_references(vec!["len".to_string()]);
2360        b.add_nodes(vec![import, caller]);
2361        let graph = b.build();
2362
2363        let callers = callers_of(&graph, "len", "stdlib_shadow.py");
2364        assert_eq!(callers.len(), 1);
2365        assert_eq!(callers[0].name, "use");
2366    }
2367
2368    #[test]
2369    fn python_star_import_keeps_a_bare_cross_file_call() {
2370        let mut b = GraphBuilder::new();
2371        b.add_nodes(vec![CodeNode::new(
2372            "len",
2373            "len",
2374            NodeKind::Function,
2375            "hard/stdlib_shadow.py",
2376        )]);
2377        let import = CodeNode::new("helpers", "helpers", NodeKind::Import, "app/caller.py")
2378            .with_references(vec!["*".to_string()]);
2379        let caller = CodeNode::new("use", "use", NodeKind::Function, "app/caller.py")
2380            .with_references(vec!["len".to_string()]);
2381        b.add_nodes(vec![import, caller]);
2382        let graph = b.build();
2383
2384        assert_eq!(callers_of(&graph, "len", "stdlib_shadow.py").len(), 1);
2385        // `*` doesn't say `len` came from `helpers`: the edge stays as weak
2386        // as main made it, never raised to the resolution's full confidence.
2387        assert!(only_edge_confidence(&graph) < Edge::CONFIDENT_THRESHOLD);
2388    }
2389
2390    #[test]
2391    fn qualified_module_call_does_not_bind_bare_len() {
2392        let mut b = GraphBuilder::new();
2393        b.add_nodes(vec![CodeNode::new(
2394            "len",
2395            "len",
2396            NodeKind::Function,
2397            "hard/stdlib_shadow.py",
2398        )]);
2399        // `import len_module` records the module, not a local name.
2400        let import = CodeNode::new(
2401            "len_module",
2402            "len_module",
2403            NodeKind::Import,
2404            "app/caller.py",
2405        );
2406        let caller = CodeNode::new("use", "use", NodeKind::Function, "app/caller.py")
2407            .with_references(vec!["len_module.len".to_string()]);
2408        b.add_nodes(vec![import, caller]);
2409        let graph = b.build();
2410
2411        assert!(callers_of(&graph, "len", "stdlib_shadow.py").is_empty());
2412    }
2413
2414    #[test]
2415    fn shadowed_process_keeps_local_and_explicitly_imported_callers() {
2416        let mut b = GraphBuilder::new();
2417        b.add_nodes(vec![
2418            CodeNode::new("process", "process", NodeKind::Function, "hard/shadowed.py"),
2419            CodeNode::new("caller", "caller", NodeKind::Function, "hard/shadowed.py")
2420                .with_references(vec!["process".to_string()]),
2421            CodeNode::new(
2422                "process",
2423                "process",
2424                NodeKind::Function,
2425                "hard/shadow_other.py",
2426            ),
2427            CodeNode::new(
2428                "other_caller",
2429                "other_caller",
2430                NodeKind::Function,
2431                "hard/shadow_other.py",
2432            )
2433            .with_references(vec!["process".to_string()]),
2434        ]);
2435        let import = CodeNode::new(
2436            "hard.shadowed",
2437            "hard.shadowed",
2438            NodeKind::Import,
2439            "hard/conditional.py",
2440        )
2441        .with_references(vec!["process".to_string()]);
2442        let imported_caller = CodeNode::new(
2443            "function_local_import",
2444            "function_local_import",
2445            NodeKind::Function,
2446            "hard/conditional.py",
2447        )
2448        .with_references(vec!["process".to_string()]);
2449        b.add_nodes(vec![import, imported_caller]);
2450        let graph = b.build();
2451
2452        let shadowed = callers_of(&graph, "process", "hard/shadowed.py");
2453        let other = callers_of(&graph, "process", "hard/shadow_other.py");
2454        assert_eq!(shadowed.len(), 2, "local caller plus the explicit import");
2455        assert_eq!(
2456            other.len(),
2457            1,
2458            "the sibling call stays on its own definition"
2459        );
2460        let mut shadowed_names: Vec<&str> = shadowed.iter().map(|n| n.name.as_str()).collect();
2461        shadowed_names.sort();
2462        assert_eq!(shadowed_names, vec!["caller", "function_local_import"]);
2463        assert_eq!(other[0].name, "other_caller");
2464    }
2465
2466    /// Torture section D. The parser records `from hard.reexport_base import
2467    /// original_function as renamed` as `alias:renamed:original_function`, so
2468    /// the alias reaches the function (#258). A call through a module alias
2469    /// (`base_mod.original_function()`) is dotted, outside this rule, and
2470    /// still has no edge.
2471    #[test]
2472    fn an_alias_reaches_the_original_function_and_a_module_alias_call_does_not() {
2473        let mut b = GraphBuilder::new();
2474        b.add_nodes(vec![CodeNode::new(
2475            "original_function",
2476            "original_function",
2477            NodeKind::Function,
2478            "hard/reexport_base.py",
2479        )]);
2480        let import = CodeNode::new(
2481            "hard.reexport_base",
2482            "hard.reexport_base",
2483            NodeKind::Import,
2484            "hard/aliased.py",
2485        )
2486        .with_references(vec![arbor_core::import_alias_ref(
2487            "renamed",
2488            "original_function",
2489        )]);
2490        let via_alias = CodeNode::new(
2491            "via_alias",
2492            "via_alias",
2493            NodeKind::Function,
2494            "hard/aliased.py",
2495        )
2496        .with_references(vec!["renamed".to_string()]);
2497        let via_module = CodeNode::new(
2498            "via_module_alias",
2499            "via_module_alias",
2500            NodeKind::Function,
2501            "hard/aliased.py",
2502        )
2503        .with_references(vec!["base_mod.original_function".to_string()]);
2504        b.add_nodes(vec![import, via_alias, via_module]);
2505        let graph = b.build();
2506
2507        let callers: Vec<&str> = callers_of(&graph, "original_function", "reexport_base.py")
2508            .iter()
2509            .map(|n| n.name.as_str())
2510            .collect();
2511        assert_eq!(callers, vec!["via_alias"]);
2512    }
2513
2514    fn callers_of<'a>(
2515        graph: &'a ArborGraph,
2516        name: &str,
2517        file_frag: &str,
2518    ) -> Vec<&'a arbor_core::CodeNode> {
2519        graph
2520            .node_indexes()
2521            .filter_map(|idx| {
2522                let node = graph.get(idx)?;
2523                if node.name == name && node.file.contains(file_frag) {
2524                    Some(graph.get_callers(idx))
2525                } else {
2526                    None
2527                }
2528            })
2529            .next()
2530            .unwrap_or_default()
2531    }
2532
2533    #[test]
2534    fn go_same_package_bare_call_is_kept() {
2535        let mut b = GraphBuilder::new();
2536        let import = CodeNode::new("fmt", "fmt", NodeKind::Import, "pkg/a.go");
2537        let caller = CodeNode::new("main", "main", NodeKind::Function, "pkg/a.go")
2538            .with_references(vec!["helper".to_string()]);
2539        let callee = CodeNode::new("helper", "helper", NodeKind::Function, "pkg/b.go");
2540        b.add_nodes(vec![
2541            go_package("handler", "pkg/a.go"),
2542            go_package("handler", "pkg/b.go"),
2543            import,
2544            caller,
2545            callee,
2546        ]);
2547        let graph = b.build();
2548
2549        assert_eq!(graph.edge_count(), 1);
2550    }
2551
2552    #[test]
2553    fn go_same_clause_in_another_directory_is_dropped() {
2554        let mut b = GraphBuilder::new();
2555        let caller = CodeNode::new("main", "main", NodeKind::Function, "cmd/a.go")
2556            .with_references(vec!["helper".to_string()]);
2557        let callee = CodeNode::new("helper", "helper", NodeKind::Function, "pkg/b.go");
2558        b.add_nodes(vec![
2559            go_package("main", "cmd/a.go"),
2560            go_package("main", "pkg/b.go"),
2561            caller,
2562            callee,
2563        ]);
2564        let graph = b.build();
2565
2566        assert_eq!(graph.edge_count(), 0);
2567    }
2568
2569    #[test]
2570    fn go_external_test_package_does_not_bind_a_bare_name() {
2571        let mut b = GraphBuilder::new();
2572        let caller = CodeNode::new(
2573            "TestHelper",
2574            "TestHelper",
2575            NodeKind::Function,
2576            "pkg/a_test.go",
2577        )
2578        .with_references(vec!["helper".to_string()]);
2579        let callee = CodeNode::new("helper", "helper", NodeKind::Function, "pkg/a.go");
2580        b.add_nodes(vec![
2581            go_package("foo_test", "pkg/a_test.go"),
2582            go_package("foo", "pkg/a.go"),
2583            caller,
2584            callee,
2585        ]);
2586        let graph = b.build();
2587
2588        assert_eq!(graph.edge_count(), 0);
2589    }
2590
2591    #[test]
2592    fn go_len_does_not_bind_to_a_python_definition() {
2593        let mut b = GraphBuilder::new();
2594        b.add_nodes(vec![CodeNode::new(
2595            "len",
2596            "len",
2597            NodeKind::Function,
2598            "hard/stdlib_shadow.py",
2599        )]);
2600        let caller = CodeNode::new(
2601            "HandleRequest",
2602            "HandleRequest",
2603            NodeKind::Function,
2604            "poly/go/handler/handler.go",
2605        )
2606        .with_references(vec!["len".to_string()]);
2607        b.add_nodes(vec![
2608            go_package("handler", "poly/go/handler/handler.go"),
2609            caller,
2610        ]);
2611        let graph = b.build();
2612
2613        assert!(callers_of(&graph, "len", "stdlib_shadow.py").is_empty());
2614    }
2615
2616    #[test]
2617    fn rust_use_does_not_drop_a_bare_cross_file_call() {
2618        assert_residual_bare_call_links("crate::helper", "src/main.rs", "src/helper.rs");
2619    }
2620
2621    #[test]
2622    fn c_include_does_not_drop_a_bare_cross_file_call() {
2623        assert_residual_bare_call_links("foo.h", "src/main.c", "src/foo.c");
2624    }
2625
2626    #[test]
2627    fn java_import_does_not_drop_a_bare_cross_file_call() {
2628        assert_residual_bare_call_links("com.example.Helper", "src/Main.java", "src/Helper.java");
2629    }
2630
2631    #[test]
2632    fn csharp_using_does_not_drop_a_bare_cross_file_call() {
2633        assert_residual_bare_call_links("Example", "src/Main.cs", "src/Helper.cs");
2634    }
2635
2636    #[test]
2637    fn dart_import_does_not_drop_a_bare_cross_file_call() {
2638        assert_residual_bare_call_links(
2639            "package:app/helper.dart",
2640            "lib/main.dart",
2641            "lib/helper.dart",
2642        );
2643    }
2644
2645    fn go_package(name: &str, file: &str) -> CodeNode {
2646        CodeNode::new(name, name, NodeKind::Module, file)
2647    }
2648
2649    /// An import node whose name is the module path and whose references do
2650    /// not include `helper`. The bare call must still link.
2651    fn assert_residual_bare_call_links(import_name: &str, caller_file: &str, callee_file: &str) {
2652        let mut b = GraphBuilder::new();
2653        let import = CodeNode::new(import_name, import_name, NodeKind::Import, caller_file);
2654        let caller = CodeNode::new("main", "main", NodeKind::Function, caller_file)
2655            .with_references(vec!["helper".to_string()]);
2656        let callee = CodeNode::new("helper", "helper", NodeKind::Function, callee_file);
2657        b.add_nodes(vec![import, caller, callee]);
2658        let graph = b.build();
2659        assert_eq!(
2660            graph.edge_count(),
2661            1,
2662            "{caller_file} should still call {callee_file}"
2663        );
2664    }
2665
2666    #[test]
2667    fn bare_name_visibility_matches_python_and_js_extensions() {
2668        assert!(bare_name_requires_import(Path::new(
2669            "hard/stdlib_shadow.py"
2670        )));
2671        assert!(bare_name_requires_import(Path::new("stubs/mod.pyi")));
2672        assert!(bare_name_requires_import(Path::new("HARD/LEN.PY")));
2673        assert!(bare_name_requires_import(Path::new("src/main.ts")));
2674        assert!(bare_name_requires_import(Path::new("src/App.tsx")));
2675        assert!(bare_name_requires_import(Path::new("src/app.js")));
2676        assert!(bare_name_requires_import(Path::new("src/app.jsx")));
2677        assert!(bare_name_requires_import(Path::new("src/app.mts")));
2678        assert!(bare_name_requires_import(Path::new("src/app.cts")));
2679        assert!(bare_name_requires_import(Path::new("src/app.mjs")));
2680        assert!(bare_name_requires_import(Path::new("src/app.cjs")));
2681        assert!(!bare_name_requires_import(Path::new("pkg/a.go")));
2682        assert!(!bare_name_requires_import(Path::new("src/main.rs")));
2683        assert!(!bare_name_requires_import(Path::new("src/Main.java")));
2684        assert!(!bare_name_requires_import(Path::new("src/Main.cs")));
2685        assert!(!bare_name_requires_import(Path::new("lib/main.dart")));
2686        assert!(!bare_name_requires_import(Path::new("src/main.c")));
2687        assert!(!bare_name_requires_import(Path::new("Makefile")));
2688    }
2689}
2690
2691#[cfg(test)]
2692mod rust_path_tests {
2693    use super::*;
2694    use arbor_core::NodeKind;
2695
2696    fn function(name: &str, file: &str, calls: &[&str]) -> CodeNode {
2697        CodeNode::new(name, name, NodeKind::Function, file)
2698            .with_references(calls.iter().map(|c| c.to_string()).collect())
2699    }
2700
2701    fn method(owner: &str, name: &str, file: &str, calls: &[&str]) -> CodeNode {
2702        CodeNode::new(name, format!("{owner}.{name}"), NodeKind::Method, file)
2703            .with_references(calls.iter().map(|c| c.to_string()).collect())
2704    }
2705
2706    fn callers_of(graph: &ArborGraph, name: &str, file: &str) -> Vec<String> {
2707        let id = graph
2708            .node_indexes()
2709            .find(|id| {
2710                graph
2711                    .get(*id)
2712                    .is_some_and(|n| n.name == name && n.file == file)
2713            })
2714            .unwrap_or_else(|| panic!("no {name} in {file}"));
2715        let mut names: Vec<String> = graph
2716            .get_callers(id)
2717            .into_iter()
2718            .map(|n| n.name.clone())
2719            .collect();
2720        names.sort();
2721        names
2722    }
2723
2724    #[test]
2725    fn module_paths_resolve_to_the_named_module_and_never_across_languages() {
2726        let mut b = GraphBuilder::new();
2727        b.add_nodes(vec![
2728            function("enqueue", "src/app/jobs.rs", &[]),
2729            function("enqueue", "src/billing/jobs_old.rs", &[]),
2730            function("enqueue", "web/src/components/Toast.tsx", &[]),
2731            function("dispatch", "src/app/dispatch.rs", &["jobs::enqueue"]),
2732            function("start", "web/src/lib/bridge.ts", &["enqueue"]),
2733        ]);
2734        let graph = b.build();
2735        assert_eq!(
2736            callers_of(&graph, "enqueue", "src/app/jobs.rs"),
2737            vec!["dispatch"]
2738        );
2739        assert!(callers_of(&graph, "enqueue", "src/billing/jobs_old.rs").is_empty());
2740        // The TypeScript call binds to the TypeScript definition only.
2741        assert_eq!(
2742            callers_of(&graph, "enqueue", "web/src/components/Toast.tsx"),
2743            vec!["start"]
2744        );
2745    }
2746
2747    #[test]
2748    fn mod_rs_crate_prefixes_and_re_exports_resolve() {
2749        let mut b = GraphBuilder::new();
2750        b.add_nodes(vec![
2751            function("create_project", "src/app/mod.rs", &[]),
2752            function("record", "src/app/audit/writer.rs", &[]),
2753            function(
2754                "handler",
2755                "src/routes/mod.rs",
2756                &["app::create_project", "app::audit::record"],
2757            ),
2758            function(
2759                "persistence_test",
2760                "tests/integration.rs",
2761                &["my_app::app::create_project", "app::record"],
2762            ),
2763        ]);
2764        let graph = b.build();
2765        assert_eq!(
2766            callers_of(&graph, "create_project", "src/app/mod.rs"),
2767            vec!["handler", "persistence_test"]
2768        );
2769        // `app::record` is a `pub use audit::writer::record` re-export.
2770        assert_eq!(
2771            callers_of(&graph, "record", "src/app/audit/writer.rs"),
2772            vec!["handler", "persistence_test"]
2773        );
2774    }
2775
2776    #[test]
2777    fn external_crate_paths_do_not_bind_to_local_names() {
2778        let mut b = GraphBuilder::new();
2779        b.add_nodes(vec![
2780            function("query", "src/db/queries.rs", &[]),
2781            function("load", "src/routes/mod.rs", &["sqlx::query"]),
2782        ]);
2783        let graph = b.build();
2784        assert!(callers_of(&graph, "query", "src/db/queries.rs").is_empty());
2785    }
2786
2787    #[test]
2788    fn type_paths_resolve_to_the_types_method() {
2789        let mut b = GraphBuilder::new();
2790        b.add_nodes(vec![
2791            CodeNode::new(
2792                "Provider",
2793                "Provider",
2794                NodeKind::Struct,
2795                "src/billing/mod.rs",
2796            ),
2797            method("Provider", "new", "src/billing/mod.rs", &[]),
2798            method("Fixture", "new", "tests/fixture.rs", &[]),
2799            function("boot", "src/main.rs", &["Provider::new"]),
2800        ]);
2801        let graph = b.build();
2802        assert_eq!(
2803            callers_of(&graph, "new", "src/billing/mod.rs"),
2804            vec!["boot"]
2805        );
2806        assert!(callers_of(&graph, "new", "tests/fixture.rs").is_empty());
2807    }
2808
2809    #[test]
2810    fn a_mock_struct_with_the_same_name_does_not_hide_the_real_owner() {
2811        let mut b = GraphBuilder::new();
2812        b.add_nodes(vec![
2813            CodeNode::new(
2814                "Provider",
2815                "Provider",
2816                NodeKind::Struct,
2817                "src/payments/mod.rs",
2818            ),
2819            CodeNode::new("Provider", "Provider", NodeKind::Struct, "tests/mocks.rs"),
2820            method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
2821            method(
2822                "Provider",
2823                "order_history",
2824                "src/payments/cancellation.rs",
2825                &["self.owner_of", ".bind"],
2826            ),
2827            function("bind", "src/payments/tests.rs", &[]),
2828        ]);
2829        let graph = b.build();
2830        assert_eq!(
2831            callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
2832            vec!["order_history"]
2833        );
2834        // `.bind(...)` is a method call; it can't reach a free function.
2835        assert!(callers_of(&graph, "bind", "src/payments/tests.rs").is_empty());
2836    }
2837
2838    #[test]
2839    fn self_calls_reach_methods_whose_impl_is_in_another_file() {
2840        let mut b = GraphBuilder::new();
2841        b.add_nodes(vec![
2842            CodeNode::new(
2843                "Provider",
2844                "Provider",
2845                NodeKind::Struct,
2846                "src/payments/mod.rs",
2847            ),
2848            method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
2849            method(
2850                "Provider",
2851                "order_history",
2852                "src/payments/cancellation.rs",
2853                &["self.owner_of"],
2854            ),
2855        ]);
2856        let graph = b.build();
2857        assert_eq!(
2858            callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
2859            vec!["order_history"]
2860        );
2861    }
2862}
2863
2864/// `from money import money_to_minor_units as to_minor` makes `to_minor()` a
2865/// call to `money.money_to_minor_units` (#258).
2866#[cfg(test)]
2867mod import_alias_tests {
2868    use super::*;
2869    use petgraph::visit::{EdgeRef, IntoEdgeReferences};
2870    use std::collections::BTreeSet;
2871
2872    /// Parses each `(path, source)` with its real language parser and builds
2873    /// the graph, as `arbor index` does.
2874    pub(super) fn index(files: &[(&str, &str)]) -> ArborGraph {
2875        let mut builder = GraphBuilder::new();
2876        for (path, source) in files {
2877            let ext = Path::new(path)
2878                .extension()
2879                .and_then(|e| e.to_str())
2880                .expect("extension");
2881            let parser = arbor_core::languages::get_parser(ext).expect("parser");
2882            builder
2883                .add_nodes(arbor_core::parse_source(source, path, parser.as_ref()).expect("parse"));
2884        }
2885        builder.build()
2886    }
2887
2888    /// Every call edge, as `file::name -> file::name`.
2889    pub(super) fn calls(graph: &ArborGraph) -> BTreeSet<String> {
2890        graph
2891            .graph
2892            .edge_references()
2893            .filter(|e| e.weight().kind == EdgeKind::Calls)
2894            .map(|e| {
2895                let from = &graph.graph[e.source()];
2896                let to = &graph.graph[e.target()];
2897                format!("{}::{} -> {}::{}", from.file, from.name, to.file, to.name)
2898            })
2899            .collect()
2900    }
2901
2902    pub(super) fn edges(expected: &[&str]) -> BTreeSet<String> {
2903        expected.iter().map(|e| e.to_string()).collect()
2904    }
2905
2906    const MONEY: &str = "\
2907def money_to_minor_units(amount, currency):
2908    return int(round(amount * 100))
2909
2910
2911def minor_unit_scale(currency):
2912    return 2
2913";
2914
2915    /// The eval corpus repro (`eval/corpus/py-alias`).
2916    #[test]
2917    fn aliased_import_call_reaches_the_imported_function() {
2918        let graph = index(&[
2919            ("money.py", MONEY),
2920            (
2921                "orders.py",
2922                "\
2923from money import money_to_minor_units as to_minor
2924
2925
2926def total_cents(items):
2927    return sum(to_minor(item[\"price\"], \"USD\") for item in items)
2928",
2929            ),
2930        ]);
2931        assert_eq!(
2932            calls(&graph),
2933            edges(&["orders.py::total_cents -> money.py::money_to_minor_units"])
2934        );
2935    }
2936
2937    #[test]
2938    fn alias_from_a_dotted_module_reaches_that_module_only() {
2939        let graph = index(&[
2940            ("billing/money.py", MONEY),
2941            ("legacy/money.py", MONEY),
2942            (
2943                "app/orders.py",
2944                "\
2945from billing.money import money_to_minor_units as to_minor
2946
2947
2948def total_cents(items):
2949    return sum(to_minor(item, \"USD\") for item in items)
2950",
2951            ),
2952        ]);
2953        assert_eq!(
2954            calls(&graph),
2955            edges(&["app/orders.py::total_cents -> billing/money.py::money_to_minor_units"])
2956        );
2957    }
2958
2959    #[test]
2960    fn alias_from_a_relative_module_reaches_the_sibling_module() {
2961        let graph = index(&[
2962            ("shop/money.py", MONEY),
2963            ("other/money.py", MONEY),
2964            (
2965                "shop/orders.py",
2966                "\
2967from .money import money_to_minor_units as to_minor
2968
2969
2970def total_cents(items):
2971    return sum(to_minor(item, \"USD\") for item in items)
2972",
2973            ),
2974        ]);
2975        assert_eq!(
2976            calls(&graph),
2977            edges(&["shop/orders.py::total_cents -> shop/money.py::money_to_minor_units"])
2978        );
2979    }
2980
2981    #[test]
2982    fn several_aliases_in_one_import_each_reach_their_own_target() {
2983        let graph = index(&[
2984            ("money.py", MONEY),
2985            (
2986                "orders.py",
2987                "\
2988from money import money_to_minor_units as to_minor, minor_unit_scale as scale
2989
2990
2991def total_cents(amount):
2992    return to_minor(amount, \"USD\") * scale(\"USD\")
2993",
2994            ),
2995            (
2996                "invoices.py",
2997                "\
2998from money import (
2999    money_to_minor_units as cents,
3000    minor_unit_scale as digits,
3001)
3002
3003
3004def invoice_total(amount):
3005    return cents(amount, \"EUR\") + digits(\"EUR\")
3006",
3007            ),
3008        ]);
3009        assert_eq!(
3010            calls(&graph),
3011            edges(&[
3012                "invoices.py::invoice_total -> money.py::minor_unit_scale",
3013                "invoices.py::invoice_total -> money.py::money_to_minor_units",
3014                "orders.py::total_cents -> money.py::minor_unit_scale",
3015                "orders.py::total_cents -> money.py::money_to_minor_units",
3016            ])
3017        );
3018    }
3019
3020    /// `fmt_b.fmt` shares the alias's name. Resolving the local name instead
3021    /// of the imported one binds the call to it.
3022    #[test]
3023    fn alias_reaches_its_target_not_a_function_named_like_the_alias() {
3024        let graph = index(&[
3025            ("fmt_a.py", "def render(value):\n    return f\"A{value}\"\n"),
3026            ("fmt_b.py", "def fmt(value):\n    return f\"B{value}\"\n"),
3027            (
3028                "app.py",
3029                "\
3030from fmt_a import render as fmt
3031
3032
3033def show(value):
3034    return fmt(value)
3035",
3036            ),
3037        ]);
3038        assert_eq!(calls(&graph), edges(&["app.py::show -> fmt_a.py::render"]));
3039    }
3040
3041    /// Only a call creates an edge: `scale` is imported and never called, and
3042    /// `describe` calls neither alias.
3043    #[test]
3044    fn an_alias_that_is_never_called_adds_no_edge() {
3045        let graph = index(&[
3046            ("money.py", MONEY),
3047            (
3048                "orders.py",
3049                "\
3050from money import money_to_minor_units as to_minor, minor_unit_scale as scale
3051
3052
3053def total_cents(amount):
3054    return to_minor(amount, \"USD\")
3055
3056
3057def describe(order):
3058    return str(order)
3059",
3060            ),
3061        ]);
3062        assert_eq!(
3063            calls(&graph),
3064            edges(&["orders.py::total_cents -> money.py::money_to_minor_units"])
3065        );
3066    }
3067
3068    /// A compatibility wrapper that keeps the imported function's name. The
3069    /// import names another module, so the call is not a call to itself.
3070    #[test]
3071    fn a_wrapper_named_like_the_imported_function_reaches_the_import() {
3072        let graph = index(&[
3073            ("money.py", MONEY),
3074            (
3075                "compat.py",
3076                "\
3077from money import money_to_minor_units as _impl
3078
3079
3080def money_to_minor_units(amount):
3081    return _impl(amount, \"USD\")
3082",
3083            ),
3084        ]);
3085        assert_eq!(
3086            calls(&graph),
3087            edges(&["compat.py::money_to_minor_units -> money.py::money_to_minor_units"])
3088        );
3089    }
3090
3091    /// As with an unaliased import, a definition in the caller's own file
3092    /// outranks the import.
3093    #[test]
3094    fn a_local_definition_of_the_alias_name_still_shadows_the_import() {
3095        let graph = index(&[
3096            ("money.py", MONEY),
3097            (
3098                "orders.py",
3099                "\
3100from money import money_to_minor_units as to_minor
3101
3102
3103def to_minor(amount, currency):
3104    return amount
3105
3106
3107def total_cents(amount):
3108    return to_minor(amount, \"USD\")
3109",
3110            ),
3111        ]);
3112        assert_eq!(
3113            calls(&graph),
3114            edges(&["orders.py::total_cents -> orders.py::to_minor"])
3115        );
3116    }
3117
3118    /// `numpy` is not in the project, so its `array` is not the project's.
3119    #[test]
3120    fn an_alias_of_an_external_name_links_nothing() {
3121        let graph = index(&[
3122            (
3123                "helpers.py",
3124                "def array(values):\n    return list(values)\n",
3125            ),
3126            (
3127                "calc.py",
3128                "\
3129from numpy import array as arr
3130
3131
3132def build(values):
3133    return arr(values)
3134",
3135            ),
3136        ]);
3137        assert_eq!(calls(&graph), edges(&[]));
3138    }
3139
3140    /// A typed package's `__init__.pyi` is a stub, not the module that runs:
3141    /// `__init__.py` re-exports the implementation from a submodule. The stub
3142    /// doesn't outrank the implementation, so the alias reaches what the
3143    /// plain import reaches.
3144    #[test]
3145    fn a_package_stub_does_not_hide_the_implementation_from_an_alias() {
3146        let graph = index(&[
3147            ("attr/__init__.pyi", "def evolve(inst, **changes): ...\n"),
3148            ("attr/__init__.py", "from ._funcs import evolve\n"),
3149            (
3150                "attr/_funcs.py",
3151                "def evolve(inst, **changes):\n    return inst\n",
3152            ),
3153            (
3154                "app.py",
3155                "\
3156from attr import evolve as ev
3157
3158
3159def run(x):
3160    return ev(x)
3161",
3162            ),
3163            (
3164                "plain.py",
3165                "\
3166from attr import evolve
3167
3168
3169def run2(x):
3170    return evolve(x)
3171",
3172            ),
3173        ]);
3174        let reached = |caller: &str| -> BTreeSet<String> {
3175            calls(&graph)
3176                .into_iter()
3177                .filter_map(|e| e.strip_prefix(&format!("{caller} -> ")).map(str::to_string))
3178                .collect()
3179        };
3180        assert!(reached("app.py::run").contains("attr/_funcs.py::evolve"));
3181        assert_eq!(reached("app.py::run"), reached("plain.py::run2"));
3182    }
3183
3184    /// Known limit: a module is matched by name, so an external module (Node's
3185    /// `http`) that shares its name with a project file binds to that file.
3186    /// The alias binds exactly as the unaliased import does, no further.
3187    #[test]
3188    fn an_external_module_named_like_a_project_file_binds_like_a_plain_import() {
3189        let graph = index(&[
3190            (
3191                "src/lib/http.ts",
3192                "export function request(url: string): string {\n  return url;\n}\n",
3193            ),
3194            (
3195                "src/aliased.ts",
3196                "\
3197import { request as httpRequest } from \"http\";
3198
3199export function go(url: string): string {
3200  return httpRequest(url);
3201}
3202",
3203            ),
3204            (
3205                "src/plain.ts",
3206                "\
3207import { request } from \"http\";
3208
3209export function go(url: string): string {
3210  return request(url);
3211}
3212",
3213            ),
3214        ]);
3215        assert_eq!(
3216            calls(&graph),
3217            edges(&[
3218                "src/aliased.ts::go -> src/lib/http.ts::request",
3219                "src/plain.ts::go -> src/lib/http.ts::request",
3220            ])
3221        );
3222    }
3223
3224    /// `import { formatName as fmt } from "./format"` has the same gap: the
3225    /// import recorded only `fmt`.
3226    #[test]
3227    fn typescript_named_import_alias_reaches_the_imported_function() {
3228        let graph = index(&[
3229            (
3230                "format.ts",
3231                "export function formatName(first: string, last: string): string {\n  return `${last}, ${first}`;\n}\n",
3232            ),
3233            (
3234                "legacy/fmt.ts",
3235                "export function fmt(value: string): string {\n  return value;\n}\n",
3236            ),
3237            (
3238                "app.ts",
3239                "\
3240import { formatName as fmt } from \"./format\";
3241
3242export function label(first: string, last: string): string {
3243  return fmt(first, last);
3244}
3245",
3246            ),
3247        ]);
3248        assert_eq!(
3249            calls(&graph),
3250            edges(&["app.ts::label -> format.ts::formatName"])
3251        );
3252    }
3253
3254    /// `../route` is one file, read from the importing file's directory. A
3255    /// Next.js app has a `route.ts` per endpoint, each exporting `POST`.
3256    #[test]
3257    fn a_relative_typescript_alias_reaches_only_the_file_it_names() {
3258        let post = "export async function POST(req: Request) {\n  return req;\n}\n";
3259        let graph = index(&[
3260            ("app/api/subscribe/route.ts", post),
3261            ("app/api/waitlist/route.ts", post),
3262            ("app/api/admin/route.ts", post),
3263            (
3264                "app/api/subscribe/__tests__/route.test.ts",
3265                "\
3266import { POST as subscribe } from \"../route\";
3267
3268export async function postsTheForm(req: Request) {
3269  return subscribe(req);
3270}
3271",
3272            ),
3273        ]);
3274        assert_eq!(
3275            calls(&graph),
3276            edges(&[
3277                "app/api/subscribe/__tests__/route.test.ts::postsTheForm -> app/api/subscribe/route.ts::POST"
3278            ])
3279        );
3280    }
3281
3282    /// `..money` is the parent package's `money`, not any `money.py`.
3283    #[test]
3284    fn a_relative_python_alias_reaches_only_the_module_it_names() {
3285        let graph = index(&[
3286            ("shop/money.py", MONEY),
3287            ("other/money.py", MONEY),
3288            (
3289                "shop/checkout/orders.py",
3290                "\
3291from ..money import money_to_minor_units as to_minor
3292
3293
3294def total_cents(amount):
3295    return to_minor(amount, \"USD\")
3296",
3297            ),
3298        ]);
3299        assert_eq!(
3300            calls(&graph),
3301            edges(&["shop/checkout/orders.py::total_cents -> shop/money.py::money_to_minor_units"])
3302        );
3303    }
3304
3305    /// `pkg/__init__.py` is the module `pkg` itself, so it is the target and a
3306    /// submodule that defines the same name is not.
3307    #[test]
3308    fn an_alias_from_a_package_reaches_its_init_not_a_submodule() {
3309        let graph = index(&[
3310            ("pkg/__init__.py", "def f(x):\n    return x\n"),
3311            ("pkg/sub.py", "def f(x):\n    return -x\n"),
3312            (
3313                "app.py",
3314                "\
3315from pkg import f as g
3316
3317
3318def run(x):
3319    return g(x)
3320",
3321            ),
3322        ]);
3323        assert_eq!(calls(&graph), edges(&["app.py::run -> pkg/__init__.py::f"]));
3324    }
3325
3326    /// `subscribe/route.ts` only re-exports `POST` from another file, so the
3327    /// name is not defined where the import points. Nothing else named `POST`
3328    /// is the target.
3329    #[test]
3330    fn a_relative_alias_to_a_re_export_links_nothing_else() {
3331        let post = "export async function POST(req: Request) {\n  return req;\n}\n";
3332        let graph = index(&[
3333            (
3334                "app/api/subscribe/route.ts",
3335                "export { POST } from \"../waitlist/route\";\n",
3336            ),
3337            ("app/api/admin/route.ts", post),
3338            ("app/api/reports/route.ts", post),
3339            (
3340                "app/api/subscribe/__tests__/route.test.ts",
3341                "\
3342import { POST as subscribe } from \"../route\";
3343
3344export async function postsTheForm(req: Request) {
3345  return subscribe(req);
3346}
3347",
3348            ),
3349        ]);
3350        assert_eq!(calls(&graph), edges(&[]));
3351    }
3352}
3353
3354/// The bare-name visibility rule keeps a JavaScript or TypeScript call to
3355/// another file only when the caller imports the name. CommonJS `require`,
3356/// TypeScript's `import x = require()` and an awaited `import()` bind names
3357/// too, so they have to reach the import map like an ES `import` does.
3358#[cfg(test)]
3359mod commonjs_visibility_tests {
3360    use super::import_alias_tests::{calls, edges, index};
3361
3362    /// A private `helper` in another directory's module, so the tests that use
3363    /// it pass only when the import, not a fallback, picks the target.
3364    const DECOY_HELPER_JS: &str =
3365        "const fs = require(\"fs\");\n\nfunction helper(x) {\n  return fs.existsSync(x);\n}\n";
3366
3367    const UTILS: &str = "\
3368function helper(x) {
3369  return x * 2;
3370}
3371
3372module.exports = { helper };
3373";
3374
3375    /// The repro from review: one caller on main, none with the rule alone.
3376    #[test]
3377    fn a_destructured_require_keeps_the_call() {
3378        let graph = index(&[
3379            ("utils.js", UTILS),
3380            (
3381                "index.js",
3382                "\
3383const { helper } = require(\"./utils\");
3384
3385function main() {
3386  return helper(21);
3387}
3388",
3389            ),
3390        ]);
3391        assert_eq!(
3392            calls(&graph),
3393            edges(&["index.js::main -> utils.js::helper"])
3394        );
3395    }
3396
3397    /// `{ helper: twice }` is `import { helper as twice }`: the call reaches
3398    /// `helper`, not a function that happens to be named `twice`.
3399    #[test]
3400    fn a_renamed_destructured_require_reaches_the_exported_name() {
3401        let graph = index(&[
3402            ("utils.js", UTILS),
3403            (
3404                "legacy/twice.js",
3405                "function twice(x) {\n  return x + x;\n}\n",
3406            ),
3407            (
3408                "index.js",
3409                "\
3410const { helper: twice } = require(\"./utils\");
3411
3412function main() {
3413  return twice(21);
3414}
3415",
3416            ),
3417        ]);
3418        assert_eq!(
3419            calls(&graph),
3420            edges(&["index.js::main -> utils.js::helper"])
3421        );
3422    }
3423
3424    /// `const twice = require("./utils").helper` names one export too.
3425    #[test]
3426    fn a_property_of_a_required_module_reaches_that_export() {
3427        let graph = index(&[
3428            ("utils.js", UTILS),
3429            (
3430                "legacy/twice.js",
3431                "function twice(x) {\n  return x + x;\n}\n",
3432            ),
3433            (
3434                "index.js",
3435                "\
3436const twice = require(\"./utils\").helper;
3437
3438function main() {
3439  return twice(21);
3440}
3441",
3442            ),
3443        ]);
3444        assert_eq!(
3445            calls(&graph),
3446            edges(&["index.js::main -> utils.js::helper"])
3447        );
3448    }
3449
3450    /// `module.exports = helper`: the required value is the function itself,
3451    /// as with a default import.
3452    #[test]
3453    fn a_required_module_called_directly_keeps_the_call() {
3454        let graph = index(&[
3455            (
3456                "helper.js",
3457                "function helper(x) {\n  return x * 2;\n}\n\nmodule.exports = helper;\n",
3458            ),
3459            ("lib/helper.js", DECOY_HELPER_JS),
3460            (
3461                "index.js",
3462                "\
3463const helper = require(\"./helper\");
3464
3465function main() {
3466  return helper(21);
3467}
3468",
3469            ),
3470        ]);
3471        assert_eq!(
3472            calls(&graph),
3473            edges(&["index.js::main -> helper.js::helper"])
3474        );
3475        assert!(confidence(&graph, "index.js::main", "helper.js::helper").unwrap() >= 0.95);
3476    }
3477
3478    /// Dependency injection through a factory the module exports: the names
3479    /// come from a call on the required module, so they are the module's.
3480    #[test]
3481    fn names_destructured_from_a_required_factory_keep_the_call() {
3482        let graph = index(&[
3483            (
3484                "services/paged.js",
3485                "\
3486const db = require(\"./db\");
3487
3488function createPagedReads(prisma) {
3489  async function getOrderDetail(id) {
3490    return prisma.find(id);
3491  }
3492  return { getOrderDetail };
3493}
3494
3495module.exports = { createPagedReads };
3496",
3497            ),
3498            (
3499                "services/orders.js",
3500                "\
3501const prisma = require(\"./prisma\");
3502const { getOrderDetail } = require(\"./paged\").createPagedReads(prisma);
3503
3504async function getOrderById(id) {
3505  return getOrderDetail(id);
3506}
3507",
3508            ),
3509        ]);
3510        assert_eq!(
3511            calls(&graph),
3512            edges(&["services/orders.js::getOrderById -> services/paged.js::getOrderDetail"])
3513        );
3514    }
3515
3516    /// A React custom hook: the setter comes from the return value of a hook
3517    /// the file imports, so it is the hook module's function, not the
3518    /// exported function of the same name in another file.
3519    #[test]
3520    fn names_destructured_from_an_imported_hook_reach_the_hook_module() {
3521        let graph = index(&[
3522            (
3523                "hooks/useListState.js",
3524                "\
3525export function useListFilters(defaults) {
3526  function setFilters(patch) {
3527    return { ...defaults, ...patch };
3528  }
3529  return { setFilters };
3530}
3531",
3532            ),
3533            (
3534                "components/Search.jsx",
3535                "export function setFilters(event) {\n  return event;\n}\n",
3536            ),
3537            (
3538                "pages/Orders.jsx",
3539                "\
3540import { useListFilters } from \"../hooks/useListState\";
3541
3542export function Orders() {
3543  const { setFilters } = useListFilters({});
3544  return setFilters({ q: \"\" });
3545}
3546",
3547            ),
3548        ]);
3549        assert_eq!(
3550            calls(&graph),
3551            edges(&[
3552                "pages/Orders.jsx::Orders -> hooks/useListState.js::setFilters",
3553                "pages/Orders.jsx::Orders -> hooks/useListState.js::useListFilters",
3554            ])
3555        );
3556    }
3557
3558    /// A name destructured from an external hook's return value may hold any
3559    /// function, so a call to it keeps the weak edge main gave it, and never
3560    /// an import's confidence.
3561    #[test]
3562    fn names_destructured_from_an_external_hook_keep_only_a_weak_edge() {
3563        let graph = index(&[
3564            (
3565                "components/Other.jsx",
3566                "export function handleSubmit(event) {\n  return event;\n}\n",
3567            ),
3568            (
3569                "components/Form.jsx",
3570                "\
3571import { useForm } from \"react-hook-form\";
3572
3573export function Form({ save }) {
3574  const { handleSubmit } = useForm();
3575  return handleSubmit(save);
3576}
3577",
3578            ),
3579        ]);
3580        assert_eq!(
3581            calls(&graph),
3582            edges(&["components/Form.jsx::Form -> components/Other.jsx::handleSubmit"])
3583        );
3584        let weak = confidence(
3585            &graph,
3586            "components/Form.jsx::Form",
3587            "components/Other.jsx::handleSubmit",
3588        )
3589        .unwrap();
3590        assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3591    }
3592
3593    const AUTH_CONTEXT: &str = "\
3594import { createContext } from \"react\";
3595
3596export const AuthContext = createContext(null);
3597
3598export function AuthProvider({ children }) {
3599  function login(email) {
3600    return email;
3601  }
3602  return <AuthContext.Provider value={{ login }}>{children}</AuthContext.Provider>;
3603}
3604";
3605
3606    /// `useContext(AuthContext)` hands out the provider's inner `login`. The
3607    /// name is bound from React's hook, so it can't be pinned, but the file
3608    /// binds it, so the call keeps main's weak edge.
3609    #[test]
3610    fn a_name_from_use_context_keeps_a_weak_edge_to_the_provider() {
3611        let graph = index(&[
3612            ("context/AuthContext.jsx", AUTH_CONTEXT),
3613            (
3614                "pages/Login.jsx",
3615                "\
3616import { useContext } from \"react\";
3617import { AuthContext } from \"../context/AuthContext\";
3618
3619export function Login() {
3620  const { login } = useContext(AuthContext);
3621  return login(\"a@b.c\");
3622}
3623",
3624            ),
3625        ]);
3626        assert_eq!(
3627            calls(&graph),
3628            edges(&["pages/Login.jsx::Login -> context/AuthContext.jsx::login"])
3629        );
3630        let weak = confidence(
3631            &graph,
3632            "pages/Login.jsx::Login",
3633            "context/AuthContext.jsx::login",
3634        )
3635        .unwrap();
3636        assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3637    }
3638
3639    /// The hook lives apart from the provider, so its module doesn't define
3640    /// `login`. The pinned lookup finds nothing there, and the call falls back
3641    /// to main's weak edge instead of disappearing.
3642    #[test]
3643    fn a_hook_apart_from_its_provider_keeps_a_weak_edge() {
3644        let graph = index(&[
3645            ("context/AuthContext.jsx", AUTH_CONTEXT),
3646            (
3647                "hooks/useAuth.js",
3648                "\
3649import { useContext } from \"react\";
3650import { AuthContext } from \"../context/AuthContext\";
3651
3652export function useAuth() {
3653  return useContext(AuthContext);
3654}
3655",
3656            ),
3657            (
3658                "pages/Login.jsx",
3659                "\
3660import { useAuth } from \"../hooks/useAuth\";
3661
3662export function Login() {
3663  const { login } = useAuth();
3664  return login(\"a@b.c\");
3665}
3666",
3667            ),
3668        ]);
3669        assert_eq!(
3670            calls(&graph),
3671            edges(&[
3672                "pages/Login.jsx::Login -> context/AuthContext.jsx::login",
3673                "pages/Login.jsx::Login -> hooks/useAuth.js::useAuth",
3674            ])
3675        );
3676        let weak = confidence(
3677            &graph,
3678            "pages/Login.jsx::Login",
3679            "context/AuthContext.jsx::login",
3680        )
3681        .unwrap();
3682        assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3683    }
3684
3685    /// Two functions bind `handler` from two modules. One file-level map can
3686    /// hold only one, so neither is trusted: both callers keep weak edges to
3687    /// both handlers, as on main, instead of both going to the last module at
3688    /// an import's confidence.
3689    #[test]
3690    fn a_name_bound_from_two_modules_in_two_functions_is_not_pinned() {
3691        let handler = "const fs = require(\"fs\");\n\nasync function handler(event) {\n  return fs.existsSync(event);\n}\n\nmodule.exports = { handler };\n";
3692        let graph = index(&[
3693            ("lambdas/a.js", handler),
3694            ("lambdas/b.js", handler),
3695            (
3696                "test/handlers.test.js",
3697                "\
3698const assert = require(\"assert\");
3699
3700async function runA() {
3701  const { handler } = require(\"../lambdas/a\");
3702  return handler({});
3703}
3704
3705async function runB() {
3706  const { handler } = require(\"../lambdas/b\");
3707  return handler({});
3708}
3709",
3710            ),
3711        ]);
3712        assert_eq!(
3713            calls(&graph),
3714            edges(&[
3715                "test/handlers.test.js::runA -> lambdas/a.js::handler",
3716                "test/handlers.test.js::runA -> lambdas/b.js::handler",
3717                "test/handlers.test.js::runB -> lambdas/a.js::handler",
3718                "test/handlers.test.js::runB -> lambdas/b.js::handler",
3719            ])
3720        );
3721        for run in ["runA", "runB"] {
3722            for module in ["a", "b"] {
3723                let weak = confidence(
3724                    &graph,
3725                    &format!("test/handlers.test.js::{run}"),
3726                    &format!("lambdas/{module}.js::handler"),
3727                )
3728                .unwrap();
3729                assert!(
3730                    weak < super::Edge::CONFIDENT_THRESHOLD,
3731                    "{run} -> {module}: {weak}"
3732                );
3733            }
3734        }
3735    }
3736
3737    /// A function parameter is a binding too: `onSave` holds whatever the
3738    /// caller passed, so the call keeps main's weak edge.
3739    #[test]
3740    fn a_call_through_a_parameter_keeps_a_weak_edge() {
3741        let graph = index(&[
3742            (
3743                "components/Editor.jsx",
3744                "\
3745import { useState } from \"react\";
3746
3747export function Editor() {
3748  function onSave(value) {
3749    return value;
3750  }
3751  return <Button onSave={onSave} />;
3752}
3753",
3754            ),
3755            (
3756                "components/Button.jsx",
3757                "\
3758import { useRef } from \"react\";
3759
3760export function Button({ onSave }) {
3761  return onSave(1);
3762}
3763",
3764            ),
3765        ]);
3766        let weak = confidence(
3767            &graph,
3768            "components/Button.jsx::Button",
3769            "components/Editor.jsx::onSave",
3770        )
3771        .expect("the parameter call keeps an edge");
3772        assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3773    }
3774
3775    /// A CommonJS module that requires nothing is still a module: its
3776    /// functions aren't globals, so Jest's global `expect()` doesn't reach
3777    /// its private `expect` helper.
3778    #[test]
3779    fn a_commonjs_module_without_requires_is_not_a_script() {
3780        let graph = index(&[
3781            (
3782                "scripts/verify.cjs",
3783                "function expect(path, status) {\n  return path;\n}\n\nmodule.exports = { expect };\n",
3784            ),
3785            (
3786                "src/add.ts",
3787                "export function add(a: number, b: number): number {\n  return a + b;\n}\n",
3788            ),
3789            (
3790                "src/__tests__/add.test.ts",
3791                "\
3792import { add } from \"../add\";
3793
3794export function addsTwoNumbers() {
3795  return expect(add(1, 2)).toBe(3);
3796}
3797",
3798            ),
3799        ]);
3800        assert_eq!(
3801            calls(&graph),
3802            edges(&["src/__tests__/add.test.ts::addsTwoNumbers -> src/add.ts::add"])
3803        );
3804    }
3805
3806    /// TypeScript's own CommonJS import form.
3807    #[test]
3808    fn a_typescript_import_require_keeps_the_call() {
3809        let graph = index(&[
3810            (
3811                "helper.ts",
3812                "function helper(x: number): number {\n  return x * 2;\n}\n\nexport = helper;\n",
3813            ),
3814            (
3815                "lib/helper.ts",
3816                "import fs from \"fs\";\n\nfunction helper(x: number): number {\n  return x;\n}\n",
3817            ),
3818            (
3819                "index.ts",
3820                "\
3821import helper = require(\"./helper\");
3822
3823export function main(): number {
3824  return helper(21);
3825}
3826",
3827            ),
3828        ]);
3829        assert_eq!(
3830            calls(&graph),
3831            edges(&["index.ts::main -> helper.ts::helper"])
3832        );
3833        assert!(confidence(&graph, "index.ts::main", "helper.ts::helper").unwrap() >= 0.95);
3834    }
3835
3836    /// An awaited `import()` destructures named exports like `require` does.
3837    #[test]
3838    fn a_destructured_dynamic_import_keeps_the_call() {
3839        let graph = index(&[
3840            (
3841                "utils.mjs",
3842                "export function helper(x) {\n  return x * 2;\n}\n",
3843            ),
3844            (
3845                "lib/other.mjs",
3846                "import fs from \"fs\";\n\nexport function helper(x) {\n  return x;\n}\n",
3847            ),
3848            (
3849                "index.mjs",
3850                "\
3851export async function main() {
3852  const { helper } = await import(\"./utils.mjs\");
3853  return helper(21);
3854}
3855",
3856            ),
3857        ]);
3858        assert_eq!(
3859            calls(&graph),
3860            edges(&["index.mjs::main -> utils.mjs::helper"])
3861        );
3862        assert!(confidence(&graph, "index.mjs::main", "utils.mjs::helper").unwrap() >= 0.95);
3863    }
3864
3865    /// Requiring some names does not make every other name visible.
3866    #[test]
3867    fn a_name_the_file_does_not_require_is_still_dropped() {
3868        let graph = index(&[
3869            ("utils.js", UTILS),
3870            (
3871                "other.js",
3872                "const path = require(\"path\");\n\nfunction other(x) {\n  return path.basename(x);\n}\n\nmodule.exports = { other };\n",
3873            ),
3874            (
3875                "index.js",
3876                "\
3877const { helper } = require(\"./utils\");
3878
3879function main() {
3880  return other(helper(21));
3881}
3882",
3883            ),
3884        ]);
3885        assert_eq!(
3886            calls(&graph),
3887            edges(&["index.js::main -> utils.js::helper"])
3888        );
3889    }
3890
3891    /// A file with no import or `require` may be a classic script, whose
3892    /// top-level functions are globals shared with the page's other scripts.
3893    #[test]
3894    fn a_script_with_no_imports_keeps_its_bare_calls() {
3895        let graph = index(&[
3896            (
3897                "legacy/format.js",
3898                "function formatPrice(x) {\n  return \"$\" + x;\n}\n",
3899            ),
3900            (
3901                "legacy/cart.js",
3902                "function render(total) {\n  return formatPrice(total);\n}\n",
3903            ),
3904        ]);
3905        assert_eq!(
3906            calls(&graph),
3907            edges(&["legacy/cart.js::render -> legacy/format.js::formatPrice"])
3908        );
3909    }
3910
3911    /// The confidence of the call edge `from -> to`, written as in [`calls`].
3912    fn confidence(graph: &super::ArborGraph, from: &str, to: &str) -> Option<f32> {
3913        use petgraph::visit::{EdgeRef, IntoEdgeReferences};
3914        graph
3915            .graph
3916            .edge_references()
3917            .filter(|e| e.weight().kind == super::EdgeKind::Calls)
3918            .find(|e| {
3919                let source = &graph.graph[e.source()];
3920                let target = &graph.graph[e.target()];
3921                format!("{}::{}", source.file, source.name) == from
3922                    && format!("{}::{}", target.file, target.name) == to
3923            })
3924            .map(|e| e.weight().confidence)
3925    }
3926
3927    /// Jest's `jest.resetModules()` pattern: the test binds the export from
3928    /// an `await import()` inside a helper, which no import records. The
3929    /// function is exported, so another module can reach it this way; the
3930    /// call keeps a weak edge, as on main.
3931    #[test]
3932    fn an_exported_function_bound_through_a_helper_keeps_a_weak_edge() {
3933        let graph = index(&[
3934            (
3935                "lib/razorpay.ts",
3936                "export function verifyPaymentSignature(sig: string): boolean {\n  return sig.length > 0;\n}\n",
3937            ),
3938            (
3939                "lib/__tests__/razorpay.test.ts",
3940                "\
3941import crypto from \"crypto\";
3942
3943async function loadModule() {
3944  return await import(\"../razorpay\");
3945}
3946
3947export async function acceptsAValidSignature() {
3948  const { verifyPaymentSignature } = await loadModule();
3949  return verifyPaymentSignature(crypto.randomUUID());
3950}
3951",
3952            ),
3953        ]);
3954        let test = "lib/__tests__/razorpay.test.ts::acceptsAValidSignature";
3955        assert_eq!(
3956            calls(&graph),
3957            edges(&[
3958                "lib/__tests__/razorpay.test.ts::acceptsAValidSignature -> lib/__tests__/razorpay.test.ts::loadModule",
3959                "lib/__tests__/razorpay.test.ts::acceptsAValidSignature -> lib/razorpay.ts::verifyPaymentSignature",
3960            ])
3961        );
3962        let weak = confidence(&graph, test, "lib/razorpay.ts::verifyPaymentSignature").unwrap();
3963        assert!(
3964            weak > 0.0 && weak < super::Edge::CONFIDENT_THRESHOLD,
3965            "unproven, so weak: {weak}"
3966        );
3967    }
3968
3969    /// Next.js `dynamic()` loads a component without a static import.
3970    #[test]
3971    fn an_exported_component_loaded_with_next_dynamic_keeps_a_weak_edge() {
3972        let graph = index(&[
3973            (
3974                "components/TrendsChart.tsx",
3975                "export function TrendsChart({ points }: { points: number[] }) {\n  return <svg>{points.length}</svg>;\n}\n",
3976            ),
3977            (
3978                "app/trends/page.tsx",
3979                "\
3980import dynamic from \"next/dynamic\";
3981
3982const TrendsChart = dynamic(() =>
3983  import(\"../../components/TrendsChart\").then((m) => ({ default: m.TrendsChart })),
3984);
3985
3986export function TrendsPage() {
3987  return <TrendsChart points={[]} />;
3988}
3989",
3990            ),
3991        ]);
3992        assert_eq!(
3993            calls(&graph),
3994            edges(&["app/trends/page.tsx::TrendsPage -> components/TrendsChart.tsx::TrendsChart"])
3995        );
3996        let weak = confidence(
3997            &graph,
3998            "app/trends/page.tsx::TrendsPage",
3999            "components/TrendsChart.tsx::TrendsChart",
4000        )
4001        .unwrap();
4002        assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
4003    }
4004
4005    /// A function a module doesn't export can't be called from another
4006    /// module by a bare name: a Jest test's global `expect` is not a script's
4007    /// private `expect` helper.
4008    #[test]
4009    fn a_module_private_function_is_not_reached_from_another_module() {
4010        let graph = index(&[
4011            (
4012                "scripts/verify-site.mjs",
4013                "\
4014import { strict as assert } from \"node:assert\";
4015
4016async function expect(path, status) {
4017  assert.ok(path, status);
4018}
4019",
4020            ),
4021            (
4022                "src/add.ts",
4023                "export function add(a: number, b: number): number {\n  return a + b;\n}\n",
4024            ),
4025            (
4026                "src/__tests__/add.test.ts",
4027                "\
4028import { add } from \"../add\";
4029
4030export function addsTwoNumbers() {
4031  return expect(add(1, 2)).toBe(3);
4032}
4033",
4034            ),
4035        ]);
4036        assert_eq!(
4037            calls(&graph),
4038            edges(&["src/__tests__/add.test.ts::addsTwoNumbers -> src/add.ts::add"])
4039        );
4040    }
4041
4042    /// A classic script's top-level functions are page globals, so a module
4043    /// can call one by a bare name. Unproven, so the edge is weak.
4044    #[test]
4045    fn a_classic_script_function_keeps_a_weak_edge_from_a_module() {
4046        let graph = index(&[
4047            (
4048                "legacy/format.js",
4049                "function formatPrice(x) {\n  return \"$\" + x;\n}\n",
4050            ),
4051            (
4052                "src/cart.ts",
4053                "\
4054import { total } from \"./total\";
4055
4056export function render(): string {
4057  return formatPrice(total());
4058}
4059",
4060            ),
4061            (
4062                "src/total.ts",
4063                "export function total(): number {\n  return 1;\n}\n",
4064            ),
4065        ]);
4066        assert_eq!(
4067            calls(&graph),
4068            edges(&[
4069                "src/cart.ts::render -> legacy/format.js::formatPrice",
4070                "src/cart.ts::render -> src/total.ts::total",
4071            ])
4072        );
4073        let weak = confidence(
4074            &graph,
4075            "src/cart.ts::render",
4076            "legacy/format.js::formatPrice",
4077        )
4078        .unwrap();
4079        assert!(
4080            weak > 0.0 && weak < super::Edge::CONFIDENT_THRESHOLD,
4081            "{weak}"
4082        );
4083    }
4084
4085    /// A file whose only import is a namespace import, and which exports
4086    /// nothing, is still a module: its private function can't be reached by
4087    /// another module's bare call.
4088    #[test]
4089    fn a_file_with_only_a_namespace_import_is_a_module() {
4090        let graph = index(&[
4091            (
4092                "format.ts",
4093                "export function pad(x: string): string {\n  return x;\n}\n",
4094            ),
4095            (
4096                "helpers.ts",
4097                "import * as fmt from \"./format\";\n\nfunction other(x: string): string {\n  return fmt.pad(x);\n}\n",
4098            ),
4099            (
4100                "app.ts",
4101                "\
4102import { pad } from \"./format\";
4103
4104export function show(x: string): string {
4105  return other(pad(x));
4106}
4107",
4108            ),
4109        ]);
4110        assert!(
4111            confidence(&graph, "app.ts::show", "helpers.ts::other").is_none(),
4112            "{:?}",
4113            calls(&graph)
4114        );
4115    }
4116
4117    /// TypeScript files whose code sits only in `namespace` blocks have no
4118    /// top-level import or export: they are global scripts, and same-named
4119    /// namespaces merge across files. A namespace member's `export` doesn't
4120    /// make the file a module, so the merged calls keep their edges.
4121    #[test]
4122    fn merged_namespace_members_in_script_files_keep_their_calls() {
4123        let graph = index(&[
4124            (
4125                "src/factory.ts",
4126                "namespace ts {\n  export function createNode(kind: number) {\n    return { kind };\n  }\n}\n",
4127            ),
4128            (
4129                "src/parser.ts",
4130                "namespace ts {\n  export function parseSourceFile() {\n    return createNode(1);\n  }\n}\n",
4131            ),
4132        ]);
4133        assert_eq!(
4134            calls(&graph),
4135            edges(&["src/parser.ts::parseSourceFile -> src/factory.ts::createNode"])
4136        );
4137    }
4138
4139    /// A run-time binding is looked up in the module itself. `'..'` names a
4140    /// barrel that only re-exports the hook, so a same-named function
4141    /// elsewhere in that directory is not the hook's: the call keeps only the
4142    /// weak edges of a local binding.
4143    #[test]
4144    fn a_binding_from_a_barrel_is_not_pinned_to_a_sibling_file() {
4145        let graph = index(&[
4146            ("src/app/index.ts", "export { useApp } from \"./context\";\n"),
4147            (
4148                "src/app/context.tsx",
4149                "import { useContext } from \"react\";\n\nexport function useApp() {\n  return useContext(AppContext);\n}\n",
4150            ),
4151            (
4152                "src/app/admin/session.ts",
4153                "export function logout() {\n  return 1;\n}\n",
4154            ),
4155            (
4156                "src/lib/auth/session.ts",
4157                "export async function logout() {\n  return 2;\n}\n",
4158            ),
4159            (
4160                "src/app/settings/Account.tsx",
4161                "\
4162import { useApp } from \"..\";
4163
4164export function Account() {
4165  const { logout } = useApp();
4166  return logout();
4167}
4168",
4169            ),
4170        ]);
4171        let account = "src/app/settings/Account.tsx::Account";
4172        for target in [
4173            "src/app/admin/session.ts::logout",
4174            "src/lib/auth/session.ts::logout",
4175        ] {
4176            let weak = confidence(&graph, account, target)
4177                .unwrap_or_else(|| panic!("{target}: {:?}", calls(&graph)));
4178            assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{target}: {weak}");
4179        }
4180    }
4181
4182    /// Build tools can inject imports (Nuxt's `composables/`,
4183    /// unplugin-auto-import), so a call to a name the file doesn't bind may
4184    /// reach another module's exported function. It keeps a weak edge.
4185    #[test]
4186    fn a_global_call_to_an_exported_function_keeps_a_weak_edge() {
4187        let graph = index(&[
4188            (
4189                "composables/useUser.ts",
4190                "export const useUser = () => useState(\"user\", () => null);\n",
4191            ),
4192            (
4193                "composables/useCart.ts",
4194                "export const useCart = () => {\n  const user = useUser();\n  return { user };\n};\n",
4195            ),
4196        ]);
4197        let weak = confidence(
4198            &graph,
4199            "composables/useCart.ts::useCart",
4200            "composables/useUser.ts::useUser",
4201        )
4202        .unwrap_or_else(|| panic!("{:?}", calls(&graph)));
4203        assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
4204    }
4205
4206    /// The index cache stores nodes by id. Two imports of one module in one
4207    /// file (an import and a run-time binding of it, `import` and
4208    /// `import type`, two Python `from` lines) must both survive a round trip
4209    /// through it, or the next `arbor index` loses a binding and drops calls.
4210    #[test]
4211    fn imports_of_one_module_survive_the_cache() {
4212        let files = [
4213            (
4214                "hooks.ts",
4215                "export function useListFilters() {\n  function setFilters(patch: object) {\n    return patch;\n  }\n  return { setFilters };\n}\n",
4216            ),
4217            (
4218                "List.tsx",
4219                "import { useListFilters } from \"./hooks\";\n\nexport function List() {\n  const { setFilters } = useListFilters();\n  return setFilters({});\n}\n",
4220            ),
4221            (
4222                "api.ts",
4223                "export function fetchUser() {\n  return 1;\n}\n\nexport interface User {\n  id: number;\n}\n",
4224            ),
4225            (
4226                "load.ts",
4227                "import { fetchUser } from \"./api\";\nimport type { User } from \"./api\";\n\nexport function load(): User {\n  return { id: fetchUser() };\n}\n",
4228            ),
4229            ("money.py", "def a():\n    return 1\n\n\ndef b():\n    return 2\n"),
4230            (
4231                "orders.py",
4232                "from money import a\n\n\ndef first():\n    return a()\n\n\nfrom money import b\n\n\ndef second():\n    return b()\n",
4233            ),
4234        ];
4235        let fresh = calls(&index(&files));
4236        for expected in [
4237            "List.tsx::List -> hooks.ts::useListFilters",
4238            "List.tsx::List -> hooks.ts::setFilters",
4239            "load.ts::load -> api.ts::fetchUser",
4240            "orders.py::first -> money.py::a",
4241            "orders.py::second -> money.py::b",
4242        ] {
4243            assert!(fresh.contains(expected), "{expected}: {fresh:?}");
4244        }
4245
4246        let dir = tempfile::tempdir().unwrap();
4247        let store = crate::store::GraphStore::open(dir.path()).unwrap();
4248        for (path, source) in &files {
4249            let ext = std::path::Path::new(path)
4250                .extension()
4251                .and_then(|e| e.to_str())
4252                .unwrap();
4253            let parser = arbor_core::languages::get_parser(ext).unwrap();
4254            let nodes = arbor_core::parse_source(source, path, parser.as_ref()).unwrap();
4255            store.update_file(path, &nodes, 1).unwrap();
4256        }
4257        let mut builder = super::GraphBuilder::new();
4258        for (path, _) in &files {
4259            builder.add_nodes(store.get_file_nodes(path).unwrap().unwrap());
4260        }
4261        assert_eq!(calls(&builder.build()), fresh);
4262    }
4263}