1use std::path::Path;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use super::graph_index::{self, ProjectIndex};
5use super::property_graph::served::GraphGate;
6use super::property_graph::{CodeGraph, GraphSource};
7
8static GRAPH_BUILD_TRIGGERED: AtomicBool = AtomicBool::new(false);
9
10#[derive(Debug, Clone)]
11pub struct SymbolInfo {
12 pub name: String,
13 pub file: String,
14 pub kind: String,
15 pub start_line: usize,
16 pub end_line: usize,
17 pub is_exported: bool,
18}
19
20fn index_edge_kind(pg_kind: &str) -> String {
28 match pg_kind {
29 "imports" => "import".to_string(),
30 other => other.to_string(),
31 }
32}
33
34fn line_distance(start: usize, target: Option<usize>) -> usize {
38 match target {
39 Some(t) => start.abs_diff(t),
40 None => 0,
41 }
42}
43
44fn symbol_info_from_node(n: super::property_graph::Node) -> SymbolInfo {
50 let (meta_kind, meta_exported) =
51 super::property_graph::parse_symbol_metadata(n.metadata.as_deref());
52 SymbolInfo {
53 kind: meta_kind.unwrap_or_else(|| n.kind.as_str().to_string()),
54 is_exported: meta_exported.unwrap_or(true),
55 name: n.name,
56 file: n.file_path,
57 start_line: n.line_start.unwrap_or(0),
58 end_line: n.line_end.unwrap_or(0),
59 }
60}
61
62#[derive(Debug, Clone)]
63pub struct EdgeInfo {
64 pub from: String,
65 pub to: String,
66 pub kind: String,
67 pub weight: f64,
68}
69
70#[derive(Debug, Clone)]
71pub struct FileInfo {
72 pub path: String,
73 pub hash: String,
74 pub language: String,
75 pub line_count: usize,
76 pub token_count: usize,
77 pub exports: Vec<String>,
78 pub summary: String,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum GraphProviderSource {
83 PropertyGraph,
84 GraphIndex,
85}
86
87#[allow(clippy::large_enum_variant)]
90pub enum GraphProvider {
91 PropertyGraph(CodeGraph),
92 GraphIndex(ProjectIndex),
93}
94
95pub struct OpenGraphProvider {
96 pub source: GraphProviderSource,
97 pub provider: GraphProvider,
98}
99
100fn edge_file(end: &str) -> &str {
103 end.split_once("::").map_or(end, |(file, _)| file)
104}
105
106impl GraphProvider {
112 fn index_gate(&self) -> Option<GraphGate> {
113 match self {
114 GraphProvider::PropertyGraph(_) => None,
115 GraphProvider::GraphIndex(i) => Some(GraphGate::for_root(&i.project_root)),
116 }
117 }
118
119 fn file_served(&self, gate: Option<&GraphGate>, path: &str) -> bool {
120 match self {
121 GraphProvider::PropertyGraph(g) => g.serves_file(path),
122 GraphProvider::GraphIndex(_) => gate.is_none_or(|gate| gate.file(path)),
123 }
124 }
125
126 fn symbol_served(&self, gate: Option<&GraphGate>, path: &str, name: &str) -> bool {
127 match self {
128 GraphProvider::PropertyGraph(g) => g.serves_symbol(path, name),
129 GraphProvider::GraphIndex(_) => gate.is_none_or(|gate| gate.symbol(path, name)),
130 }
131 }
132
133 fn served_from(&self, anchor: Option<&str>, paths: Vec<String>) -> Vec<String> {
136 let gate = self.index_gate();
137 if anchor.is_some_and(|anchor| !self.file_served(gate.as_ref(), anchor)) {
138 return Vec::new();
139 }
140 paths
141 .into_iter()
142 .filter(|path| self.file_served(gate.as_ref(), path))
143 .collect()
144 }
145
146 fn served_symbols(&self, symbols: Vec<SymbolInfo>) -> Vec<SymbolInfo> {
147 let gate = self.index_gate();
148 symbols
149 .into_iter()
150 .filter(|symbol| self.symbol_served(gate.as_ref(), &symbol.file, &symbol.name))
151 .collect()
152 }
153
154 pub fn dependencies(&self, file_path: &str) -> Vec<String> {
155 self.served_from(Some(file_path), self.dependencies_unchecked(file_path))
156 }
157
158 pub fn dependents(&self, file_path: &str) -> Vec<String> {
159 self.served_from(Some(file_path), self.dependents_unchecked(file_path))
160 }
161
162 pub fn related(&self, file_path: &str, depth: usize) -> Vec<String> {
167 let gate = self.index_gate();
168 let served = |path: &str| self.file_served(gate.as_ref(), path);
169 if !served(file_path) {
170 return Vec::new();
171 }
172 match self {
173 GraphProvider::PropertyGraph(g) => g
174 .impact_analysis(file_path, depth)
175 .map(|r| r.affected_files)
176 .unwrap_or_default(),
177 GraphProvider::GraphIndex(i) => i.get_related_served(file_path, depth, &served),
178 }
179 }
180
181 #[doc(hidden)]
187 pub fn ranking_graph(&self) -> (Vec<String>, Vec<EdgeInfo>) {
188 let mut files = self.file_paths_unchecked();
189 files.sort();
190 files.dedup();
191 let edges = self.edges_unchecked();
192 let pairs: Vec<(String, String)> = edges
193 .iter()
194 .map(|e| (edge_file(&e.from).to_owned(), edge_file(&e.to).to_owned()))
195 .collect();
196 let served = match self {
197 GraphProvider::PropertyGraph(g) => g.rankable_files(files.clone(), &pairs, &[]),
198 GraphProvider::GraphIndex(i) => {
199 GraphGate::for_root(&i.project_root).ranking_files(files.clone(), &pairs, &[])
200 }
201 };
202 files.retain(|file| served.contains(file));
203 let edges = edges
204 .into_iter()
205 .filter(|e| served.contains(edge_file(&e.from)) && served.contains(edge_file(&e.to)))
206 .collect();
207 (files, edges)
208 }
209
210 pub fn file_paths(&self) -> Vec<String> {
211 self.served_from(None, self.file_paths_unchecked())
212 }
213
214 pub fn find_symbols(
215 &self,
216 name: &str,
217 file_filter: Option<&str>,
218 kind_filter: Option<&str>,
219 ) -> Vec<SymbolInfo> {
220 self.served_symbols(self.find_symbols_unchecked(name, file_filter, kind_filter))
221 }
222
223 pub fn all_symbols(&self) -> Vec<SymbolInfo> {
225 self.served_symbols(self.all_symbols_unchecked())
226 }
227
228 pub fn get_symbol(&self, key: &str) -> Option<SymbolInfo> {
229 let gate = self.index_gate();
230 self.get_symbol_unchecked(key)
231 .filter(|symbol| self.symbol_served(gate.as_ref(), &symbol.file, &symbol.name))
232 }
233
234 pub fn edges(&self) -> Vec<EdgeInfo> {
235 let gate = self.index_gate();
236 let served = |end: &str| self.file_served(gate.as_ref(), edge_file(end));
237 self.edges_unchecked()
238 .into_iter()
239 .filter(|edge| served(edge.from.as_str()) && served(edge.to.as_str()))
240 .collect()
241 }
242
243 pub fn get_file_entry(&self, path: &str) -> Option<FileInfo> {
244 let gate = self.index_gate();
245 self.file_served(gate.as_ref(), path)
246 .then(|| self.get_file_entry_unchecked(path))
247 .flatten()
248 }
249
250 pub fn related_files_scored(&self, file_path: &str, limit: usize) -> Vec<(String, f64)> {
255 let gate = self.index_gate();
256 self.related_files_scored_with(gate.as_ref(), file_path, limit)
257 }
258
259 pub(crate) fn related_files_scored_with(
264 &self,
265 gate: Option<&GraphGate>,
266 file_path: &str,
267 limit: usize,
268 ) -> Vec<(String, f64)> {
269 match self {
270 GraphProvider::PropertyGraph(g) => {
271 g.related_files(file_path, limit).unwrap_or_default()
272 }
273 GraphProvider::GraphIndex(_) => {
274 let served = |path: &str| self.file_served(gate, path);
275 let mut result: Vec<(String, f64)> = Vec::new();
276 if !served(file_path) {
277 return result;
278 }
279 let neighbours = self
280 .dependencies_unchecked(file_path)
281 .into_iter()
282 .map(|dep| (dep, 1.0))
283 .chain(
284 self.dependents_unchecked(file_path)
285 .into_iter()
286 .map(|dep| (dep, 0.5)),
287 );
288 for (dep, score) in neighbours {
289 if result.len() >= limit {
290 break;
291 }
292 if !result.iter().any(|(path, _)| *path == dep) && served(&dep) {
293 result.push((dep, score));
294 }
295 }
296 result
297 }
298 }
299 }
300
301 pub fn node_count(&self) -> Option<usize> {
302 match self {
303 GraphProvider::PropertyGraph(g) => g.node_count().ok(),
304 GraphProvider::GraphIndex(i) => Some(i.file_count()),
305 }
306 }
307
308 pub fn edge_count(&self) -> Option<usize> {
309 match self {
310 GraphProvider::PropertyGraph(g) => g.edge_count().ok(),
311 GraphProvider::GraphIndex(i) => Some(i.edge_count()),
312 }
313 }
314
315 fn dependencies_unchecked(&self, file_path: &str) -> Vec<String> {
316 match self {
317 GraphProvider::PropertyGraph(g) => g.dependencies(file_path).unwrap_or_default(),
318 GraphProvider::GraphIndex(i) => i
319 .edges
320 .iter()
321 .filter(|e| e.kind == "import" && e.from == file_path)
322 .map(|e| e.to.clone())
323 .collect(),
324 }
325 }
326
327 fn dependents_unchecked(&self, file_path: &str) -> Vec<String> {
328 match self {
329 GraphProvider::PropertyGraph(g) => g.dependents(file_path).unwrap_or_default(),
330 GraphProvider::GraphIndex(i) => i
331 .edges
332 .iter()
333 .filter(|e| e.kind == "import" && e.to == file_path)
334 .map(|e| e.from.clone())
335 .collect(),
336 }
337 }
338
339 fn file_paths_unchecked(&self) -> Vec<String> {
340 match self {
341 GraphProvider::PropertyGraph(g) => g.file_catalog_paths().unwrap_or_default(),
342 GraphProvider::GraphIndex(i) => {
343 let mut paths: Vec<String> = i.files.keys().cloned().collect();
344 paths.sort();
345 paths
346 }
347 }
348 }
349
350 pub fn file_count(&self) -> usize {
351 match self {
352 GraphProvider::PropertyGraph(g) => g.file_catalog_count().unwrap_or(0),
353 GraphProvider::GraphIndex(i) => i.files.len(),
354 }
355 }
356
357 pub fn symbol_count(&self) -> usize {
358 match self {
359 GraphProvider::PropertyGraph(g) => g.symbol_count().unwrap_or(0),
360 GraphProvider::GraphIndex(i) => i.symbols.len(),
361 }
362 }
363
364 fn find_symbols_unchecked(
365 &self,
366 name: &str,
367 file_filter: Option<&str>,
368 kind_filter: Option<&str>,
369 ) -> Vec<SymbolInfo> {
370 match self {
371 GraphProvider::PropertyGraph(g) => g
372 .find_symbols(name, file_filter, None)
381 .unwrap_or_default()
382 .into_iter()
383 .map(symbol_info_from_node)
384 .filter(|s| kind_filter.is_none_or(|k| s.kind == k))
385 .collect(),
386 GraphProvider::GraphIndex(i) => {
387 let name_lower = name.to_lowercase();
388 let mut hits: Vec<_> = i
391 .symbols
392 .values()
393 .filter(|s| s.name.to_lowercase().contains(&name_lower))
394 .filter(|s| file_filter.is_none_or(|f| s.file.contains(f)))
395 .filter(|s| kind_filter.is_none_or(|k| s.kind == k))
396 .collect();
397 hits.sort_by(|a, b| {
398 (a.file.as_str(), a.start_line, a.name.as_str()).cmp(&(
399 b.file.as_str(),
400 b.start_line,
401 b.name.as_str(),
402 ))
403 });
404 hits.into_iter()
405 .take(100)
406 .map(|s| SymbolInfo {
407 name: s.name.clone(),
408 file: s.file.clone(),
409 kind: s.kind.clone(),
410 start_line: s.start_line,
411 end_line: s.end_line,
412 is_exported: s.is_exported,
413 })
414 .collect()
415 }
416 }
417 }
418
419 fn all_symbols_unchecked(&self) -> Vec<SymbolInfo> {
423 match self {
424 GraphProvider::PropertyGraph(g) => g
425 .all_symbols()
426 .unwrap_or_default()
427 .into_iter()
428 .map(symbol_info_from_node)
429 .collect(),
430 GraphProvider::GraphIndex(i) => i
431 .symbols
432 .values()
433 .map(|s| SymbolInfo {
434 name: s.name.clone(),
435 file: s.file.clone(),
436 kind: s.kind.clone(),
437 start_line: s.start_line,
438 end_line: s.end_line,
439 is_exported: s.is_exported,
440 })
441 .collect(),
442 }
443 }
444
445 fn get_symbol_unchecked(&self, key: &str) -> Option<SymbolInfo> {
446 match self {
447 GraphProvider::PropertyGraph(g) => {
448 let parts: Vec<&str> = key.splitn(2, "::").collect();
453 if parts.len() != 2 {
454 return None;
455 }
456 let (file_path, sym_name) = (parts[0], parts[1]);
457 g.get_node_by_symbol(sym_name, file_path)
458 .ok()
459 .flatten()
460 .map(symbol_info_from_node)
461 }
462 GraphProvider::GraphIndex(i) => i.get_symbol(key).map(|s| SymbolInfo {
463 name: s.name.clone(),
464 file: s.file.clone(),
465 kind: s.kind.clone(),
466 start_line: s.start_line,
467 end_line: s.end_line,
468 is_exported: s.is_exported,
469 }),
470 }
471 }
472
473 pub fn find_symbol_by_handle(
488 &self,
489 handle: &crate::core::handle::SymbolHandle,
490 ) -> Option<SymbolInfo> {
491 let key = format!("{}::{}", handle.path, handle.name);
492 if let Some(sym) = self.get_symbol(&key) {
493 return Some(sym);
494 }
495
496 let tail = handle
497 .name
498 .rsplit("::")
499 .next()
500 .unwrap_or(handle.name.as_str());
501 let mut candidates: Vec<SymbolInfo> = self
502 .all_symbols()
503 .into_iter()
504 .filter(|s| s.file == handle.path)
505 .filter(|s| s.name == handle.name || s.name.rsplit("::").next() == Some(tail))
506 .collect();
507 if candidates.is_empty() {
508 return None;
509 }
510 candidates.sort_by(|a, b| {
511 let exact_a = u8::from(a.name != handle.name);
512 let exact_b = u8::from(b.name != handle.name);
513 exact_a
514 .cmp(&exact_b)
515 .then_with(|| {
516 line_distance(a.start_line, handle.line)
517 .cmp(&line_distance(b.start_line, handle.line))
518 })
519 .then_with(|| a.start_line.cmp(&b.start_line))
520 .then_with(|| a.name.cmp(&b.name))
521 });
522 candidates.into_iter().next()
523 }
524
525 fn edges_unchecked(&self) -> Vec<EdgeInfo> {
526 match self {
527 GraphProvider::PropertyGraph(g) => g
533 .all_edges_flat()
534 .unwrap_or_default()
535 .into_iter()
536 .map(|(from, to, kind, weight)| EdgeInfo {
537 from,
538 to,
539 kind: index_edge_kind(&kind),
540 weight,
541 })
542 .collect(),
543 GraphProvider::GraphIndex(i) => i
544 .edges
545 .iter()
546 .map(|e| EdgeInfo {
547 from: e.from.clone(),
548 to: e.to.clone(),
549 kind: e.kind.clone(),
550 weight: e.weight as f64,
551 })
552 .collect(),
553 }
554 }
555
556 pub fn edges_by_kind(&self, kind: &str) -> Vec<EdgeInfo> {
557 self.edges()
558 .into_iter()
559 .filter(|e| e.kind == kind)
560 .collect()
561 }
562
563 pub fn file_entries(&self) -> Vec<FileInfo> {
567 match self {
568 GraphProvider::PropertyGraph(_) => self
569 .file_paths()
570 .into_iter()
571 .filter_map(|p| self.get_file_entry_unchecked(&p))
572 .collect(),
573 GraphProvider::GraphIndex(i) => {
574 let gate = self.index_gate();
575 i.files
576 .values()
577 .filter(|e| self.file_served(gate.as_ref(), &e.path))
578 .map(|e| FileInfo {
579 path: e.path.clone(),
580 hash: e.hash.clone(),
581 language: e.language.clone(),
582 line_count: e.line_count,
583 token_count: e.token_count,
584 exports: e.exports.clone(),
585 summary: e.summary.clone(),
586 })
587 .collect()
588 }
589 }
590 }
591
592 fn get_file_entry_unchecked(&self, path: &str) -> Option<FileInfo> {
593 match self {
594 GraphProvider::PropertyGraph(g) => {
595 g.get_file_catalog(path).ok().flatten().map(|e| FileInfo {
596 path: e.path,
597 hash: e.hash,
598 language: e.language,
599 line_count: e.line_count,
600 token_count: e.token_count,
601 exports: e.exports,
602 summary: e.summary,
603 })
604 }
605 GraphProvider::GraphIndex(i) => i.files.get(path).map(|e| FileInfo {
606 path: e.path.clone(),
607 hash: e.hash.clone(),
608 language: e.language.clone(),
609 line_count: e.line_count,
610 token_count: e.token_count,
611 exports: e.exports.clone(),
612 summary: e.summary.clone(),
613 }),
614 }
615 }
616
617 pub fn last_scan(&self) -> String {
618 match self {
619 GraphProvider::PropertyGraph(g) => g
621 .db_path()
622 .parent()
623 .and_then(super::property_graph::load_meta_from_dir)
624 .and_then(|meta| meta.built_at_local())
625 .unwrap_or_default(),
626 GraphProvider::GraphIndex(i) => i.last_scan.clone(),
627 }
628 }
629
630 pub fn materialize_project_index(&self, project_root: &str) -> ProjectIndex {
639 if let GraphProvider::GraphIndex(i) = self {
640 let gate = self.index_gate();
642 let served = |path: &str| self.file_served(gate.as_ref(), path);
643 let mut index = i.clone();
644 index.files.retain(|path, _| served(path.as_str()));
645 index
646 .symbols
647 .retain(|_, symbol| self.symbol_served(gate.as_ref(), &symbol.file, &symbol.name));
648 index
649 .edges
650 .retain(|edge| served(edge_file(&edge.from)) && served(edge_file(&edge.to)));
651 index.rebuild_interner();
652 return index;
653 }
654 let mut idx = ProjectIndex::new(project_root);
655 if let Some(stamp) =
660 super::property_graph::load_meta(project_root).and_then(|meta| meta.built_at_local())
661 {
662 idx.last_scan = stamp;
663 }
664 for f in self.file_entries() {
665 idx.files.insert(
666 f.path.clone(),
667 graph_index::FileEntry {
668 path: f.path,
669 hash: f.hash,
670 language: f.language,
671 line_count: f.line_count,
672 token_count: f.token_count,
673 exports: f.exports,
674 summary: f.summary,
675 },
676 );
677 }
678 for s in self.all_symbols() {
679 let key = format!("{}::{}", s.file, s.name);
680 idx.symbols.insert(
681 key,
682 graph_index::SymbolEntry {
683 file: s.file,
684 name: s.name,
685 kind: s.kind,
686 start_line: s.start_line,
687 end_line: s.end_line,
688 is_exported: s.is_exported,
689 },
690 );
691 }
692 for e in self.edges() {
693 idx.edges.push(graph_index::IndexEdge {
696 from: e.from,
697 to: e.to,
698 kind: e.kind,
699 weight: e.weight as f32,
700 });
701 }
702 idx.rebuild_interner();
703 idx
704 }
705
706 pub fn index_dir(project_root: &str) -> Option<std::path::PathBuf> {
707 graph_index::ProjectIndex::index_dir(project_root)
708 }
709}
710
711fn open_existing(project_root: &str) -> (Option<OpenGraphProvider>, bool) {
719 let t0 = std::time::Instant::now();
720
721 let mut pg_provider = None;
722 let mut pg_populated = false;
723 let pg_current = !crate::core::property_graph::engine_outdated(project_root);
727 if pg_current && let Ok(pg) = CodeGraph::open(project_root) {
728 let nodes = pg.node_count().unwrap_or(0);
729 let edges = pg.edge_count().unwrap_or(0);
730 let file_cat = pg.file_catalog_count().unwrap_or(0);
731 pg_populated = nodes > 0 && edges > 0 && file_cat > 0;
732 if pg_populated {
733 log_source_selection(GraphProviderSource::PropertyGraph, nodes, edges, t0);
734 return (
735 Some(OpenGraphProvider {
736 source: GraphProviderSource::PropertyGraph,
737 provider: GraphProvider::PropertyGraph(pg),
738 }),
739 false,
740 );
741 }
742 if nodes > 0 && file_cat > 0 {
743 pg_provider = Some(pg);
744 }
745 }
746
747 let needs_build = !pg_populated;
749
750 if let Some(idx) = super::index_orchestrator::try_load_graph_index(project_root) {
751 let files = idx.files.len();
752 let edges = idx.edges.len();
753 if !idx.edges.is_empty() || !idx.files.is_empty() {
754 log_source_selection(GraphProviderSource::GraphIndex, files, edges, t0);
755 return (
756 Some(OpenGraphProvider {
757 source: GraphProviderSource::GraphIndex,
758 provider: GraphProvider::GraphIndex(idx),
759 }),
760 needs_build,
761 );
762 }
763 }
764
765 if let Some(pg) = pg_provider {
766 let nodes = pg.node_count().unwrap_or(0);
767 log_source_selection(GraphProviderSource::PropertyGraph, nodes, 0, t0);
768 return (
769 Some(OpenGraphProvider {
770 source: GraphProviderSource::PropertyGraph,
771 provider: GraphProvider::PropertyGraph(pg),
772 }),
773 needs_build,
774 );
775 }
776
777 (None, needs_build)
778}
779
780pub fn open_best_effort(project_root: &str) -> Option<OpenGraphProvider> {
786 let (existing, needs_build) = open_existing(project_root);
787 if needs_build {
788 trigger_lazy_graph_build(project_root);
789 }
790 existing
791}
792
793pub fn open_ready(project_root: &str) -> Option<OpenGraphProvider> {
800 let ready = if crate::core::property_graph::engine_outdated(project_root) {
801 None
802 } else {
803 CodeGraph::open(project_root).ok().filter(|pg| {
806 pg.node_count().unwrap_or(0) > 0 && pg.file_catalog_count().unwrap_or(0) > 0
807 })
808 };
809 if let Some(pg) = ready {
810 Some(OpenGraphProvider {
811 source: GraphProviderSource::PropertyGraph,
812 provider: GraphProvider::PropertyGraph(pg),
813 })
814 } else {
815 trigger_lazy_graph_build(project_root);
816 None
817 }
818}
819
820fn log_source_selection(
821 source: GraphProviderSource,
822 nodes: usize,
823 edges: usize,
824 start: std::time::Instant,
825) {
826 let elapsed_ms = start.elapsed().as_millis();
827 if std::env::var("LCTX_DEBUG").is_ok() {
828 eprintln!(
829 "[graph_provider] source={source:?} nodes={nodes} edges={edges} resolve_ms={elapsed_ms}"
830 );
831 }
832 let _ = (source, nodes, edges, elapsed_ms);
833}
834
835fn trigger_lazy_graph_build(project_root: &str) {
837 if cfg!(test) {
846 return;
847 }
848 if GRAPH_BUILD_TRIGGERED.load(Ordering::SeqCst) {
851 return;
852 }
853 let root = Path::new(project_root);
854 let is_project = crate::core::pathutil::has_project_marker(root)
857 || crate::core::pathutil::has_multi_repo_children(root);
858 if !is_project {
859 return;
860 }
861 if GRAPH_BUILD_TRIGGERED.swap(true, Ordering::SeqCst) {
862 return;
863 }
864 super::index_orchestrator::ensure_all_background(project_root);
868}
869
870pub fn build_property_graph(project_root: &str) -> anyhow::Result<()> {
881 let index = super::index_orchestrator::try_load_graph_index(project_root)
882 .filter(|i| !i.files.is_empty())
883 .unwrap_or_else(|| graph_index::scan_with_content_cache(project_root).0);
884 super::property_graph::mirror_index(project_root, &index)
885}
886
887const BUILD_TIMEOUT_SECS: u64 = 30;
891
892static BUILD_GATE: std::sync::LazyLock<std::sync::Mutex<()>> =
897 std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
898
899pub fn open_or_build(project_root: &str) -> Option<OpenGraphProvider> {
900 if let (Some(p), _) = open_existing(project_root) {
901 return Some(p);
902 }
903
904 let _gate = if cfg!(test) {
907 BUILD_GATE
908 .lock()
909 .unwrap_or_else(std::sync::PoisonError::into_inner)
910 } else {
911 let Ok(gate) = BUILD_GATE.try_lock() else {
912 tracing::info!(
913 "open_or_build: another build in progress for {project_root}; returning None"
914 );
915 trigger_lazy_graph_build(project_root);
916 return None;
917 };
918 gate
919 };
920
921 let root_owned = project_root.to_string();
924 let (tx, rx) = std::sync::mpsc::sync_channel(1);
925 std::thread::spawn(move || {
926 let idx = super::graph_index::load_or_build(&root_owned);
927 let _ = tx.send(idx);
928 });
929
930 let timeout = std::time::Duration::from_secs(BUILD_TIMEOUT_SECS);
931 match rx.recv_timeout(timeout) {
932 Ok(idx) if !idx.files.is_empty() => Some(OpenGraphProvider {
933 source: GraphProviderSource::GraphIndex,
934 provider: GraphProvider::GraphIndex(idx),
935 }),
936 Ok(_) => None,
937 Err(_) => {
938 tracing::warn!(
939 "open_or_build: graph build timed out after {BUILD_TIMEOUT_SECS}s for {project_root}; \
940 triggering background build"
941 );
942 trigger_lazy_graph_build(project_root);
943 None
944 }
945 }
946}
947#[cfg(test)]
948mod tests {
949 use super::*;
950
951 #[test]
952 fn best_effort_prefers_graph_index_when_property_graph_empty() {
953 let _lock = crate::core::data_dir::test_env_lock();
954 let tmp = tempfile::tempdir().expect("tempdir");
955 let data = tmp.path().join("data");
956 std::fs::create_dir_all(&data).expect("mkdir data");
957 crate::test_env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
958
959 let project_root = tmp.path().join("proj");
960 std::fs::create_dir_all(&project_root).expect("mkdir proj");
961 let root = project_root.to_string_lossy().to_string();
962 std::fs::create_dir_all(project_root.join("src")).expect("mkdir src");
964 std::fs::write(project_root.join("src/main.rs"), "fn main() {}\n").expect("source");
965
966 let mut idx = ProjectIndex::new(&root);
967 idx.files.insert(
968 "src/main.rs".to_string(),
969 super::super::graph_index::FileEntry {
970 path: "src/main.rs".to_string(),
971 hash: "h".to_string(),
972 language: "rs".to_string(),
973 line_count: 1,
974 token_count: 1,
975 exports: vec![],
976 summary: String::new(),
977 },
978 );
979 idx.save().expect("save index");
980
981 let open = open_best_effort(&root).expect("open");
982 assert_eq!(open.source, GraphProviderSource::GraphIndex);
983
984 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
985 }
986
987 #[test]
988 fn best_effort_none_when_no_graphs() {
989 let _lock = crate::core::data_dir::test_env_lock();
990 let tmp = tempfile::tempdir().expect("tempdir");
991 let data = tmp.path().join("data");
992 std::fs::create_dir_all(&data).expect("mkdir data");
993 crate::test_env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
994
995 let project_root = tmp.path().join("proj");
996 std::fs::create_dir_all(&project_root).expect("mkdir proj");
997 let root = project_root.to_string_lossy().to_string();
998
999 let open = open_best_effort(&root);
1000 assert!(open.is_none());
1001
1002 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1003 }
1004
1005 fn handle_provider() -> (GraphProvider, tempfile::TempDir) {
1006 let mut idx = ProjectIndex::new("/test");
1007 for (key, file, name, kind, start, end) in [
1008 (
1009 "src/lib.rs::Config",
1010 "src/lib.rs",
1011 "Config",
1012 "struct",
1013 5usize,
1014 20usize,
1015 ),
1016 (
1017 "src/lib.rs::Config::load",
1018 "src/lib.rs",
1019 "Config::load",
1020 "method",
1021 22,
1022 35,
1023 ),
1024 ("src/main.rs::main", "src/main.rs", "main", "fn", 1, 10),
1025 ] {
1026 idx.symbols.insert(
1027 key.to_string(),
1028 graph_index::SymbolEntry {
1029 file: file.to_string(),
1030 name: name.to_string(),
1031 kind: kind.to_string(),
1032 start_line: start,
1033 end_line: end,
1034 is_exported: true,
1035 },
1036 );
1037 }
1038 let (idx, files) = idx.on_disk(&[]);
1039 (GraphProvider::GraphIndex(idx), files)
1040 }
1041
1042 #[test]
1043 fn handle_resolves_exact_file_and_name() {
1044 let (gp, _files) = handle_provider();
1045 let h = crate::core::handle::SymbolHandle::new("src/lib.rs", "Config::load", 22);
1046 let sym = gp.find_symbol_by_handle(&h).expect("resolves");
1047 assert_eq!(sym.name, "Config::load");
1048 assert_eq!(sym.start_line, 22);
1049 }
1050
1051 #[test]
1052 fn handle_resolves_after_line_drift() {
1053 let (gp, _files) = handle_provider();
1056 let h = crate::core::handle::SymbolHandle::new("src/lib.rs", "Config::load", 999);
1057 let sym = gp
1058 .find_symbol_by_handle(&h)
1059 .expect("resolves despite drift");
1060 assert_eq!(sym.start_line, 22);
1061 }
1062
1063 #[test]
1064 fn handle_resolves_by_unqualified_tail() {
1065 let (gp, _files) = handle_provider();
1068 let h = crate::core::handle::SymbolHandle::new("src/lib.rs", "load", 22);
1069 let sym = gp.find_symbol_by_handle(&h).expect("resolves by tail");
1070 assert_eq!(sym.name, "Config::load");
1071 }
1072
1073 #[test]
1074 fn handle_unknown_file_returns_none() {
1075 let (gp, _files) = handle_provider();
1076 let h = crate::core::handle::SymbolHandle::new("src/nope.rs", "Config::load", 22);
1077 assert!(gp.find_symbol_by_handle(&h).is_none());
1078 }
1079
1080 #[test]
1081 fn pg_kind_filter_matches_precise_metadata_kind() {
1082 use super::super::property_graph::{Node, NodeKind};
1086
1087 let pg = CodeGraph::open_in_memory().unwrap();
1088 pg.upsert_node(
1089 &Node::symbol("State", "simplex/simplex.go", NodeKind::Symbol)
1090 .with_lines(129, 140)
1091 .with_metadata(r#"{"kind":"struct","exported":true}"#),
1092 )
1093 .unwrap();
1094 let gp = GraphProvider::PropertyGraph(pg);
1095
1096 let hits = gp.find_symbols("State", None, Some("struct"));
1097 assert_eq!(
1098 hits.len(),
1099 1,
1100 "kind=struct must resolve the exported struct"
1101 );
1102 assert_eq!(hits[0].kind, "struct");
1103 assert!(hits[0].is_exported);
1104
1105 assert!(gp.find_symbols("State", None, Some("fn")).is_empty());
1107 }
1108
1109 #[test]
1110 fn parity_dependencies_both_stores_agree() {
1111 use super::super::graph_index::{FileEntry, IndexEdge};
1112 use super::super::property_graph::{Edge, EdgeKind, Node};
1113
1114 let pg = CodeGraph::open_in_memory().unwrap();
1115 let a_id = pg.upsert_node(&Node::file("src/a.rs")).unwrap();
1116 let b_id = pg.upsert_node(&Node::file("src/b.rs")).unwrap();
1117 let c_id = pg.upsert_node(&Node::file("src/c.rs")).unwrap();
1118 pg.upsert_edge(&Edge::new(a_id, b_id, EdgeKind::Imports))
1119 .unwrap();
1120 pg.upsert_edge(&Edge::new(a_id, c_id, EdgeKind::Imports))
1121 .unwrap();
1122
1123 let mut idx = ProjectIndex::new("/test");
1124 for name in &["src/a.rs", "src/b.rs", "src/c.rs"] {
1125 idx.files.insert(
1126 name.to_string(),
1127 FileEntry {
1128 path: name.to_string(),
1129 hash: "h".into(),
1130 language: "rs".into(),
1131 line_count: 1,
1132 token_count: 1,
1133 exports: vec![],
1134 summary: String::new(),
1135 },
1136 );
1137 }
1138 idx.edges.push(IndexEdge {
1139 from: "src/a.rs".into(),
1140 to: "src/b.rs".into(),
1141 kind: "import".into(),
1142 weight: 1.0,
1143 });
1144 idx.edges.push(IndexEdge {
1145 from: "src/a.rs".into(),
1146 to: "src/c.rs".into(),
1147 kind: "import".into(),
1148 weight: 1.0,
1149 });
1150
1151 let pg_deps = GraphProvider::PropertyGraph(pg);
1152 let (idx, _files) = idx.on_disk(&[]);
1153 let gi_deps = GraphProvider::GraphIndex(idx);
1154
1155 let mut pg_result = pg_deps.dependencies("src/a.rs");
1156 let mut gi_result = gi_deps.dependencies("src/a.rs");
1157 pg_result.sort();
1158 gi_result.sort();
1159
1160 assert_eq!(
1161 pg_result, gi_result,
1162 "Import edges must match between PG and GraphIndex"
1163 );
1164
1165 let mut pg_dependents = pg_deps.dependents("src/b.rs");
1166 let mut gi_dependents = gi_deps.dependents("src/b.rs");
1167 pg_dependents.sort();
1168 gi_dependents.sort();
1169 assert_eq!(
1170 pg_dependents, gi_dependents,
1171 "Dependents must match between PG and GraphIndex"
1172 );
1173 }
1174
1175 #[test]
1182 fn materialize_project_index_round_trips_losslessly() {
1183 use super::super::graph_index::{FileEntry, IndexEdge, SymbolEntry};
1184 use super::super::property_graph::populate_from_project_index;
1185
1186 let mut a = ProjectIndex::new("/test");
1187 a.files.insert(
1188 "src/a.rs".to_string(),
1189 FileEntry {
1190 path: "src/a.rs".to_string(),
1191 hash: "hash-a".to_string(),
1192 language: "rs".to_string(),
1193 line_count: 42,
1194 token_count: 137,
1195 exports: vec!["Foo".to_string()],
1196 summary: "module a".to_string(),
1197 },
1198 );
1199 a.files.insert(
1200 "src/b.rs".to_string(),
1201 FileEntry {
1202 path: "src/b.rs".to_string(),
1203 hash: "hash-b".to_string(),
1204 language: "rs".to_string(),
1205 line_count: 7,
1206 token_count: 19,
1207 exports: vec![],
1208 summary: String::new(),
1209 },
1210 );
1211 a.symbols.insert(
1214 "src/a.rs::Foo".to_string(),
1215 SymbolEntry {
1216 file: "src/a.rs".to_string(),
1217 name: "Foo".to_string(),
1218 kind: "struct".to_string(),
1219 start_line: 1,
1220 end_line: 9,
1221 is_exported: true,
1222 },
1223 );
1224 a.symbols.insert(
1225 "src/b.rs::helper".to_string(),
1226 SymbolEntry {
1227 file: "src/b.rs".to_string(),
1228 name: "helper".to_string(),
1229 kind: "function".to_string(),
1230 start_line: 3,
1231 end_line: 6,
1232 is_exported: false,
1233 },
1234 );
1235 a.edges.push(IndexEdge {
1236 from: "src/b.rs".to_string(),
1237 to: "src/a.rs".to_string(),
1238 kind: "import".to_string(),
1239 weight: 1.0,
1240 });
1241
1242 let pg = CodeGraph::open_in_memory().unwrap();
1243 populate_from_project_index(&pg, &a).unwrap();
1244 let provider = GraphProvider::PropertyGraph(pg);
1245 let b = provider.materialize_project_index("/test");
1246
1247 let mut a_files: Vec<&String> = a.files.keys().collect();
1249 let mut b_files: Vec<&String> = b.files.keys().collect();
1250 a_files.sort();
1251 b_files.sort();
1252 assert_eq!(a_files, b_files, "file inventory must round-trip");
1253 for (path, fa) in &a.files {
1254 let fb = b.files.get(path).expect("file present after round trip");
1255 assert_eq!(fa.hash, fb.hash, "hash {path}");
1256 assert_eq!(fa.language, fb.language, "language {path}");
1257 assert_eq!(fa.line_count, fb.line_count, "line_count {path}");
1258 assert_eq!(fa.token_count, fb.token_count, "token_count {path}");
1259 assert_eq!(fa.exports, fb.exports, "exports {path}");
1260 assert_eq!(fa.summary, fb.summary, "summary {path}");
1261 }
1262
1263 let mut a_syms: Vec<&String> = a.symbols.keys().collect();
1265 let mut b_syms: Vec<&String> = b.symbols.keys().collect();
1266 a_syms.sort();
1267 b_syms.sort();
1268 assert_eq!(a_syms, b_syms, "symbol table must round-trip");
1269 for (key, sa) in &a.symbols {
1270 let sb = b.symbols.get(key).expect("symbol present after round trip");
1271 assert_eq!(sa.name, sb.name, "name {key}");
1272 assert_eq!(sa.file, sb.file, "file {key}");
1273 assert_eq!(sa.kind, sb.kind, "kind {key}");
1274 assert_eq!(sa.start_line, sb.start_line, "start_line {key}");
1275 assert_eq!(sa.end_line, sb.end_line, "end_line {key}");
1276 assert_eq!(sa.is_exported, sb.is_exported, "is_exported {key}");
1277 }
1278
1279 assert!(
1281 b.edges
1282 .iter()
1283 .any(|e| e.from == "src/b.rs" && e.to == "src/a.rs" && e.kind == "import"),
1284 "import edge must round-trip; got {:?}",
1285 b.edges
1286 );
1287 }
1288}