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    pub fn get_callers(&self, index: NodeId) -> Vec<&CodeNode> {
226        self.graph
227            .neighbors_directed(index, petgraph::Direction::Incoming)
228            .filter_map(|idx| {
229                // Check if the edge is a call
230                let edge_idx = self.graph.find_edge(idx, index)?;
231                let edge = self.graph.edge_weight(edge_idx)?;
232                if edge.kind == EdgeKind::Calls {
233                    self.graph.node_weight(idx)
234                } else {
235                    None
236                }
237            })
238            .collect()
239    }
240
241    /// Gets nodes that this node calls.
242    pub fn get_callees(&self, index: NodeId) -> Vec<&CodeNode> {
243        self.graph
244            .neighbors_directed(index, petgraph::Direction::Outgoing)
245            .filter_map(|idx| {
246                let edge_idx = self.graph.find_edge(index, idx)?;
247                let edge = self.graph.edge_weight(edge_idx)?;
248                if edge.kind == EdgeKind::Calls {
249                    self.graph.node_weight(idx)
250                } else {
251                    None
252                }
253            })
254            .collect()
255    }
256
257    /// Gets all nodes that depend on the given node (directly or transitively).
258    pub fn get_dependents(&self, index: NodeId, max_depth: usize) -> Vec<(NodeId, usize)> {
259        let mut result = Vec::new();
260        let mut visited = std::collections::HashSet::new();
261        let mut queue = vec![(index, 0usize)];
262
263        while let Some((current, depth)) = queue.pop() {
264            if depth > max_depth || visited.contains(&current) {
265                continue;
266            }
267            visited.insert(current);
268
269            if current != index {
270                result.push((current, depth));
271            }
272
273            // Get incoming edges (callers)
274            for neighbor in self
275                .graph
276                .neighbors_directed(current, petgraph::Direction::Incoming)
277            {
278                if !visited.contains(&neighbor) {
279                    queue.push((neighbor, depth + 1));
280                }
281            }
282        }
283
284        result
285    }
286
287    /// Removes all nodes from a file. Used for incremental updates.
288    pub fn remove_file(&mut self, file: &str) {
289        if let Some(indexes) = self.file_index.remove(file) {
290            for index in indexes {
291                if let Some(node) = self.graph.node_weight(index) {
292                    // Remove from name index
293                    let name = node.name.clone();
294                    if let Some(name_list) = self.name_index.get_mut(&name) {
295                        name_list.retain(|&idx| idx != index);
296                    }
297                    // Remove from id index
298                    self.id_index.remove(&node.id);
299                    // Remove from search index
300                    self.search_index.remove(&name, index);
301                }
302                self.graph.remove_node(index);
303            }
304        }
305    }
306
307    /// Centrality as a percentile rank in `[0.0, 1.0]`.
308    ///
309    /// `0.9` means "more central than 90% of the nodes in this repository",
310    /// and carries that meaning in every repository — so a threshold written
311    /// against it behaves the same on a god-object monolith and a flat service.
312    /// For the underlying PageRank mass see [`centrality_raw`](Self::centrality_raw).
313    pub fn centrality(&self, index: NodeId) -> f64 {
314        self.centrality.get(&index).copied().unwrap_or(0.0)
315    }
316
317    /// Raw PageRank mass for a node. Sums to ~1.0 across the graph.
318    pub fn centrality_raw(&self, index: NodeId) -> f64 {
319        self.centrality_raw.get(&index).copied().unwrap_or(0.0)
320    }
321
322    /// Iterates every edge weight, for density and confidence reporting.
323    pub fn edge_weights(&self) -> impl Iterator<Item = &Edge> {
324        self.graph.edge_weights()
325    }
326
327    /// Counts edges at or above [`Edge::CONFIDENT_THRESHOLD`].
328    ///
329    /// The gap between this and [`edge_count`](Self::edge_count) is how much of
330    /// the graph rests on inference rather than proof — worth surfacing in any
331    /// report that claims to describe what a change reaches.
332    pub fn confident_edge_count(&self) -> usize {
333        self.graph
334            .edge_weights()
335            .filter(|edge| edge.is_confident())
336            .count()
337    }
338
339    /// Sets percentile centrality scores.
340    ///
341    /// Prefer [`set_centrality_scores`](Self::set_centrality_scores), which
342    /// also stores the raw scores a warm start needs.
343    pub fn set_centrality(&mut self, scores: HashMap<NodeId, f64>) {
344        self.centrality = scores;
345    }
346
347    /// Stores both the raw and percentile forms from a computation.
348    pub fn set_centrality_scores(&mut self, scores: crate::ranking::CentralityScores) {
349        let (raw, percentile) = scores.into_parts();
350        self.centrality_raw = raw;
351        self.centrality = percentile;
352    }
353
354    /// Raw score map, for warm-starting a recompute.
355    ///
356    /// Falls back to the percentile map when raw scores are absent — a graph
357    /// deserialized from a cache written before raw scores were stored. The
358    /// warm-start rescale in [`crate::ranking`] tolerates any scalar multiple
359    /// of the fixed point, so this degrades convergence speed, not correctness.
360    pub fn centrality_map(&self) -> &HashMap<NodeId, f64> {
361        if self.centrality_raw.is_empty() {
362            &self.centrality
363        } else {
364            &self.centrality_raw
365        }
366    }
367
368    /// Returns the number of nodes.
369    pub fn node_count(&self) -> usize {
370        self.graph.node_count()
371    }
372
373    /// Returns the number of edges.
374    pub fn edge_count(&self) -> usize {
375        self.graph.edge_count()
376    }
377
378    /// Iterates over all nodes.
379    pub fn nodes(&self) -> impl Iterator<Item = &CodeNode> {
380        self.graph.node_weights()
381    }
382
383    /// Iterates over all edges.
384    pub fn edges(&self) -> impl Iterator<Item = &Edge> {
385        self.graph.edge_weights()
386    }
387
388    /// Returns all edges with source and target IDs for export.
389    pub fn export_edges(&self) -> Vec<GraphEdge> {
390        (&self.graph)
391            .edge_references()
392            .filter_map(|edge_ref| {
393                let source = self.graph.node_weight(edge_ref.source())?.id.clone();
394                let target = self.graph.node_weight(edge_ref.target())?.id.clone();
395                let weight = edge_ref.weight(); // &Edge
396                Some(GraphEdge {
397                    source,
398                    target,
399                    kind: weight.kind,
400                })
401            })
402            .collect()
403    }
404
405    /// Iterates over all node indexes.
406    pub fn node_indexes(&self) -> impl Iterator<Item = NodeId> + '_ {
407        self.graph.node_indices()
408    }
409
410    /// Finds the shortest path between two nodes.
411    pub fn find_path(&self, from: NodeId, to: NodeId) -> Option<Vec<&CodeNode>> {
412        let path_indices = petgraph::algo::astar(
413            &self.graph,
414            from,
415            |finish| finish == to,
416            |_| 1, // weight of 1 for all edges (BFS-like)
417            |_| 0, // heuristic
418        )?;
419
420        Some(
421            path_indices
422                .1
423                .into_iter()
424                .filter_map(|idx| self.graph.node_weight(idx))
425                .collect(),
426        )
427    }
428
429    /// Gets the node index for a string ID.
430    pub fn get_index(&self, id: &str) -> Option<NodeId> {
431        self.id_index.get(id).copied()
432    }
433
434    /// Returns all nodes detected as production entry points.
435    pub fn list_entry_points(&self) -> Vec<&CodeNode> {
436        use crate::heuristics::HeuristicsMatcher;
437        self.graph
438            .node_weights()
439            .filter(|n| HeuristicsMatcher::is_likely_entry_point(n))
440            .collect()
441    }
442
443    /// Returns all nodes in a file and the call edges between them.
444    /// Edges returned as (caller_name, callee_name, edge_kind_debug_str) triples.
445    pub fn nodes_in_file_with_edges(
446        &self,
447        file: &str,
448    ) -> (Vec<&CodeNode>, Vec<(String, String, String)>) {
449        // Exact key first; fall back to a separator-insensitive match.
450        //
451        // `file_index` is keyed on the path exactly as the parser recorded it.
452        // Callers build lookup paths by joining a project root with a
453        // forward-slash relative path, which on Windows yields a mixed
454        // `C:\root\src/lib.rs` that never equals the stored `C:\root\src\lib.rs`.
455        let node_ids: std::collections::HashSet<NodeId> = match self.file_index.get(file) {
456            Some(ids) => ids.iter().copied().collect(),
457            None => {
458                let wanted = normalize_separators(file);
459                self.file_index
460                    .iter()
461                    .filter(|(stored, _)| normalize_separators(stored) == wanted)
462                    .flat_map(|(_, ids)| ids.iter().copied())
463                    .collect()
464            }
465        };
466
467        let nodes: Vec<&CodeNode> = node_ids
468            .iter()
469            .filter_map(|&id| self.graph.node_weight(id))
470            .collect();
471
472        let mut edges = Vec::new();
473        for &from in &node_ids {
474            for edge_ref in self
475                .graph
476                .edges_directed(from, petgraph::Direction::Outgoing)
477            {
478                let to = edge_ref.target();
479                if node_ids.contains(&to) {
480                    if let (Some(from_node), Some(to_node)) =
481                        (self.graph.node_weight(from), self.graph.node_weight(to))
482                    {
483                        edges.push((
484                            from_node.name.clone(),
485                            to_node.name.clone(),
486                            format!("{:?}", edge_ref.weight().kind),
487                        ));
488                    }
489                }
490            }
491        }
492        (nodes, edges)
493    }
494}
495
496/// Graph statistics for the info endpoint.
497#[derive(Debug, Serialize, Deserialize)]
498pub struct GraphStats {
499    pub node_count: usize,
500    pub edge_count: usize,
501    pub files: usize,
502}
503
504impl ArborGraph {
505    /// Returns graph statistics.
506    pub fn stats(&self) -> GraphStats {
507        GraphStats {
508            node_count: self.node_count(),
509            edge_count: self.edge_count(),
510            files: self.file_index.len(),
511        }
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518    use crate::edge::{Edge, EdgeKind};
519    use arbor_core::{CodeNode, NodeKind};
520
521    fn make_node(name: &str, file: &str) -> CodeNode {
522        CodeNode::new(name, name, NodeKind::Function, file)
523    }
524
525    #[test]
526    fn test_graph_new_is_empty() {
527        let g = ArborGraph::new();
528        assert_eq!(g.node_count(), 0);
529        assert_eq!(g.edge_count(), 0);
530        assert!(g.nodes().next().is_none());
531    }
532
533    #[test]
534    fn test_graph_add_and_get_node() {
535        let mut g = ArborGraph::new();
536        let node = make_node("foo", "main.rs");
537        let id = g.add_node(node.clone());
538        assert_eq!(g.node_count(), 1);
539
540        let got = g.get(id).unwrap();
541        assert_eq!(got.name, "foo");
542    }
543
544    #[test]
545    fn test_graph_find_by_name() {
546        let mut g = ArborGraph::new();
547        g.add_node(make_node("alpha", "a.rs"));
548        g.add_node(make_node("beta", "b.rs"));
549
550        let found = g.find_by_name("alpha");
551        assert_eq!(found.len(), 1);
552        assert_eq!(found[0].name, "alpha");
553
554        let not_found = g.find_by_name("gamma");
555        assert!(not_found.is_empty());
556    }
557
558    #[test]
559    fn test_graph_find_by_file() {
560        let mut g = ArborGraph::new();
561        g.add_node(make_node("foo", "main.rs"));
562        g.add_node(make_node("bar", "main.rs"));
563        g.add_node(make_node("baz", "other.rs"));
564
565        let main_nodes = g.find_by_file("main.rs");
566        assert_eq!(main_nodes.len(), 2);
567
568        let other_nodes = g.find_by_file("other.rs");
569        assert_eq!(other_nodes.len(), 1);
570
571        let empty = g.find_by_file("nonexistent.rs");
572        assert!(empty.is_empty());
573    }
574
575    #[test]
576    fn test_graph_search_substring() {
577        let mut g = ArborGraph::new();
578        g.add_node(make_node("validate_user", "a.rs"));
579        g.add_node(make_node("validate_email", "b.rs"));
580        g.add_node(make_node("send_email", "c.rs"));
581
582        let results = g.search("validate");
583        assert_eq!(results.len(), 2);
584        assert!(results.iter().any(|n| n.name == "validate_user"));
585        assert!(results.iter().any(|n| n.name == "validate_email"));
586    }
587
588    #[test]
589    fn test_graph_callers_callees() {
590        let mut g = ArborGraph::new();
591        let a = g.add_node(make_node("caller", "a.rs"));
592        let b = g.add_node(make_node("callee", "b.rs"));
593        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
594
595        let callees = g.get_callees(a);
596        assert_eq!(callees.len(), 1);
597        assert_eq!(callees[0].name, "callee");
598
599        let callers = g.get_callers(b);
600        assert_eq!(callers.len(), 1);
601        assert_eq!(callers[0].name, "caller");
602
603        // No callers/callees for disconnected nodes
604        assert!(g.get_callers(a).is_empty());
605        assert!(g.get_callees(b).is_empty());
606    }
607
608    #[test]
609    fn test_graph_get_dependents() {
610        // a -> b -> c
611        let mut g = ArborGraph::new();
612        let a = g.add_node(make_node("a", "a.rs"));
613        let b = g.add_node(make_node("b", "b.rs"));
614        let c = g.add_node(make_node("c", "c.rs"));
615        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
616        g.add_edge(b, c, Edge::new(EdgeKind::Calls));
617
618        // Dependents of c at depth 2 should include a and b
619        let deps = g.get_dependents(c, 2);
620        assert!(deps.iter().any(|(idx, _)| g.get(*idx).unwrap().name == "b"));
621        assert!(deps.iter().any(|(idx, _)| g.get(*idx).unwrap().name == "a"));
622    }
623
624    #[test]
625    fn test_graph_remove_file_cleanup() {
626        let mut g = ArborGraph::new();
627        g.add_node(make_node("foo", "remove_me.rs"));
628        g.add_node(make_node("bar", "remove_me.rs"));
629        g.add_node(make_node("keep", "keep.rs"));
630
631        assert_eq!(g.node_count(), 3);
632
633        g.remove_file("remove_me.rs");
634
635        // Nodes from removed file are gone
636        assert!(g.find_by_name("foo").is_empty());
637        assert!(g.find_by_name("bar").is_empty());
638        // Node from other file remains
639        assert_eq!(g.find_by_name("keep").len(), 1);
640        assert!(g.find_by_file("remove_me.rs").is_empty());
641    }
642
643    #[test]
644    fn test_graph_find_path() {
645        // a -> b -> c
646        let mut g = ArborGraph::new();
647        let a = g.add_node(make_node("start", "a.rs"));
648        let b = g.add_node(make_node("middle", "b.rs"));
649        let c = g.add_node(make_node("end", "c.rs"));
650        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
651        g.add_edge(b, c, Edge::new(EdgeKind::Calls));
652
653        let path = g.find_path(a, c).unwrap();
654        assert_eq!(path.len(), 3);
655        assert_eq!(path[0].name, "start");
656        assert_eq!(path[1].name, "middle");
657        assert_eq!(path[2].name, "end");
658    }
659
660    #[test]
661    fn test_graph_find_path_no_connection() {
662        let mut g = ArborGraph::new();
663        let a = g.add_node(make_node("island_a", "a.rs"));
664        let b = g.add_node(make_node("island_b", "b.rs"));
665
666        // No edges → no path
667        assert!(g.find_path(a, b).is_none());
668    }
669
670    #[test]
671    fn test_graph_export_edges() {
672        let mut g = ArborGraph::new();
673        let a = g.add_node(make_node("a", "a.rs"));
674        let b = g.add_node(make_node("b", "b.rs"));
675        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
676
677        let exported = g.export_edges();
678        assert_eq!(exported.len(), 1);
679        assert_eq!(exported[0].kind, EdgeKind::Calls);
680    }
681
682    #[test]
683    fn test_graph_stats() {
684        let mut g = ArborGraph::new();
685        g.add_node(make_node("a", "x.rs"));
686        g.add_node(make_node("b", "y.rs"));
687
688        let stats = g.stats();
689        assert_eq!(stats.node_count, 2);
690        assert_eq!(stats.edge_count, 0);
691        assert_eq!(stats.files, 2);
692    }
693
694    #[test]
695    fn test_graph_get_index_and_get_by_id() {
696        let mut g = ArborGraph::new();
697        let node = make_node("lookup_me", "test.rs");
698        let node_id_str = node.id.clone();
699        let idx = g.add_node(node);
700
701        assert_eq!(g.get_index(&node_id_str), Some(idx));
702        assert!(g.get_by_id(&node_id_str).is_some());
703        assert!(g.get_index("nonexistent").is_none());
704        assert!(g.get_by_id("nonexistent").is_none());
705    }
706
707    #[test]
708    fn test_graph_centrality_default_zero() {
709        let mut g = ArborGraph::new();
710        let idx = g.add_node(make_node("a", "a.rs"));
711        assert_eq!(g.centrality(idx), 0.0);
712    }
713
714    #[test]
715    fn test_graph_set_centrality() {
716        let mut g = ArborGraph::new();
717        let idx = g.add_node(make_node("a", "a.rs"));
718
719        let mut scores = HashMap::new();
720        scores.insert(idx, 0.75);
721        g.set_centrality(scores);
722
723        assert!((g.centrality(idx) - 0.75).abs() < f64::EPSILON);
724    }
725}
726
727#[cfg(test)]
728mod new_query_tests {
729    use super::*;
730    use crate::edge::{Edge, EdgeKind};
731    use arbor_core::{CodeNode, NodeKind};
732
733    fn make_node(name: &str, kind: NodeKind, file: &str) -> CodeNode {
734        CodeNode::new(name, format!("{}::{}", file, name), kind, file)
735    }
736
737    #[test]
738    fn test_list_entry_points_returns_main() {
739        let mut g = ArborGraph::new();
740        g.add_node(make_node("main", NodeKind::Function, "src/main.rs"));
741        g.add_node(make_node("helper", NodeKind::Function, "src/util.rs"));
742        let eps = g.list_entry_points();
743        assert!(
744            eps.iter().any(|n| n.name == "main"),
745            "main must be an entry point"
746        );
747        assert!(
748            !eps.iter().any(|n| n.name == "helper"),
749            "helper must not be an entry point"
750        );
751    }
752
753    #[test]
754    fn test_nodes_in_file_with_edges_returns_edges() {
755        let mut g = ArborGraph::new();
756        let a = g.add_node(make_node("foo", NodeKind::Function, "src/a.rs"));
757        let b = g.add_node(make_node("bar", NodeKind::Function, "src/a.rs"));
758        let _c = g.add_node(make_node("baz", NodeKind::Function, "src/b.rs"));
759        g.add_edge(a, b, Edge::new(EdgeKind::Calls));
760        let (nodes, edges) = g.nodes_in_file_with_edges("src/a.rs");
761        assert_eq!(nodes.len(), 2);
762        assert_eq!(edges.len(), 1);
763        assert_eq!(edges[0].0, "foo");
764        assert_eq!(edges[0].1, "bar");
765    }
766
767    #[test]
768    fn nodes_in_file_lookup_is_separator_insensitive() {
769        // Callers join a project root with a forward-slash relative path,
770        // which on Windows yields `C:\root\src/lib.rs` while the parser
771        // recorded `C:\root\src\lib.rs`. Exact-key lookup missed, and
772        // `file-graph` reported "No symbols found" for a file full of symbols.
773        let mut g = ArborGraph::new();
774        g.add_node(make_node(
775            "helper",
776            NodeKind::Function,
777            r"C:/root/src\lib.rs",
778        ));
779
780        let (backslash, _) = g.nodes_in_file_with_edges(r"C:/root/src\lib.rs");
781        assert_eq!(backslash.len(), 1, "exact key must still work");
782
783        let (forward, _) = g.nodes_in_file_with_edges("C:/root/src/lib.rs");
784        assert_eq!(forward.len(), 1, "separator spelling must not matter");
785    }
786
787    #[test]
788    fn test_nodes_in_file_with_edges_excludes_cross_file_edges() {
789        use crate::edge::{Edge, EdgeKind};
790        let mut g = ArborGraph::new();
791        let a = g.add_node(make_node("foo", NodeKind::Function, "src/a.rs"));
792        let c = g.add_node(make_node("baz", NodeKind::Function, "src/b.rs"));
793        // Edge from a.rs to b.rs — should NOT appear in get_file_graph for a.rs
794        g.add_edge(a, c, Edge::new(EdgeKind::Calls));
795        let (nodes, edges) = g.nodes_in_file_with_edges("src/a.rs");
796        assert_eq!(nodes.len(), 1); // only foo
797        assert_eq!(edges.len(), 0); // cross-file edge excluded
798    }
799}
800
801/// Feeds a node's supporting text into the search index.
802///
803/// Docstrings, signatures, and qualified names are already parsed into every
804/// `CodeNode` and were previously ignored at search time — so a function
805/// documented as "validates the user's login credentials" was unreachable by a
806/// search for "login". The file path is included too: `src/auth/session.ts`
807/// says as much about a symbol as its name often does.
808fn index_node_documentation(index: &mut SearchIndex, node: &CodeNode, id: NodeId) {
809    if let Some(doc) = &node.docstring {
810        index.insert_documentation(doc, id);
811    }
812    if let Some(sig) = &node.signature {
813        index.insert_documentation(sig, id);
814    }
815    index.insert_documentation(&node.file, id);
816    if node.qualified_name != node.name {
817        index.insert_documentation(&node.qualified_name, id);
818    }
819}
820
821/// Normalizes path separators for comparison.
822///
823/// Windows accepts both `/` and `\`, so the same file can be spelled either
824/// way depending on whether the path came from a directory walk or from
825/// joining a user-supplied relative path.
826fn normalize_separators(path: &str) -> String {
827    path.replace('\\', "/")
828}