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