Skip to main content

arbor_graph/
graph.rs

1//! Core graph data structure.
2//!
3//! The ArborGraph wraps petgraph and adds indexes for fast lookups.
4//! It's the central data structure that everything else works with.
5
6use crate::edge::{Edge, EdgeKind, GraphEdge};
7use crate::search_index::SearchIndex;
8use arbor_core::CodeNode;
9use petgraph::stable_graph::{NodeIndex, StableDiGraph};
10use petgraph::visit::{EdgeRef, IntoEdgeReferences}; // For edge_references
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14/// Unique identifier for a node in the graph.
15pub type NodeId = NodeIndex;
16
17/// The code relationship graph.
18///
19/// This is the heart of Arbor. It stores all code entities as nodes
20/// and their relationships as edges, with indexes for fast access.
21#[derive(Debug, Serialize, Deserialize)]
22pub struct ArborGraph {
23    /// The underlying petgraph graph.
24    pub(crate) graph: StableDiGraph<CodeNode, Edge>,
25
26    /// Maps string IDs to graph node indexes.
27    id_index: HashMap<String, NodeId>,
28
29    /// Maps node names to node IDs (for search).
30    name_index: HashMap<String, Vec<NodeId>>,
31
32    /// Maps file paths to node IDs (for incremental updates).
33    file_index: HashMap<String, Vec<NodeId>>,
34
35    /// Percentile-rank centrality, comparable across repositories.
36    centrality: HashMap<NodeId, f64>,
37
38    /// Raw PageRank mass, kept so a recompute can warm-start from it.
39    #[serde(default)]
40    centrality_raw: HashMap<NodeId, f64>,
41
42    /// Search index for fast substring queries.
43    #[serde(skip)]
44    search_index: SearchIndex,
45}
46
47impl Default for ArborGraph {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl ArborGraph {
54    /// Creates a new empty graph.
55    pub fn new() -> Self {
56        Self {
57            graph: StableDiGraph::new(),
58            id_index: HashMap::new(),
59            name_index: HashMap::new(),
60            file_index: HashMap::new(),
61            centrality: HashMap::new(),
62            centrality_raw: HashMap::new(),
63            search_index: SearchIndex::new(),
64        }
65    }
66
67    /// Rebuilds the search index from existing graph nodes.
68    /// Call after deserialization since search_index is not serialized.
69    pub fn rebuild_search_index(&mut self) {
70        self.search_index = SearchIndex::new();
71        for index in self.graph.node_indices() {
72            if let Some(node) = self.graph.node_weight(index) {
73                self.search_index.insert(&node.name, index);
74                index_node_documentation(&mut self.search_index, node, index);
75            }
76        }
77    }
78
79    /// Adds a code node to the graph.
80    ///
81    /// Returns the node's index for adding edges later.
82    pub fn add_node(&mut self, node: CodeNode) -> NodeId {
83        let id = node.id.clone();
84        let name = node.name.clone();
85        let file = node.file.clone();
86
87        let index = self.graph.add_node(node);
88
89        // Update indexes
90        self.id_index.insert(id, index);
91        self.name_index.entry(name.clone()).or_default().push(index);
92        self.file_index.entry(file).or_default().push(index);
93        self.search_index.insert(&name, index);
94        if let Some(node) = self.graph.node_weight(index) {
95            index_node_documentation(&mut self.search_index, node, index);
96        }
97
98        index
99    }
100
101    /// Adds an edge between two nodes.
102    pub fn add_edge(&mut self, from: NodeId, to: NodeId, edge: Edge) {
103        self.graph.add_edge(from, to, edge);
104    }
105
106    /// Gets a node by its string ID.
107    pub fn get_by_id(&self, id: &str) -> Option<&CodeNode> {
108        let index = self.id_index.get(id)?;
109        self.graph.node_weight(*index)
110    }
111
112    /// Gets a node by its graph index.
113    pub fn get(&self, index: NodeId) -> Option<&CodeNode> {
114        self.graph.node_weight(index)
115    }
116
117    /// Finds all nodes with a given name.
118    pub fn find_by_name(&self, name: &str) -> Vec<&CodeNode> {
119        self.name_index
120            .get(name)
121            .map(|indexes| {
122                indexes
123                    .iter()
124                    .filter_map(|idx| self.graph.node_weight(*idx))
125                    .collect()
126            })
127            .unwrap_or_default()
128    }
129
130    /// Resolves a symbol name to candidate nodes, best match first.
131    ///
132    /// Names collide constantly — `getPath` may be a utility function *and* a
133    /// method on four unrelated classes. Callers that took
134    /// `find_by_name(..).first()` got whichever file happened to be parsed
135    /// first and then answered as though it were the only candidate; on a real
136    /// codebase that reported a heavily-used function as unreachable dead code.
137    ///
138    /// Ranking is by graph degree, then centrality, then file path — so the
139    /// pick is meaningful and does not depend on parse order. An exact node-id
140    /// match short-circuits to a single result.
141    pub fn resolve_symbol_ranked(&self, name: &str) -> Vec<NodeId> {
142        if let Some(idx) = self.get_index(name) {
143            return vec![idx];
144        }
145
146        let mut candidates: Vec<NodeId> = self
147            .find_by_name(name)
148            .iter()
149            .filter_map(|n| self.get_index(&n.id))
150            .collect();
151
152        candidates.sort_by(|&a, &b| {
153            let degree = |i: NodeId| self.get_callers(i).len() + self.get_callees(i).len();
154            degree(b)
155                .cmp(&degree(a))
156                .then_with(|| {
157                    self.centrality(b)
158                        .partial_cmp(&self.centrality(a))
159                        .unwrap_or(std::cmp::Ordering::Equal)
160                })
161                .then_with(|| {
162                    let file = |i: NodeId| self.get(i).map(|n| n.file.clone()).unwrap_or_default();
163                    file(a).cmp(&file(b))
164                })
165        });
166
167        candidates
168    }
169
170    /// The single node a user most likely meant by `name`.
171    ///
172    /// See [`resolve_symbol_ranked`](Self::resolve_symbol_ranked) for how ties
173    /// are broken.
174    pub fn resolve_symbol(&self, name: &str) -> Option<NodeId> {
175        self.resolve_symbol_ranked(name).into_iter().next()
176    }
177
178    /// Finds all nodes in a file.
179    pub fn find_by_file(&self, file: &str) -> Vec<&CodeNode> {
180        self.file_index
181            .get(file)
182            .map(|indexes| {
183                indexes
184                    .iter()
185                    .filter_map(|idx| self.graph.node_weight(*idx))
186                    .collect()
187            })
188            .unwrap_or_default()
189    }
190
191    /// Searches for nodes whose name literally contains the query.
192    ///
193    /// Substring matching only: `search("login")` will not find
194    /// `get_authenticated`. Use [`search_ranked`](Self::search_ranked) when the
195    /// caller is asking about a concept rather than spelling a name.
196    pub fn search(&self, query: &str) -> Vec<&CodeNode> {
197        self.search_index
198            .search(query)
199            .iter()
200            .filter_map(|id| self.graph.node_weight(*id))
201            .collect()
202    }
203
204    /// Searches names, identifier tokens, related concepts, and documentation.
205    ///
206    /// Returns hits ordered strongest-first, each labelled with *how* it
207    /// matched — so a caller can present an exact hit and a concept guess
208    /// differently instead of blending them into one opaque ranking.
209    ///
210    /// ```ignore
211    /// // Finds `get_authenticated`, `verifyJwt`, `hashPassword`, …
212    /// for (node, hit) in graph.search_ranked("login") {
213    ///     println!("{} ({})", node.name, hit.kind.label());
214    /// }
215    /// ```
216    pub fn search_ranked(&self, query: &str) -> Vec<(&CodeNode, crate::search_index::SearchHit)> {
217        self.search_index
218            .search_ranked(query)
219            .into_iter()
220            .filter_map(|hit| self.graph.node_weight(hit.id).map(|node| (node, hit)))
221            .collect()
222    }
223
224    /// Gets nodes that call the given node.
225    ///
226    /// Call edges only. A subclass does not call its base; that relationship
227    /// is an `extends` edge and is reported by [`direct_dependents`](Self::direct_dependents).
228    pub fn get_callers(&self, index: NodeId) -> Vec<&CodeNode> {
229        self.graph
230            .neighbors_directed(index, petgraph::Direction::Incoming)
231            .filter_map(|idx| {
232                // Check if the edge is a call
233                let edge_idx = self.graph.find_edge(idx, index)?;
234                let edge = self.graph.edge_weight(edge_idx)?;
235                if edge.kind == EdgeKind::Calls {
236                    self.graph.node_weight(idx)
237                } else {
238                    None
239                }
240            })
241            .collect()
242    }
243
244    /// Nodes that directly reach `index` by calling it, extending it, or
245    /// implementing it.
246    ///
247    /// PageRank still follows [`EdgeKind::Calls`] only. Blast radius and the
248    /// graded inheritance check need the type edges as well: a base with
249    /// subclasses is reached, even though nothing calls the class.
250    pub fn direct_dependents(&self, index: NodeId) -> Vec<&CodeNode> {
251        let mut seen = Vec::new();
252        let mut out = Vec::new();
253        for edge_ref in self
254            .graph
255            .edges_directed(index, petgraph::Direction::Incoming)
256        {
257            if !matches!(
258                edge_ref.weight().kind,
259                EdgeKind::Calls | EdgeKind::Extends | EdgeKind::Implements
260            ) {
261                continue;
262            }
263            let source = edge_ref.source();
264            if seen.contains(&source) {
265                continue;
266            }
267            seen.push(source);
268            if let Some(node) = self.graph.node_weight(source) {
269                out.push(node);
270            }
271        }
272        out
273    }
274
275    /// Gets nodes that this node calls.
276    pub fn get_callees(&self, index: NodeId) -> Vec<&CodeNode> {
277        self.graph
278            .neighbors_directed(index, petgraph::Direction::Outgoing)
279            .filter_map(|idx| {
280                let edge_idx = self.graph.find_edge(index, idx)?;
281                let edge = self.graph.edge_weight(edge_idx)?;
282                if edge.kind == EdgeKind::Calls {
283                    self.graph.node_weight(idx)
284                } else {
285                    None
286                }
287            })
288            .collect()
289    }
290
291    /// Gets all nodes that depend on the given node (directly or transitively).
292    pub fn get_dependents(&self, index: NodeId, max_depth: usize) -> Vec<(NodeId, usize)> {
293        let mut result = Vec::new();
294        let mut visited = std::collections::HashSet::new();
295        let mut queue = vec![(index, 0usize)];
296
297        while let Some((current, depth)) = queue.pop() {
298            if depth > max_depth || visited.contains(&current) {
299                continue;
300            }
301            visited.insert(current);
302
303            if current != index {
304                result.push((current, depth));
305            }
306
307            // Get incoming edges (callers)
308            for neighbor in self
309                .graph
310                .neighbors_directed(current, petgraph::Direction::Incoming)
311            {
312                if !visited.contains(&neighbor) {
313                    queue.push((neighbor, depth + 1));
314                }
315            }
316        }
317
318        result
319    }
320
321    /// Removes all nodes from a file. Used for incremental updates.
322    pub fn remove_file(&mut self, file: &str) {
323        if let Some(indexes) = self.file_index.remove(file) {
324            for index in indexes {
325                if let Some(node) = self.graph.node_weight(index) {
326                    // Remove from name index
327                    let name = node.name.clone();
328                    if let Some(name_list) = self.name_index.get_mut(&name) {
329                        name_list.retain(|&idx| idx != index);
330                    }
331                    // Remove from id index
332                    self.id_index.remove(&node.id);
333                    // Remove from search index
334                    self.search_index.remove(&name, index);
335                }
336                self.graph.remove_node(index);
337            }
338        }
339    }
340
341    /// Centrality as a percentile rank in `[0.0, 1.0]`.
342    ///
343    /// `0.9` means "more central than 90% of the nodes in this repository",
344    /// and carries that meaning in every repository — so a threshold written
345    /// against it behaves the same on a god-object monolith and a flat service.
346    /// For the underlying PageRank mass see [`centrality_raw`](Self::centrality_raw).
347    pub fn centrality(&self, index: NodeId) -> f64 {
348        self.centrality.get(&index).copied().unwrap_or(0.0)
349    }
350
351    /// Raw PageRank mass for a node. Sums to ~1.0 across the graph.
352    pub fn centrality_raw(&self, index: NodeId) -> f64 {
353        self.centrality_raw.get(&index).copied().unwrap_or(0.0)
354    }
355
356    /// Iterates every edge weight, for density and confidence reporting.
357    pub fn edge_weights(&self) -> impl Iterator<Item = &Edge> {
358        self.graph.edge_weights()
359    }
360
361    /// Counts edges at or above [`Edge::CONFIDENT_THRESHOLD`].
362    ///
363    /// The gap between this and [`edge_count`](Self::edge_count) is how much of
364    /// the graph rests on inference rather than proof — worth surfacing in any
365    /// report that claims to describe what a change reaches.
366    pub fn confident_edge_count(&self) -> usize {
367        self.graph
368            .edge_weights()
369            .filter(|edge| edge.is_confident())
370            .count()
371    }
372
373    /// Sets percentile centrality scores.
374    ///
375    /// Prefer [`set_centrality_scores`](Self::set_centrality_scores), which
376    /// also stores the raw scores a warm start needs.
377    pub fn set_centrality(&mut self, scores: HashMap<NodeId, f64>) {
378        self.centrality = scores;
379    }
380
381    /// Whether every node has a stored percentile, including a legitimate `0.0`.
382    ///
383    /// A missing computation leaves the map empty. A finished one writes a score
384    /// for each node, and the bottom rank is defined to be `0.0`, so "any score
385    /// is positive" is the wrong test.
386    pub fn has_centrality_scores(&self) -> bool {
387        let n = self.node_count();
388        n > 0 && self.centrality.len() == n
389    }
390
391    /// Stores both the raw and percentile forms from a computation.
392    pub fn set_centrality_scores(&mut self, scores: crate::ranking::CentralityScores) {
393        let (raw, percentile) = scores.into_parts();
394        self.centrality_raw = raw;
395        self.centrality = percentile;
396    }
397
398    /// Raw score map, for warm-starting a recompute.
399    ///
400    /// Falls back to the percentile map when raw scores are absent — a graph
401    /// deserialized from a cache written before raw scores were stored. The
402    /// warm-start rescale in [`crate::ranking`] tolerates any scalar multiple
403    /// of the fixed point, so this degrades convergence speed, not correctness.
404    pub fn centrality_map(&self) -> &HashMap<NodeId, f64> {
405        if self.centrality_raw.is_empty() {
406            &self.centrality
407        } else {
408            &self.centrality_raw
409        }
410    }
411
412    /// Returns the number of nodes.
413    pub fn node_count(&self) -> usize {
414        self.graph.node_count()
415    }
416
417    /// Returns the number of edges.
418    pub fn edge_count(&self) -> usize {
419        self.graph.edge_count()
420    }
421
422    /// Iterates over all nodes.
423    pub fn nodes(&self) -> impl Iterator<Item = &CodeNode> {
424        self.graph.node_weights()
425    }
426
427    /// Iterates over all edges.
428    pub fn edges(&self) -> impl Iterator<Item = &Edge> {
429        self.graph.edge_weights()
430    }
431
432    /// Returns all edges with source and target IDs for export.
433    pub fn export_edges(&self) -> Vec<GraphEdge> {
434        (&self.graph)
435            .edge_references()
436            .filter_map(|edge_ref| {
437                let source = self.graph.node_weight(edge_ref.source())?.id.clone();
438                let target = self.graph.node_weight(edge_ref.target())?.id.clone();
439                let weight = edge_ref.weight(); // &Edge
440                Some(GraphEdge {
441                    source,
442                    target,
443                    kind: weight.kind,
444                })
445            })
446            .collect()
447    }
448
449    /// Iterates over all node indexes.
450    pub fn node_indexes(&self) -> impl Iterator<Item = NodeId> + '_ {
451        self.graph.node_indices()
452    }
453
454    /// Finds the shortest path between two nodes.
455    pub fn find_path(&self, from: NodeId, to: NodeId) -> Option<Vec<&CodeNode>> {
456        let path_indices = petgraph::algo::astar(
457            &self.graph,
458            from,
459            |finish| finish == to,
460            |_| 1, // weight of 1 for all edges (BFS-like)
461            |_| 0, // heuristic
462        )?;
463
464        Some(
465            path_indices
466                .1
467                .into_iter()
468                .filter_map(|idx| self.graph.node_weight(idx))
469                .collect(),
470        )
471    }
472
473    /// Gets the node index for a string ID.
474    pub fn get_index(&self, id: &str) -> Option<NodeId> {
475        self.id_index.get(id).copied()
476    }
477
478    /// Returns all nodes detected as production entry points.
479    pub fn list_entry_points(&self) -> Vec<&CodeNode> {
480        use crate::heuristics::HeuristicsMatcher;
481        self.graph
482            .node_weights()
483            .filter(|n| HeuristicsMatcher::is_likely_entry_point(n))
484            .collect()
485    }
486
487    /// Returns all nodes in a file and the call edges between them.
488    /// Edges returned as (caller_name, callee_name, edge_kind_debug_str) triples.
489    pub fn nodes_in_file_with_edges(
490        &self,
491        file: &str,
492    ) -> (Vec<&CodeNode>, Vec<(String, String, String)>) {
493        // Exact key first; fall back to a separator-insensitive match.
494        //
495        // `file_index` is keyed on the path exactly as the parser recorded it.
496        // Callers build lookup paths by joining a project root with a
497        // forward-slash relative path, which on Windows yields a mixed
498        // `C:\root\src/lib.rs` that never equals the stored `C:\root\src\lib.rs`.
499        let node_ids: std::collections::HashSet<NodeId> = match self.file_index.get(file) {
500            Some(ids) => ids.iter().copied().collect(),
501            None => {
502                let wanted = normalize_separators(file);
503                self.file_index
504                    .iter()
505                    .filter(|(stored, _)| normalize_separators(stored) == wanted)
506                    .flat_map(|(_, ids)| ids.iter().copied())
507                    .collect()
508            }
509        };
510
511        let nodes: Vec<&CodeNode> = node_ids
512            .iter()
513            .filter_map(|&id| self.graph.node_weight(id))
514            .collect();
515
516        let mut edges = Vec::new();
517        for &from in &node_ids {
518            for edge_ref in self
519                .graph
520                .edges_directed(from, petgraph::Direction::Outgoing)
521            {
522                let to = edge_ref.target();
523                if node_ids.contains(&to) {
524                    if let (Some(from_node), Some(to_node)) =
525                        (self.graph.node_weight(from), self.graph.node_weight(to))
526                    {
527                        edges.push((
528                            from_node.name.clone(),
529                            to_node.name.clone(),
530                            format!("{:?}", edge_ref.weight().kind),
531                        ));
532                    }
533                }
534            }
535        }
536        (nodes, edges)
537    }
538}
539
540/// Graph statistics for the info endpoint.
541#[derive(Debug, Serialize, Deserialize)]
542pub struct GraphStats {
543    pub node_count: usize,
544    pub edge_count: usize,
545    pub files: usize,
546}
547
548impl ArborGraph {
549    /// Returns graph statistics.
550    pub fn stats(&self) -> GraphStats {
551        GraphStats {
552            node_count: self.node_count(),
553            edge_count: self.edge_count(),
554            files: self.file_index.len(),
555        }
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562    use crate::edge::{Edge, EdgeKind};
563    use arbor_core::{CodeNode, NodeKind};
564
565    fn make_node(name: &str, file: &str) -> CodeNode {
566        CodeNode::new(name, name, NodeKind::Function, file)
567    }
568
569    #[test]
570    fn test_graph_new_is_empty() {
571        let g = ArborGraph::new();
572        assert_eq!(g.node_count(), 0);
573        assert_eq!(g.edge_count(), 0);
574        assert!(g.nodes().next().is_none());
575    }
576
577    #[test]
578    fn test_graph_add_and_get_node() {
579        let mut g = ArborGraph::new();
580        let node = make_node("foo", "main.rs");
581        let id = g.add_node(node.clone());
582        assert_eq!(g.node_count(), 1);
583
584        let got = g.get(id).unwrap();
585        assert_eq!(got.name, "foo");
586    }
587
588    #[test]
589    fn test_graph_find_by_name() {
590        let mut g = ArborGraph::new();
591        g.add_node(make_node("alpha", "a.rs"));
592        g.add_node(make_node("beta", "b.rs"));
593
594        let found = g.find_by_name("alpha");
595        assert_eq!(found.len(), 1);
596        assert_eq!(found[0].name, "alpha");
597
598        let not_found = g.find_by_name("gamma");
599        assert!(not_found.is_empty());
600    }
601
602    #[test]
603    fn test_graph_find_by_file() {
604        let mut g = ArborGraph::new();
605        g.add_node(make_node("foo", "main.rs"));
606        g.add_node(make_node("bar", "main.rs"));
607        g.add_node(make_node("baz", "other.rs"));
608
609        let main_nodes = g.find_by_file("main.rs");
610        assert_eq!(main_nodes.len(), 2);
611
612        let other_nodes = g.find_by_file("other.rs");
613        assert_eq!(other_nodes.len(), 1);
614
615        let empty = g.find_by_file("nonexistent.rs");
616        assert!(empty.is_empty());
617    }
618
619    #[test]
620    fn test_graph_search_substring() {
621        let mut g = ArborGraph::new();
622        g.add_node(make_node("validate_user", "a.rs"));
623        g.add_node(make_node("validate_email", "b.rs"));
624        g.add_node(make_node("send_email", "c.rs"));
625
626        let results = g.search("validate");
627        assert_eq!(results.len(), 2);
628        assert!(results.iter().any(|n| n.name == "validate_user"));
629        assert!(results.iter().any(|n| n.name == "validate_email"));
630    }
631
632    #[test]
633    fn test_graph_callers_callees() {
634        let mut g = ArborGraph::new();
635        let a = g.add_node(make_node("caller", "a.rs"));
636        let b = g.add_node(make_node("callee", "b.rs"));
637        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
638
639        let callees = g.get_callees(a);
640        assert_eq!(callees.len(), 1);
641        assert_eq!(callees[0].name, "callee");
642
643        let callers = g.get_callers(b);
644        assert_eq!(callers.len(), 1);
645        assert_eq!(callers[0].name, "caller");
646
647        // No callers/callees for disconnected nodes
648        assert!(g.get_callers(a).is_empty());
649        assert!(g.get_callees(b).is_empty());
650    }
651
652    #[test]
653    fn direct_dependents_include_subclasses_and_not_callers_query() {
654        let mut g = ArborGraph::new();
655        let middle = g.add_node(make_node("Middle", "a.py"));
656        let base = g.add_node(make_node("Base", "a.py"));
657        g.add_edge(middle, base, Edge::new(EdgeKind::Extends));
658
659        assert!(g.get_callers(base).is_empty());
660        let dependents = g.direct_dependents(base);
661        assert_eq!(dependents.len(), 1);
662        assert_eq!(dependents[0].name, "Middle");
663    }
664
665    #[test]
666    fn test_graph_get_dependents() {
667        // a -> b -> c
668        let mut g = ArborGraph::new();
669        let a = g.add_node(make_node("a", "a.rs"));
670        let b = g.add_node(make_node("b", "b.rs"));
671        let c = g.add_node(make_node("c", "c.rs"));
672        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
673        g.add_edge(b, c, Edge::new(EdgeKind::Calls));
674
675        // Dependents of c at depth 2 should include a and b
676        let deps = g.get_dependents(c, 2);
677        assert!(deps.iter().any(|(idx, _)| g.get(*idx).unwrap().name == "b"));
678        assert!(deps.iter().any(|(idx, _)| g.get(*idx).unwrap().name == "a"));
679    }
680
681    #[test]
682    fn test_graph_remove_file_cleanup() {
683        let mut g = ArborGraph::new();
684        g.add_node(make_node("foo", "remove_me.rs"));
685        g.add_node(make_node("bar", "remove_me.rs"));
686        g.add_node(make_node("keep", "keep.rs"));
687
688        assert_eq!(g.node_count(), 3);
689
690        g.remove_file("remove_me.rs");
691
692        // Nodes from removed file are gone
693        assert!(g.find_by_name("foo").is_empty());
694        assert!(g.find_by_name("bar").is_empty());
695        // Node from other file remains
696        assert_eq!(g.find_by_name("keep").len(), 1);
697        assert!(g.find_by_file("remove_me.rs").is_empty());
698    }
699
700    #[test]
701    fn test_graph_find_path() {
702        // a -> b -> c
703        let mut g = ArborGraph::new();
704        let a = g.add_node(make_node("start", "a.rs"));
705        let b = g.add_node(make_node("middle", "b.rs"));
706        let c = g.add_node(make_node("end", "c.rs"));
707        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
708        g.add_edge(b, c, Edge::new(EdgeKind::Calls));
709
710        let path = g.find_path(a, c).unwrap();
711        assert_eq!(path.len(), 3);
712        assert_eq!(path[0].name, "start");
713        assert_eq!(path[1].name, "middle");
714        assert_eq!(path[2].name, "end");
715    }
716
717    #[test]
718    fn test_graph_find_path_no_connection() {
719        let mut g = ArborGraph::new();
720        let a = g.add_node(make_node("island_a", "a.rs"));
721        let b = g.add_node(make_node("island_b", "b.rs"));
722
723        // No edges → no path
724        assert!(g.find_path(a, b).is_none());
725    }
726
727    #[test]
728    fn test_graph_export_edges() {
729        let mut g = ArborGraph::new();
730        let a = g.add_node(make_node("a", "a.rs"));
731        let b = g.add_node(make_node("b", "b.rs"));
732        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
733
734        let exported = g.export_edges();
735        assert_eq!(exported.len(), 1);
736        assert_eq!(exported[0].kind, EdgeKind::Calls);
737    }
738
739    #[test]
740    fn test_graph_stats() {
741        let mut g = ArborGraph::new();
742        g.add_node(make_node("a", "x.rs"));
743        g.add_node(make_node("b", "y.rs"));
744
745        let stats = g.stats();
746        assert_eq!(stats.node_count, 2);
747        assert_eq!(stats.edge_count, 0);
748        assert_eq!(stats.files, 2);
749    }
750
751    #[test]
752    fn test_graph_get_index_and_get_by_id() {
753        let mut g = ArborGraph::new();
754        let node = make_node("lookup_me", "test.rs");
755        let node_id_str = node.id.clone();
756        let idx = g.add_node(node);
757
758        assert_eq!(g.get_index(&node_id_str), Some(idx));
759        assert!(g.get_by_id(&node_id_str).is_some());
760        assert!(g.get_index("nonexistent").is_none());
761        assert!(g.get_by_id("nonexistent").is_none());
762    }
763
764    #[test]
765    fn test_graph_centrality_default_zero() {
766        let mut g = ArborGraph::new();
767        let idx = g.add_node(make_node("a", "a.rs"));
768        assert_eq!(g.centrality(idx), 0.0);
769    }
770
771    #[test]
772    fn test_graph_set_centrality() {
773        let mut g = ArborGraph::new();
774        let idx = g.add_node(make_node("a", "a.rs"));
775
776        let mut scores = HashMap::new();
777        scores.insert(idx, 0.75);
778        g.set_centrality(scores);
779
780        assert!((g.centrality(idx) - 0.75).abs() < f64::EPSILON);
781    }
782}
783
784#[cfg(test)]
785mod new_query_tests {
786    use super::*;
787    use crate::edge::{Edge, EdgeKind};
788    use arbor_core::{CodeNode, NodeKind};
789
790    fn make_node(name: &str, kind: NodeKind, file: &str) -> CodeNode {
791        CodeNode::new(name, format!("{}::{}", file, name), kind, file)
792    }
793
794    #[test]
795    fn test_list_entry_points_returns_main() {
796        let mut g = ArborGraph::new();
797        g.add_node(make_node("main", NodeKind::Function, "src/main.rs"));
798        g.add_node(make_node("helper", NodeKind::Function, "src/util.rs"));
799        let eps = g.list_entry_points();
800        assert!(
801            eps.iter().any(|n| n.name == "main"),
802            "main must be an entry point"
803        );
804        assert!(
805            !eps.iter().any(|n| n.name == "helper"),
806            "helper must not be an entry point"
807        );
808    }
809
810    #[test]
811    fn test_nodes_in_file_with_edges_returns_edges() {
812        let mut g = ArborGraph::new();
813        let a = g.add_node(make_node("foo", NodeKind::Function, "src/a.rs"));
814        let b = g.add_node(make_node("bar", NodeKind::Function, "src/a.rs"));
815        let _c = g.add_node(make_node("baz", NodeKind::Function, "src/b.rs"));
816        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
817        let (nodes, edges) = g.nodes_in_file_with_edges("src/a.rs");
818        assert_eq!(nodes.len(), 2);
819        assert_eq!(edges.len(), 1);
820        assert_eq!(edges[0].0, "foo");
821        assert_eq!(edges[0].1, "bar");
822    }
823
824    #[test]
825    fn nodes_in_file_lookup_is_separator_insensitive() {
826        // Callers join a project root with a forward-slash relative path,
827        // which on Windows yields `C:\root\src/lib.rs` while the parser
828        // recorded `C:\root\src\lib.rs`. Exact-key lookup missed, and
829        // `file-graph` reported "No symbols found" for a file full of symbols.
830        let mut g = ArborGraph::new();
831        g.add_node(make_node(
832            "helper",
833            NodeKind::Function,
834            r"C:/root/src\lib.rs",
835        ));
836
837        let (backslash, _) = g.nodes_in_file_with_edges(r"C:/root/src\lib.rs");
838        assert_eq!(backslash.len(), 1, "exact key must still work");
839
840        let (forward, _) = g.nodes_in_file_with_edges("C:/root/src/lib.rs");
841        assert_eq!(forward.len(), 1, "separator spelling must not matter");
842    }
843
844    #[test]
845    fn test_nodes_in_file_with_edges_excludes_cross_file_edges() {
846        use crate::edge::{Edge, EdgeKind};
847        let mut g = ArborGraph::new();
848        let a = g.add_node(make_node("foo", NodeKind::Function, "src/a.rs"));
849        let c = g.add_node(make_node("baz", NodeKind::Function, "src/b.rs"));
850        // Edge from a.rs to b.rs — should NOT appear in get_file_graph for a.rs
851        g.add_edge(a, c, Edge::new(EdgeKind::Calls));
852        let (nodes, edges) = g.nodes_in_file_with_edges("src/a.rs");
853        assert_eq!(nodes.len(), 1); // only foo
854        assert_eq!(edges.len(), 0); // cross-file edge excluded
855    }
856}
857
858/// Feeds a node's supporting text into the search index.
859///
860/// Docstrings, signatures, and qualified names are already parsed into every
861/// `CodeNode` and were previously ignored at search time — so a function
862/// documented as "validates the user's login credentials" was unreachable by a
863/// search for "login". The file path is included too: `src/auth/session.ts`
864/// says as much about a symbol as its name often does.
865fn index_node_documentation(index: &mut SearchIndex, node: &CodeNode, id: NodeId) {
866    if let Some(doc) = &node.docstring {
867        index.insert_documentation(doc, id);
868    }
869    if let Some(sig) = &node.signature {
870        index.insert_documentation(sig, id);
871    }
872    index.insert_documentation(&node.file, id);
873    if node.qualified_name != node.name {
874        index.insert_documentation(&node.qualified_name, id);
875    }
876}
877
878/// Normalizes path separators for comparison.
879///
880/// Windows accepts both `/` and `\`, so the same file can be spelled either
881/// way depending on whether the path came from a directory walk or from
882/// joining a user-supplied relative path.
883fn normalize_separators(path: &str) -> String {
884    path.replace('\\', "/")
885}