lean_ctx/core/
graph_provider.rs1use std::path::Path;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use super::graph_index::ProjectIndex;
5use super::property_graph::CodeGraph;
6
7static GRAPH_BUILD_TRIGGERED: AtomicBool = AtomicBool::new(false);
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum GraphProviderSource {
11 PropertyGraph,
12 GraphIndex,
13}
14
15pub enum GraphProvider {
16 PropertyGraph(CodeGraph),
17 GraphIndex(ProjectIndex),
18}
19
20pub struct OpenGraphProvider {
21 pub source: GraphProviderSource,
22 pub provider: GraphProvider,
23}
24
25impl GraphProvider {
26 pub fn node_count(&self) -> Option<usize> {
27 match self {
28 GraphProvider::PropertyGraph(g) => g.node_count().ok(),
29 GraphProvider::GraphIndex(i) => Some(i.file_count()),
30 }
31 }
32
33 pub fn edge_count(&self) -> Option<usize> {
34 match self {
35 GraphProvider::PropertyGraph(g) => g.edge_count().ok(),
36 GraphProvider::GraphIndex(i) => Some(i.edge_count()),
37 }
38 }
39
40 pub fn dependencies(&self, file_path: &str) -> Vec<String> {
41 match self {
42 GraphProvider::PropertyGraph(g) => g.dependencies(file_path).unwrap_or_default(),
43 GraphProvider::GraphIndex(i) => i
44 .edges
45 .iter()
46 .filter(|e| e.kind == "import" && e.from == file_path)
47 .map(|e| e.to.clone())
48 .collect(),
49 }
50 }
51
52 pub fn dependents(&self, file_path: &str) -> Vec<String> {
53 match self {
54 GraphProvider::PropertyGraph(g) => g.dependents(file_path).unwrap_or_default(),
55 GraphProvider::GraphIndex(i) => i
56 .edges
57 .iter()
58 .filter(|e| e.kind == "import" && e.to == file_path)
59 .map(|e| e.from.clone())
60 .collect(),
61 }
62 }
63
64 pub fn related(&self, file_path: &str, depth: usize) -> Vec<String> {
65 match self {
66 GraphProvider::PropertyGraph(g) => g
67 .impact_analysis(file_path, depth)
68 .map(|r| r.affected_files)
69 .unwrap_or_default(),
70 GraphProvider::GraphIndex(i) => i.get_related(file_path, depth),
71 }
72 }
73
74 pub fn related_files_scored(&self, file_path: &str, limit: usize) -> Vec<(String, f64)> {
77 match self {
78 GraphProvider::PropertyGraph(g) => {
79 g.related_files(file_path, limit).unwrap_or_default()
80 }
81 GraphProvider::GraphIndex(_) => {
82 let mut result: Vec<(String, f64)> = Vec::new();
83 for dep in self.dependencies(file_path) {
84 result.push((dep, 1.0));
85 }
86 for dep in self.dependents(file_path) {
87 if !result.iter().any(|(p, _)| *p == dep) {
88 result.push((dep, 0.5));
89 }
90 }
91 result.truncate(limit);
92 result
93 }
94 }
95 }
96}
97
98pub fn open_best_effort(project_root: &str) -> Option<OpenGraphProvider> {
99 let mut pg_provider = None;
100 let mut pg_populated = false;
101 if let Ok(pg) = CodeGraph::open(project_root) {
102 let nodes = pg.node_count().unwrap_or(0);
103 let edges = pg.edge_count().unwrap_or(0);
104 pg_populated = nodes > 0 && edges > 0;
105 if pg_populated {
106 return Some(OpenGraphProvider {
107 source: GraphProviderSource::PropertyGraph,
108 provider: GraphProvider::PropertyGraph(pg),
109 });
110 }
111 if nodes > 0 {
112 pg_provider = Some(pg);
113 }
114 }
115
116 if !pg_populated {
119 trigger_lazy_graph_build(project_root);
120 }
121
122 if let Some(idx) = super::index_orchestrator::try_load_graph_index(project_root) {
123 if !idx.edges.is_empty() {
124 return Some(OpenGraphProvider {
125 source: GraphProviderSource::GraphIndex,
126 provider: GraphProvider::GraphIndex(idx),
127 });
128 }
129 if !idx.files.is_empty() {
130 return Some(OpenGraphProvider {
131 source: GraphProviderSource::GraphIndex,
132 provider: GraphProvider::GraphIndex(idx),
133 });
134 }
135 }
136
137 if let Some(pg) = pg_provider {
138 return Some(OpenGraphProvider {
139 source: GraphProviderSource::PropertyGraph,
140 provider: GraphProvider::PropertyGraph(pg),
141 });
142 }
143
144 None
145}
146
147fn trigger_lazy_graph_build(project_root: &str) {
149 if GRAPH_BUILD_TRIGGERED.swap(true, Ordering::SeqCst) {
150 return;
151 }
152 let root = Path::new(project_root);
153 let is_project = root.is_dir()
154 && (root.join(".git").exists()
155 || root.join("Cargo.toml").exists()
156 || root.join("package.json").exists()
157 || root.join("go.mod").exists());
158 if !is_project {
159 return;
160 }
161 let root_owned = project_root.to_string();
162 std::thread::spawn(move || {
163 let _ = crate::tools::ctx_impact::handle("build", None, &root_owned, None, None);
166 });
167}
168
169pub fn open_or_build(project_root: &str) -> Option<OpenGraphProvider> {
170 if let Some(p) = open_best_effort(project_root) {
171 return Some(p);
172 }
173 let idx = super::graph_index::load_or_build(project_root);
174 if idx.files.is_empty() {
175 return None;
176 }
177 Some(OpenGraphProvider {
178 source: GraphProviderSource::GraphIndex,
179 provider: GraphProvider::GraphIndex(idx),
180 })
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn best_effort_prefers_graph_index_when_property_graph_empty() {
189 let _lock = crate::core::data_dir::test_env_lock();
190 let tmp = tempfile::tempdir().expect("tempdir");
191 let data = tmp.path().join("data");
192 std::fs::create_dir_all(&data).expect("mkdir data");
193 std::env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
194
195 let project_root = tmp.path().join("proj");
196 std::fs::create_dir_all(&project_root).expect("mkdir proj");
197 let root = project_root.to_string_lossy().to_string();
198
199 let mut idx = ProjectIndex::new(&root);
200 idx.files.insert(
201 "src/main.rs".to_string(),
202 super::super::graph_index::FileEntry {
203 path: "src/main.rs".to_string(),
204 hash: "h".to_string(),
205 language: "rs".to_string(),
206 line_count: 1,
207 token_count: 1,
208 exports: vec![],
209 summary: String::new(),
210 },
211 );
212 idx.save().expect("save index");
213
214 let open = open_best_effort(&root).expect("open");
215 assert_eq!(open.source, GraphProviderSource::GraphIndex);
216
217 std::env::remove_var("LEAN_CTX_DATA_DIR");
218 }
219
220 #[test]
221 fn best_effort_none_when_no_graphs() {
222 let _lock = crate::core::data_dir::test_env_lock();
223 let tmp = tempfile::tempdir().expect("tempdir");
224 let data = tmp.path().join("data");
225 std::fs::create_dir_all(&data).expect("mkdir data");
226 std::env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
227
228 let project_root = tmp.path().join("proj");
229 std::fs::create_dir_all(&project_root).expect("mkdir proj");
230 let root = project_root.to_string_lossy().to_string();
231
232 let open = open_best_effort(&root);
233 assert!(open.is_none());
234
235 std::env::remove_var("LEAN_CTX_DATA_DIR");
236 }
237}