Skip to main content

lean_ctx_ext/core/repomap/
graph.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Graph builder for repo map.
3//!
4//! Constructs a file-level directed graph from the project index edges
5//! and call graph edges, then exposes symbol definitions per file.
6
7use std::collections::{HashMap, HashSet};
8
9use crate::core::call_graph::{CallGraph, CallGraphInputs};
10use crate::core::graph_index::{self, ProjectIndex, SymbolEntry};
11
12/// A symbol definition with its file context.
13#[derive(Debug, Clone)]
14pub struct SymbolDef {
15    pub name: String,
16    pub kind: String,
17    pub file: String,
18    pub line: usize,
19    pub end_line: usize,
20    pub is_exported: bool,
21    pub signature: String,
22}
23
24/// File-level graph combining import edges and call edges.
25pub struct RepoGraph {
26    pub files: HashSet<String>,
27    /// Forward adjacency: file -> list of files it depends on.
28    pub forward: HashMap<String, Vec<String>>,
29    /// All symbol definitions grouped by file.
30    pub symbols_by_file: HashMap<String, Vec<SymbolDef>>,
31}
32
33impl RepoGraph {
34    /// Build the repo graph from a project root.
35    ///
36    /// Loads or builds the project index and call graph,
37    /// then merges their edges into a unified file-level graph.
38    pub fn build(project_root: &str) -> Self {
39        let (index, content_cache) = graph_index::scan_with_content_cache(project_root);
40        let calls = graph_call_pairs(project_root).unwrap_or_else(|| {
41            let cg_inputs = CallGraphInputs::from_project_index(&index);
42            let call_graph = CallGraph::load_or_build(project_root, &cg_inputs);
43            structural_call_pairs(&cg_inputs, &call_graph)
44        });
45
46        Self::from_index_and_calls(&index, &calls, &content_cache)
47    }
48
49    /// `calls`: caller file → callee file pairs (see [`graph_call_pairs`]).
50    fn from_index_and_calls(
51        index: &ProjectIndex,
52        calls: &[(String, String)],
53        content_cache: &HashMap<String, String>,
54    ) -> Self {
55        let files: HashSet<String> = index.files.keys().cloned().collect();
56
57        let mut forward: HashMap<String, Vec<String>> = HashMap::new();
58
59        // Import edges from the project index
60        for edge in &index.edges {
61            if files.contains(&edge.from) && files.contains(&edge.to) && edge.from != edge.to {
62                forward
63                    .entry(edge.from.clone())
64                    .or_default()
65                    .push(edge.to.clone());
66            }
67        }
68
69        // Call edges, resolved like the property graph's (never by bare name)
70        for (from, to) in calls {
71            if files.contains(from) && files.contains(to) && from != to {
72                forward.entry(from.clone()).or_default().push(to.clone());
73            }
74        }
75
76        // Deduplicate edges
77        for deps in forward.values_mut() {
78            deps.sort();
79            deps.dedup();
80        }
81
82        let symbols_by_file = build_symbols_with_signatures(index, content_cache);
83
84        Self {
85            files,
86            forward,
87            symbols_by_file,
88        }
89    }
90}
91
92/// File-level `calls` edges of a current property graph: the same edges
93/// ranking and impact analysis use — scope-resolved, verified by a semantic
94/// backend where one answered, and without name-match guesses a backend
95/// vetoed. `None` without a current graph whose calls were consolidated (a
96/// freshly mirrored graph has none until enrichment runs). An empty edge set
97/// counts once a backend has answered for the graph: then every candidate
98/// was vetoed or ambiguous, and a fallback would resurrect the vetoed guess.
99fn graph_call_pairs(project_root: &str) -> Option<Vec<(String, String)>> {
100    use crate::core::property_graph::{CodeGraph, EdgeKind};
101    if crate::core::property_graph::engine_outdated(project_root) {
102        return None;
103    }
104    let graph = CodeGraph::open(project_root).ok()?;
105    let pairs: Vec<(String, String)> = graph
106        .file_edges_of_kind(&EdgeKind::Calls)
107        .ok()?
108        .into_iter()
109        // Serve-time source check (G04): an edge of a withdrawn file neither
110        // appears in the map nor ranks another file.
111        .filter(|(from, to, _)| graph.serves_file(from) && graph.serves_file(to))
112        .map(|(from, to, _)| (from, to))
113        .collect();
114    (!pairs.is_empty() || graph.has_semantic_answers().unwrap_or(false)).then_some(pairs)
115}
116
117/// Without a property graph: each call bound in the caller's own scope
118/// (same file → unique import → unique in the project); an ambiguous name
119/// yields no edge rather than an arbitrary one.
120fn structural_call_pairs(
121    inputs: &CallGraphInputs,
122    call_graph: &CallGraph,
123) -> Vec<(String, String)> {
124    crate::core::call_graph::resolve_edge_callee_files(inputs, &call_graph.edges)
125        .into_iter()
126        .zip(&call_graph.edges)
127        .filter_map(|(to, edge)| Some((edge.caller_file.clone(), to?)))
128        .collect()
129}
130
131/// Build symbol definitions with compact signatures from file contents.
132fn build_symbols_with_signatures(
133    index: &ProjectIndex,
134    content_cache: &HashMap<String, String>,
135) -> HashMap<String, Vec<SymbolDef>> {
136    let mut result: HashMap<String, Vec<SymbolDef>> = HashMap::new();
137
138    // Group index symbols by file
139    let mut idx_symbols: HashMap<&str, Vec<&SymbolEntry>> = HashMap::new();
140    for sym in index.symbols.values() {
141        idx_symbols.entry(sym.file.as_str()).or_default().push(sym);
142    }
143
144    for (file_path, file_entry) in &index.files {
145        let ext = std::path::Path::new(file_path)
146            .extension()
147            .and_then(|e| e.to_str())
148            .unwrap_or("");
149
150        // Extract signatures from file content if available
151        let signatures = content_cache
152            .get(file_path)
153            .map(|content| crate::core::signatures::extract_signatures(content, ext))
154            .unwrap_or_default();
155
156        let sig_by_name: HashMap<&str, &crate::core::signatures::Signature> =
157            signatures.iter().map(|s| (s.name.as_str(), s)).collect();
158
159        let mut file_symbols: Vec<SymbolDef> = Vec::new();
160
161        if let Some(syms) = idx_symbols.get(file_path.as_str()) {
162            for sym in syms {
163                let signature = sig_by_name
164                    .get(sym.name.as_str())
165                    .map_or_else(|| format!("{} {}", sym.kind, sym.name), |s| s.to_compact());
166
167                file_symbols.push(SymbolDef {
168                    name: sym.name.clone(),
169                    kind: sym.kind.clone(),
170                    file: sym.file.clone(),
171                    line: sym.start_line,
172                    end_line: sym.end_line,
173                    is_exported: sym.is_exported,
174                    signature,
175                });
176            }
177        }
178
179        // Also include exports from file entry that may not be in the symbols map
180        for export in &file_entry.exports {
181            let already_present = file_symbols.iter().any(|s| s.name == *export);
182            if !already_present {
183                let signature = sig_by_name
184                    .get(export.as_str())
185                    .map_or_else(|| export.clone(), |s| s.to_compact());
186
187                let (line, end_line) = sig_by_name
188                    .get(export.as_str())
189                    .and_then(|s| s.start_line.zip(s.end_line))
190                    .unwrap_or((0, 0));
191
192                file_symbols.push(SymbolDef {
193                    name: export.clone(),
194                    kind: "export".to_string(),
195                    file: file_path.clone(),
196                    line,
197                    end_line,
198                    is_exported: true,
199                    signature,
200                });
201            }
202        }
203
204        file_symbols.sort_by_key(|s| s.line);
205
206        if !file_symbols.is_empty() {
207            result.insert(file_path.clone(), file_symbols);
208        }
209    }
210
211    result
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    /// Two files define `save`; the caller imports neither. The repo map
219    /// used to link the call to whichever definition it saw first — now an
220    /// ambiguous name yields no edge, while a scope-bound one still does.
221    #[test]
222    fn ambiguous_calls_are_not_linked_by_name() {
223        use crate::core::call_graph::{CallEdge, SymbolSpan};
224        let span = |file: &str, name: &str| SymbolSpan {
225            file: file.into(),
226            name: name.into(),
227            start_line: 1,
228            end_line: 3,
229            kind: "fn".into(),
230        };
231        let inputs = CallGraphInputs {
232            project_root: "/tmp".into(),
233            file_paths: vec!["a.rs".into(), "b.rs".into(), "app.rs".into()],
234            symbols: vec![
235                span("a.rs", "save"),
236                span("b.rs", "save"),
237                span("b.rs", "load"),
238            ],
239            import_edges: Vec::new(),
240        };
241        let call = |callee: &str| CallEdge {
242            caller_file: "app.rs".into(),
243            caller_symbol: "run".into(),
244            caller_line: 2,
245            callee_name: callee.into(),
246            ..Default::default()
247        };
248        let mut call_graph = CallGraph::new("/tmp");
249        call_graph.edges = vec![call("save"), call("load")];
250
251        assert_eq!(
252            structural_call_pairs(&inputs, &call_graph),
253            [("app.rs".to_string(), "b.rs".to_string())],
254            "only the unique `load` binds"
255        );
256    }
257
258    /// A current graph without call edges is authoritative once a backend
259    /// answered for it (every guess was vetoed) — but not before enrichment.
260    #[test]
261    fn empty_graph_calls_count_only_after_a_semantic_answer() {
262        use crate::core::property_graph::{
263            CachedResolution, CodeGraph, GRAPH_ENGINE_VERSION, PropertyGraphMetaV1, write_meta,
264        };
265        let _iso = crate::core::data_dir::isolated_data_dir();
266        let proj = tempfile::tempdir().unwrap();
267        let root = proj.path().to_str().unwrap();
268        let meta = PropertyGraphMetaV1 {
269            built_at: "2026-01-01T00:00:00Z".to_string(),
270            engine_version: GRAPH_ENGINE_VERSION,
271            ..Default::default()
272        };
273        write_meta(root, &meta).unwrap();
274        let graph = CodeGraph::open(root).unwrap();
275        assert_eq!(graph_call_pairs(root), None, "not consolidated yet");
276
277        let veto = CachedResolution {
278            backend: "lsp:test@1".into(),
279            outcome: "external".into(),
280            target_file: None,
281            target_line: None,
282            target_symbol: None,
283            context: String::new(),
284        };
285        let admission = crate::core::context_admission::stores::StoreAdmission::current();
286        graph
287            .semantic_store(("app.rs", 2, 4, "definition"), "h", &veto, &admission)
288            .unwrap();
289        assert_eq!(graph_call_pairs(root), Some(Vec::new()), "vetoed stays out");
290    }
291
292    #[test]
293    fn repo_graph_deduplicates_edges() {
294        let mut index = ProjectIndex::new("/tmp");
295        index.files.insert("a.rs".into(), dummy_file_entry("a.rs"));
296        index.files.insert("b.rs".into(), dummy_file_entry("b.rs"));
297        index.edges.push(graph_index::IndexEdge {
298            from: "a.rs".into(),
299            to: "b.rs".into(),
300            kind: "import".into(),
301            weight: 1.0,
302        });
303        index.edges.push(graph_index::IndexEdge {
304            from: "a.rs".into(),
305            to: "b.rs".into(),
306            kind: "import".into(),
307            weight: 1.0,
308        });
309
310        let graph = RepoGraph::from_index_and_calls(&index, &[], &HashMap::new());
311
312        let a_deps = graph.forward.get("a.rs").unwrap();
313        assert_eq!(a_deps.len(), 1, "duplicate edges should be deduped");
314    }
315
316    #[test]
317    fn repo_graph_ignores_self_edges() {
318        let mut index = ProjectIndex::new("/tmp");
319        index.files.insert("a.rs".into(), dummy_file_entry("a.rs"));
320        index.edges.push(graph_index::IndexEdge {
321            from: "a.rs".into(),
322            to: "a.rs".into(),
323            kind: "import".into(),
324            weight: 1.0,
325        });
326
327        let graph = RepoGraph::from_index_and_calls(&index, &[], &HashMap::new());
328
329        assert!(
330            !graph.forward.contains_key("a.rs"),
331            "self-edges should be excluded"
332        );
333    }
334
335    fn dummy_file_entry(path: &str) -> graph_index::FileEntry {
336        graph_index::FileEntry {
337            path: path.into(),
338            hash: "abc".into(),
339            language: "rust".into(),
340            line_count: 10,
341            token_count: 50,
342            exports: vec![],
343            summary: String::new(),
344        }
345    }
346}