Skip to main content

lean_ctx/core/
graph_provider.rs

1use std::path::Path;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use super::graph_index::{self, ProjectIndex};
5use super::property_graph::CodeGraph;
6
7static GRAPH_BUILD_TRIGGERED: AtomicBool = AtomicBool::new(false);
8
9#[derive(Debug, Clone)]
10pub struct SymbolInfo {
11    pub name: String,
12    pub file: String,
13    pub kind: String,
14    pub start_line: usize,
15    pub end_line: usize,
16    pub is_exported: bool,
17}
18
19/// Normalize a property-graph edge-kind string back to the graph_index spelling
20/// when materializing a [`ProjectIndex`]. The mirror maps graph_index `import` →
21/// `EdgeKind::Imports`, which serializes as the plural `imports`; the legacy
22/// dependency consumers (`graph_index` BFS, the facade's index-backed
23/// `dependencies`/`dependents`, `ctx_graph`) filter on the singular `import`, so
24/// reverse exactly that one rename. All other kinds already share their spelling
25/// across both stores (#696 C1).
26fn index_edge_kind(pg_kind: &str) -> String {
27    match pg_kind {
28        "imports" => "import".to_string(),
29        other => other.to_string(),
30    }
31}
32
33/// Absolute distance from a symbol's `start` line to a handle's hint `line`.
34/// A missing hint contributes zero distance, so handles without an `@Lline`
35/// suffix neither help nor hurt the tiebreak (all candidates rank equal here).
36fn line_distance(start: usize, target: Option<usize>) -> usize {
37    match target {
38        Some(t) => start.abs_diff(t),
39        None => 0,
40    }
41}
42
43/// Convert a property-graph symbol [`Node`] into a backend-agnostic
44/// [`SymbolInfo`], recovering the precise source `kind` and export flag from the
45/// node metadata (the `Node` itself only carries a coarse `NodeKind`). Single
46/// source of truth for the three facade methods that surface PG symbols, so a
47/// materialized `ProjectIndex` is lossless (#696 C1).
48fn symbol_info_from_node(n: super::property_graph::Node) -> SymbolInfo {
49    let (meta_kind, meta_exported) =
50        super::property_graph::parse_symbol_metadata(n.metadata.as_deref());
51    SymbolInfo {
52        kind: meta_kind.unwrap_or_else(|| n.kind.as_str().to_string()),
53        is_exported: meta_exported.unwrap_or(true),
54        name: n.name,
55        file: n.file_path,
56        start_line: n.line_start.unwrap_or(0),
57        end_line: n.line_end.unwrap_or(0),
58    }
59}
60
61#[derive(Debug, Clone)]
62pub struct EdgeInfo {
63    pub from: String,
64    pub to: String,
65    pub kind: String,
66    pub weight: f64,
67}
68
69#[derive(Debug, Clone)]
70pub struct FileInfo {
71    pub path: String,
72    pub hash: String,
73    pub language: String,
74    pub line_count: usize,
75    pub token_count: usize,
76    pub exports: Vec<String>,
77    pub summary: String,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum GraphProviderSource {
82    PropertyGraph,
83    GraphIndex,
84}
85
86pub enum GraphProvider {
87    PropertyGraph(CodeGraph),
88    GraphIndex(ProjectIndex),
89}
90
91pub struct OpenGraphProvider {
92    pub source: GraphProviderSource,
93    pub provider: GraphProvider,
94}
95
96impl GraphProvider {
97    pub fn node_count(&self) -> Option<usize> {
98        match self {
99            GraphProvider::PropertyGraph(g) => g.node_count().ok(),
100            GraphProvider::GraphIndex(i) => Some(i.file_count()),
101        }
102    }
103
104    pub fn edge_count(&self) -> Option<usize> {
105        match self {
106            GraphProvider::PropertyGraph(g) => g.edge_count().ok(),
107            GraphProvider::GraphIndex(i) => Some(i.edge_count()),
108        }
109    }
110
111    pub fn dependencies(&self, file_path: &str) -> Vec<String> {
112        match self {
113            GraphProvider::PropertyGraph(g) => g.dependencies(file_path).unwrap_or_default(),
114            GraphProvider::GraphIndex(i) => i
115                .edges
116                .iter()
117                .filter(|e| e.kind == "import" && e.from == file_path)
118                .map(|e| e.to.clone())
119                .collect(),
120        }
121    }
122
123    pub fn dependents(&self, file_path: &str) -> Vec<String> {
124        match self {
125            GraphProvider::PropertyGraph(g) => g.dependents(file_path).unwrap_or_default(),
126            GraphProvider::GraphIndex(i) => i
127                .edges
128                .iter()
129                .filter(|e| e.kind == "import" && e.to == file_path)
130                .map(|e| e.from.clone())
131                .collect(),
132        }
133    }
134
135    pub fn related(&self, file_path: &str, depth: usize) -> Vec<String> {
136        match self {
137            GraphProvider::PropertyGraph(g) => g
138                .impact_analysis(file_path, depth)
139                .map(|r| r.affected_files)
140                .unwrap_or_default(),
141            GraphProvider::GraphIndex(i) => i.get_related(file_path, depth),
142        }
143    }
144
145    pub fn file_paths(&self) -> Vec<String> {
146        match self {
147            GraphProvider::PropertyGraph(g) => g.file_catalog_paths().unwrap_or_default(),
148            GraphProvider::GraphIndex(i) => {
149                let mut paths: Vec<String> = i.files.keys().cloned().collect();
150                paths.sort();
151                paths
152            }
153        }
154    }
155
156    pub fn file_count(&self) -> usize {
157        match self {
158            GraphProvider::PropertyGraph(g) => g.file_catalog_count().unwrap_or(0),
159            GraphProvider::GraphIndex(i) => i.files.len(),
160        }
161    }
162
163    pub fn symbol_count(&self) -> usize {
164        match self {
165            GraphProvider::PropertyGraph(g) => g.symbol_count().unwrap_or(0),
166            GraphProvider::GraphIndex(i) => i.symbols.len(),
167        }
168    }
169
170    pub fn find_symbols(
171        &self,
172        name: &str,
173        file_filter: Option<&str>,
174        kind_filter: Option<&str>,
175    ) -> Vec<SymbolInfo> {
176        match self {
177            GraphProvider::PropertyGraph(g) => g
178                // Kind is filtered AFTER mapping, not in SQL: the PG `nodes.kind`
179                // column is the coarse `NodeKind` (every code symbol is `"symbol"`),
180                // while the precise source kind (`struct`, `fn`, …) lives in metadata
181                // and is recovered by `symbol_info_from_node`. Passing `kind_filter`
182                // to the SQL query matched it against `"symbol"` and dropped every
183                // hit — an exported struct queried with kind="struct" came back empty
184                // (#889). ponytail: the SQL LIMIT 100 caps candidates pre-kind-filter,
185                // fine until a name substring has >100 cross-kind matches.
186                .find_symbols(name, file_filter, None)
187                .unwrap_or_default()
188                .into_iter()
189                .map(symbol_info_from_node)
190                .filter(|s| kind_filter.is_none_or(|k| s.kind == k))
191                .collect(),
192            GraphProvider::GraphIndex(i) => {
193                let name_lower = name.to_lowercase();
194                i.symbols
195                    .values()
196                    .filter(|s| s.name.to_lowercase().contains(&name_lower))
197                    .filter(|s| file_filter.is_none_or(|f| s.file.contains(f)))
198                    .filter(|s| kind_filter.is_none_or(|k| s.kind == k))
199                    .take(100)
200                    .map(|s| SymbolInfo {
201                        name: s.name.clone(),
202                        file: s.file.clone(),
203                        kind: s.kind.clone(),
204                        start_line: s.start_line,
205                        end_line: s.end_line,
206                        is_exported: s.is_exported,
207                    })
208                    .collect()
209            }
210        }
211    }
212
213    /// Every symbol with its file + line span (unfiltered). Backend-agnostic
214    /// equivalent of iterating `ProjectIndex::symbols` — used by the call-graph
215    /// builder to attribute call sites to their enclosing symbol.
216    pub fn all_symbols(&self) -> Vec<SymbolInfo> {
217        match self {
218            GraphProvider::PropertyGraph(g) => g
219                .all_symbols()
220                .unwrap_or_default()
221                .into_iter()
222                .map(symbol_info_from_node)
223                .collect(),
224            GraphProvider::GraphIndex(i) => i
225                .symbols
226                .values()
227                .map(|s| SymbolInfo {
228                    name: s.name.clone(),
229                    file: s.file.clone(),
230                    kind: s.kind.clone(),
231                    start_line: s.start_line,
232                    end_line: s.end_line,
233                    is_exported: s.is_exported,
234                })
235                .collect(),
236        }
237    }
238
239    pub fn get_symbol(&self, key: &str) -> Option<SymbolInfo> {
240        match self {
241            GraphProvider::PropertyGraph(g) => {
242                // Keys are `rel_path::sym_name` (graph_index, see `mod.rs`). A
243                // file path never contains `::`, but a symbol name does for trait
244                // impls (`std::fmt::Display for T`). Split on the FIRST `::` so
245                // those names round-trip — `rsplitn` mangled them (#682.3).
246                let parts: Vec<&str> = key.splitn(2, "::").collect();
247                if parts.len() != 2 {
248                    return None;
249                }
250                let (file_path, sym_name) = (parts[0], parts[1]);
251                g.get_node_by_symbol(sym_name, file_path)
252                    .ok()
253                    .flatten()
254                    .map(symbol_info_from_node)
255            }
256            GraphProvider::GraphIndex(i) => i.get_symbol(key).map(|s| SymbolInfo {
257                name: s.name.clone(),
258                file: s.file.clone(),
259                kind: s.kind.clone(),
260                start_line: s.start_line,
261                end_line: s.end_line,
262                is_exported: s.is_exported,
263            }),
264        }
265    }
266
267    /// Resolve a stable `SymbolHandle` to
268    /// its current [`SymbolInfo`], robust to line drift. Resolution order:
269    ///
270    /// 1. Exact `(path, name)` — the unique `{file}::{name}` index key, so the
271    ///    common case is a single `O(1)` lookup that ignores the `@Lline` hint
272    ///    entirely (the symbol may have moved since the handle was emitted).
273    /// 2. Otherwise, same-file candidates whose name matches exactly or by its
274    ///    unqualified tail (`Config::load` ↔ `load`), ranked by exact-name
275    ///    first, then nearest line to the handle hint, then lowest line, then
276    ///    name — a total, deterministic order (#498).
277    ///
278    /// Returns `None` only when no symbol in that file plausibly matches. The
279    /// `@Lline` is never a hard requirement, so this is strictly more robust
280    /// than a brittle line-only reference.
281    pub fn find_symbol_by_handle(
282        &self,
283        handle: &crate::core::handle::SymbolHandle,
284    ) -> Option<SymbolInfo> {
285        let key = format!("{}::{}", handle.path, handle.name);
286        if let Some(sym) = self.get_symbol(&key) {
287            return Some(sym);
288        }
289
290        let tail = handle
291            .name
292            .rsplit("::")
293            .next()
294            .unwrap_or(handle.name.as_str());
295        let mut candidates: Vec<SymbolInfo> = self
296            .all_symbols()
297            .into_iter()
298            .filter(|s| s.file == handle.path)
299            .filter(|s| s.name == handle.name || s.name.rsplit("::").next() == Some(tail))
300            .collect();
301        if candidates.is_empty() {
302            return None;
303        }
304        candidates.sort_by(|a, b| {
305            let exact_a = u8::from(a.name != handle.name);
306            let exact_b = u8::from(b.name != handle.name);
307            exact_a
308                .cmp(&exact_b)
309                .then_with(|| {
310                    line_distance(a.start_line, handle.line)
311                        .cmp(&line_distance(b.start_line, handle.line))
312                })
313                .then_with(|| a.start_line.cmp(&b.start_line))
314                .then_with(|| a.name.cmp(&b.name))
315        });
316        candidates.into_iter().next()
317    }
318
319    pub fn edges(&self) -> Vec<EdgeInfo> {
320        match self {
321            // Normalize the raw property-graph edge-kind vocabulary back to the
322            // graph_index vocabulary every consumer speaks (notably `imports` →
323            // `import`, queried by impact/overview via `edges_by_kind("import")`).
324            // Without this the facade leaks `EdgeKind::as_str()` plurals and PG
325            // vs legacy backends would answer the same query differently (#696).
326            GraphProvider::PropertyGraph(g) => g
327                .all_edges_flat()
328                .unwrap_or_default()
329                .into_iter()
330                .map(|(from, to, kind, weight)| EdgeInfo {
331                    from,
332                    to,
333                    kind: index_edge_kind(&kind),
334                    weight,
335                })
336                .collect(),
337            GraphProvider::GraphIndex(i) => i
338                .edges
339                .iter()
340                .map(|e| EdgeInfo {
341                    from: e.from.clone(),
342                    to: e.to.clone(),
343                    kind: e.kind.clone(),
344                    weight: e.weight as f64,
345                })
346                .collect(),
347        }
348    }
349
350    pub fn edges_by_kind(&self, kind: &str) -> Vec<EdgeInfo> {
351        self.edges()
352            .into_iter()
353            .filter(|e| e.kind == kind)
354            .collect()
355    }
356
357    /// Every catalogued file as [`FileInfo`]. Backend-agnostic equivalent of
358    /// iterating `ProjectIndex::files` — used by stats/bootstrap consumers that
359    /// need per-file language + token counts, not just paths.
360    pub fn file_entries(&self) -> Vec<FileInfo> {
361        match self {
362            GraphProvider::PropertyGraph(_) => self
363                .file_paths()
364                .into_iter()
365                .filter_map(|p| self.get_file_entry(&p))
366                .collect(),
367            GraphProvider::GraphIndex(i) => i
368                .files
369                .values()
370                .map(|e| FileInfo {
371                    path: e.path.clone(),
372                    hash: e.hash.clone(),
373                    language: e.language.clone(),
374                    line_count: e.line_count,
375                    token_count: e.token_count,
376                    exports: e.exports.clone(),
377                    summary: e.summary.clone(),
378                })
379                .collect(),
380        }
381    }
382
383    pub fn get_file_entry(&self, path: &str) -> Option<FileInfo> {
384        match self {
385            GraphProvider::PropertyGraph(g) => {
386                g.get_file_catalog(path).ok().flatten().map(|e| FileInfo {
387                    path: e.path,
388                    hash: e.hash,
389                    language: e.language,
390                    line_count: e.line_count,
391                    token_count: e.token_count,
392                    exports: e.exports,
393                    summary: e.summary,
394                })
395            }
396            GraphProvider::GraphIndex(i) => i.files.get(path).map(|e| FileInfo {
397                path: e.path.clone(),
398                hash: e.hash.clone(),
399                language: e.language.clone(),
400                line_count: e.line_count,
401                token_count: e.token_count,
402                exports: e.exports.clone(),
403                summary: e.summary.clone(),
404            }),
405        }
406    }
407
408    pub fn last_scan(&self) -> String {
409        match self {
410            GraphProvider::PropertyGraph(_) => String::new(),
411            GraphProvider::GraphIndex(i) => i.last_scan.clone(),
412        }
413    }
414
415    /// Reconstruct a full [`ProjectIndex`] from this provider — the inverse of
416    /// the graph_index→PG mirror
417    /// ([`populate_from_project_index`](super::property_graph::populate_from_project_index)).
418    /// Lets the
419    /// remaining legacy `ProjectIndex` consumers be sourced from the
420    /// PropertyGraph (parity-proven lossless, #682.3) so the redundant JSON
421    /// store can be retired (#696 phase C). For the GraphIndex backend it clones
422    /// the index it already holds.
423    pub fn materialize_project_index(&self, project_root: &str) -> ProjectIndex {
424        if let GraphProvider::GraphIndex(i) = self {
425            return i.clone();
426        }
427        let mut idx = ProjectIndex::new(project_root);
428        // Stamp `last_scan` from the graph's build time (graph.meta.json) so the
429        // TTL staleness check reflects the real build age, not this
430        // materialization moment (#696 C4). Content-based staleness still keys
431        // off the meta file's mtime independently.
432        if let Some(meta) = super::property_graph::load_meta(project_root)
433            && let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&meta.built_at)
434        {
435            idx.last_scan = dt
436                .with_timezone(&chrono::Local)
437                .format("%Y-%m-%d %H:%M:%S")
438                .to_string();
439        }
440        for f in self.file_entries() {
441            idx.files.insert(
442                f.path.clone(),
443                graph_index::FileEntry {
444                    path: f.path,
445                    hash: f.hash,
446                    language: f.language,
447                    line_count: f.line_count,
448                    token_count: f.token_count,
449                    exports: f.exports,
450                    summary: f.summary,
451                },
452            );
453        }
454        for s in self.all_symbols() {
455            let key = format!("{}::{}", s.file, s.name);
456            idx.symbols.insert(
457                key,
458                graph_index::SymbolEntry {
459                    file: s.file,
460                    name: s.name,
461                    kind: s.kind,
462                    start_line: s.start_line,
463                    end_line: s.end_line,
464                    is_exported: s.is_exported,
465                },
466            );
467        }
468        for e in self.edges() {
469            // `edges()` already normalizes PG kinds to the graph_index
470            // vocabulary, so `e.kind` is ready to store verbatim.
471            idx.edges.push(graph_index::IndexEdge {
472                from: e.from,
473                to: e.to,
474                kind: e.kind,
475                weight: e.weight as f32,
476            });
477        }
478        idx.rebuild_interner();
479        idx
480    }
481
482    pub fn index_dir(project_root: &str) -> Option<std::path::PathBuf> {
483        graph_index::ProjectIndex::index_dir(project_root)
484    }
485
486    /// Scored related files using multi-edge weights.
487    /// Falls back to unscored deps/dependents for GraphIndex backend.
488    pub fn related_files_scored(&self, file_path: &str, limit: usize) -> Vec<(String, f64)> {
489        match self {
490            GraphProvider::PropertyGraph(g) => {
491                g.related_files(file_path, limit).unwrap_or_default()
492            }
493            GraphProvider::GraphIndex(_) => {
494                let mut result: Vec<(String, f64)> = Vec::new();
495                for dep in self.dependencies(file_path) {
496                    result.push((dep, 1.0));
497                }
498                for dep in self.dependents(file_path) {
499                    if !result.iter().any(|(p, _)| *p == dep) {
500                        result.push((dep, 0.5));
501                    }
502                }
503                result.truncate(limit);
504                result
505            }
506        }
507    }
508}
509
510/// Open whichever graph is already populated on disk, **without** triggering any
511/// build, plus a flag telling the caller the property graph still wants a
512/// (re)build. Prefers a fully-populated PropertyGraph and falls back to the
513/// in-memory graph_index extractor while the PG is not yet populated (first run
514/// or just after a rebuild), flagging `needs_build` so the caller can warm the
515/// PG for the next call (#696 phase D: the `legacy` backend escape hatch was
516/// retired once PG-only persistence proved lossless in #682.3).
517fn open_existing(project_root: &str) -> (Option<OpenGraphProvider>, bool) {
518    let t0 = std::time::Instant::now();
519
520    let mut pg_provider = None;
521    let mut pg_populated = false;
522    // A graph built by an older engine may hold edges the current engine no
523    // longer derives (e.g. guessed `calls`, engine 6): never serve it — fall
524    // back to the index extractor and let the flagged rebuild replace it.
525    let pg_current = !crate::core::property_graph::engine_outdated(project_root);
526    if pg_current && let Ok(pg) = CodeGraph::open(project_root) {
527        let nodes = pg.node_count().unwrap_or(0);
528        let edges = pg.edge_count().unwrap_or(0);
529        let file_cat = pg.file_catalog_count().unwrap_or(0);
530        pg_populated = nodes > 0 && edges > 0 && file_cat > 0;
531        if pg_populated {
532            log_source_selection(GraphProviderSource::PropertyGraph, nodes, edges, t0);
533            return (
534                Some(OpenGraphProvider {
535                    source: GraphProviderSource::PropertyGraph,
536                    provider: GraphProvider::PropertyGraph(pg),
537                }),
538                false,
539            );
540        }
541        if nodes > 0 && file_cat > 0 {
542            pg_provider = Some(pg);
543        }
544    }
545
546    // PG is not fully populated: a (re)build would help the next call.
547    let needs_build = !pg_populated;
548
549    if let Some(idx) = super::index_orchestrator::try_load_graph_index(project_root) {
550        let files = idx.files.len();
551        let edges = idx.edges.len();
552        if !idx.edges.is_empty() || !idx.files.is_empty() {
553            log_source_selection(GraphProviderSource::GraphIndex, files, edges, t0);
554            return (
555                Some(OpenGraphProvider {
556                    source: GraphProviderSource::GraphIndex,
557                    provider: GraphProvider::GraphIndex(idx),
558                }),
559                needs_build,
560            );
561        }
562    }
563
564    if let Some(pg) = pg_provider {
565        let nodes = pg.node_count().unwrap_or(0);
566        log_source_selection(GraphProviderSource::PropertyGraph, nodes, 0, t0);
567        return (
568            Some(OpenGraphProvider {
569                source: GraphProviderSource::PropertyGraph,
570                provider: GraphProvider::PropertyGraph(pg),
571            }),
572            needs_build,
573        );
574    }
575
576    (None, needs_build)
577}
578
579/// Open an already-built graph, kicking off a one-shot background build when the
580/// property graph is not fully populated so the *next* call is fast. Returns
581/// `None` on this call when nothing is ready yet. Best-effort callers
582/// (dashboards, context gate, stats, `ctx_graph`) use this; callers that need a
583/// graph *right now* use [`open_or_build`], which builds synchronously instead.
584pub fn open_best_effort(project_root: &str) -> Option<OpenGraphProvider> {
585    let (existing, needs_build) = open_existing(project_root);
586    if needs_build {
587        trigger_lazy_graph_build(project_root);
588    }
589    existing
590}
591
592fn log_source_selection(
593    source: GraphProviderSource,
594    nodes: usize,
595    edges: usize,
596    start: std::time::Instant,
597) {
598    let elapsed_ms = start.elapsed().as_millis();
599    if std::env::var("LCTX_DEBUG").is_ok() {
600        eprintln!(
601            "[graph_provider] source={source:?} nodes={nodes} edges={edges} resolve_ms={elapsed_ms}"
602        );
603    }
604    let _ = (source, nodes, edges, elapsed_ms);
605}
606
607/// Triggers a background graph build once per process when the graph is empty.
608fn trigger_lazy_graph_build(project_root: &str) {
609    // Unit tests rewrite the process-global `LEAN_CTX_DATA_DIR` per test (each uses
610    // its own tempdir). A detached, fire-and-forget build thread reads that global
611    // mid-flight and runs concurrently with test bodies that are otherwise
612    // serialized on `test_env_lock` — a source of graph-state concurrency, and the
613    // root of an intermittent macOS-only flake where a freshly-built index appeared
614    // empty to the asserting test. `open_or_build` has a synchronous fallback that
615    // fully covers tests, so skip the background build under `cfg!(test)`. Production
616    // (and integration tests, which run the lib normally) are unaffected.
617    if cfg!(test) {
618        return;
619    }
620    // Preserve the cheap post-trigger fast path, but do not claim the latch
621    // until the root has been validated as an actual project.
622    if GRAPH_BUILD_TRIGGERED.load(Ordering::SeqCst) {
623        return;
624    }
625    let root = Path::new(project_root);
626    // Both probes are TCC-guarded (#356): a non-existent/non-dir path has no
627    // markers, and a launchd-standalone process never stats under ~/Documents.
628    let is_project = crate::core::pathutil::has_project_marker(root)
629        || crate::core::pathutil::has_multi_repo_children(root);
630    if !is_project {
631        return;
632    }
633    if GRAPH_BUILD_TRIGGERED.swap(true, Ordering::SeqCst) {
634        return;
635    }
636    // #682.2: build via the same reliable worker that builds the JSON index
637    // (which now mirrors into PG, backend-gated), instead of a dedicated
638    // fire-and-forget thread that silently died in short-lived processes.
639    super::index_orchestrator::ensure_all_background(project_root);
640}
641
642/// Build the property graph from the proven graph_index extractor (#682.1).
643///
644/// Loads the current [`ProjectIndex`] (or scans if absent) and mirrors it into
645/// the SQLite store — files + `file_catalog`, symbols, and structural edges —
646/// then stamps `graph.meta.json`. Sourcing PG from the mature extractor
647/// guarantees PG ⊇ graph_index (so a later backend flip cannot lose data) and
648/// populates the `file_catalog` that the `pg_populated` gate requires.
649///
650/// Synchronous and self-contained in `core` (no `tools` dependency), so callers
651/// can build reliably without the fire-and-forget caveat of the lazy trigger.
652pub fn build_property_graph(project_root: &str) -> anyhow::Result<()> {
653    let index = super::index_orchestrator::try_load_graph_index(project_root)
654        .filter(|i| !i.files.is_empty())
655        .unwrap_or_else(|| graph_index::scan_with_content_cache(project_root).0);
656    super::property_graph::mirror_index(project_root, &index)
657}
658
659/// Maximum time `open_or_build` will wait for a synchronous graph build before
660/// falling back to "graph unavailable" (#1018). Prevents blocking-pool
661/// exhaustion on large repos with cold indices, especially on Windows with AV.
662const BUILD_TIMEOUT_SECS: u64 = 30;
663
664/// Serialization gate: only one synchronous graph build at a time. Concurrent
665/// callers that cannot acquire the gate return immediately with `None` rather
666/// than queueing (which would exhaust the blocking pool). The background indexer
667/// picks up the build for them asynchronously.
668static BUILD_GATE: std::sync::LazyLock<std::sync::Mutex<()>> =
669    std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
670
671pub fn open_or_build(project_root: &str) -> Option<OpenGraphProvider> {
672    if let (Some(p), _) = open_existing(project_root) {
673        return Some(p);
674    }
675
676    // Tests require the documented byte-stable result even when the parallel
677    // suite is building another fixture. Production remains non-blocking.
678    let _gate = if cfg!(test) {
679        BUILD_GATE
680            .lock()
681            .unwrap_or_else(std::sync::PoisonError::into_inner)
682    } else {
683        let Ok(gate) = BUILD_GATE.try_lock() else {
684            tracing::info!(
685                "open_or_build: another build in progress for {project_root}; returning None"
686            );
687            trigger_lazy_graph_build(project_root);
688            return None;
689        };
690        gate
691    };
692
693    // Run the potentially-slow `load_or_build` under a timeout thread so we
694    // don't block the calling tool handler for unbounded time (#1018).
695    let root_owned = project_root.to_string();
696    let (tx, rx) = std::sync::mpsc::sync_channel(1);
697    std::thread::spawn(move || {
698        let idx = super::graph_index::load_or_build(&root_owned);
699        let _ = tx.send(idx);
700    });
701
702    let timeout = std::time::Duration::from_secs(BUILD_TIMEOUT_SECS);
703    match rx.recv_timeout(timeout) {
704        Ok(idx) if !idx.files.is_empty() => Some(OpenGraphProvider {
705            source: GraphProviderSource::GraphIndex,
706            provider: GraphProvider::GraphIndex(idx),
707        }),
708        Ok(_) => None,
709        Err(_) => {
710            tracing::warn!(
711                "open_or_build: graph build timed out after {BUILD_TIMEOUT_SECS}s for {project_root}; \
712                 triggering background build"
713            );
714            trigger_lazy_graph_build(project_root);
715            None
716        }
717    }
718}
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[test]
724    fn best_effort_prefers_graph_index_when_property_graph_empty() {
725        let _lock = crate::core::data_dir::test_env_lock();
726        let tmp = tempfile::tempdir().expect("tempdir");
727        let data = tmp.path().join("data");
728        std::fs::create_dir_all(&data).expect("mkdir data");
729        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
730
731        let project_root = tmp.path().join("proj");
732        std::fs::create_dir_all(&project_root).expect("mkdir proj");
733        let root = project_root.to_string_lossy().to_string();
734
735        let mut idx = ProjectIndex::new(&root);
736        idx.files.insert(
737            "src/main.rs".to_string(),
738            super::super::graph_index::FileEntry {
739                path: "src/main.rs".to_string(),
740                hash: "h".to_string(),
741                language: "rs".to_string(),
742                line_count: 1,
743                token_count: 1,
744                exports: vec![],
745                summary: String::new(),
746            },
747        );
748        idx.save().expect("save index");
749
750        let open = open_best_effort(&root).expect("open");
751        assert_eq!(open.source, GraphProviderSource::GraphIndex);
752
753        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
754    }
755
756    #[test]
757    fn best_effort_none_when_no_graphs() {
758        let _lock = crate::core::data_dir::test_env_lock();
759        let tmp = tempfile::tempdir().expect("tempdir");
760        let data = tmp.path().join("data");
761        std::fs::create_dir_all(&data).expect("mkdir data");
762        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data.to_string_lossy().to_string());
763
764        let project_root = tmp.path().join("proj");
765        std::fs::create_dir_all(&project_root).expect("mkdir proj");
766        let root = project_root.to_string_lossy().to_string();
767
768        let open = open_best_effort(&root);
769        assert!(open.is_none());
770
771        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
772    }
773
774    fn handle_provider() -> GraphProvider {
775        let mut idx = ProjectIndex::new("/test");
776        for (key, file, name, kind, start, end) in [
777            (
778                "src/lib.rs::Config",
779                "src/lib.rs",
780                "Config",
781                "struct",
782                5usize,
783                20usize,
784            ),
785            (
786                "src/lib.rs::Config::load",
787                "src/lib.rs",
788                "Config::load",
789                "method",
790                22,
791                35,
792            ),
793            ("src/main.rs::main", "src/main.rs", "main", "fn", 1, 10),
794        ] {
795            idx.symbols.insert(
796                key.to_string(),
797                graph_index::SymbolEntry {
798                    file: file.to_string(),
799                    name: name.to_string(),
800                    kind: kind.to_string(),
801                    start_line: start,
802                    end_line: end,
803                    is_exported: true,
804                },
805            );
806        }
807        GraphProvider::GraphIndex(idx)
808    }
809
810    #[test]
811    fn handle_resolves_exact_file_and_name() {
812        let gp = handle_provider();
813        let h = crate::core::handle::SymbolHandle::new("src/lib.rs", "Config::load", 22);
814        let sym = gp.find_symbol_by_handle(&h).expect("resolves");
815        assert_eq!(sym.name, "Config::load");
816        assert_eq!(sym.start_line, 22);
817    }
818
819    #[test]
820    fn handle_resolves_after_line_drift() {
821        // Same (path, name) but a stale, drifted line — must still resolve to
822        // the current symbol at its real line (robust beyond line-only refs).
823        let gp = handle_provider();
824        let h = crate::core::handle::SymbolHandle::new("src/lib.rs", "Config::load", 999);
825        let sym = gp
826            .find_symbol_by_handle(&h)
827            .expect("resolves despite drift");
828        assert_eq!(sym.start_line, 22);
829    }
830
831    #[test]
832    fn handle_resolves_by_unqualified_tail() {
833        // Handle carries only the unqualified tail `load`; the exact key misses,
834        // so the same-file tail match + line tiebreak recovers `Config::load`.
835        let gp = handle_provider();
836        let h = crate::core::handle::SymbolHandle::new("src/lib.rs", "load", 22);
837        let sym = gp.find_symbol_by_handle(&h).expect("resolves by tail");
838        assert_eq!(sym.name, "Config::load");
839    }
840
841    #[test]
842    fn handle_unknown_file_returns_none() {
843        let gp = handle_provider();
844        let h = crate::core::handle::SymbolHandle::new("src/nope.rs", "Config::load", 22);
845        assert!(gp.find_symbol_by_handle(&h).is_none());
846    }
847
848    #[test]
849    fn pg_kind_filter_matches_precise_metadata_kind() {
850        // #889: a PG symbol's coarse `nodes.kind` is always `"symbol"`; the
851        // source kind (`struct`) lives in metadata. Filtering by kind="struct"
852        // must still find it (previously matched the coarse column → empty).
853        use super::super::property_graph::{Node, NodeKind};
854
855        let pg = CodeGraph::open_in_memory().unwrap();
856        pg.upsert_node(
857            &Node::symbol("State", "simplex/simplex.go", NodeKind::Symbol)
858                .with_lines(129, 140)
859                .with_metadata(r#"{"kind":"struct","exported":true}"#),
860        )
861        .unwrap();
862        let gp = GraphProvider::PropertyGraph(pg);
863
864        let hits = gp.find_symbols("State", None, Some("struct"));
865        assert_eq!(
866            hits.len(),
867            1,
868            "kind=struct must resolve the exported struct"
869        );
870        assert_eq!(hits[0].kind, "struct");
871        assert!(hits[0].is_exported);
872
873        // A non-matching kind still filters it out.
874        assert!(gp.find_symbols("State", None, Some("fn")).is_empty());
875    }
876
877    #[test]
878    fn parity_dependencies_both_stores_agree() {
879        use super::super::graph_index::{FileEntry, IndexEdge};
880        use super::super::property_graph::{Edge, EdgeKind, Node};
881
882        let pg = CodeGraph::open_in_memory().unwrap();
883        let a_id = pg.upsert_node(&Node::file("src/a.rs")).unwrap();
884        let b_id = pg.upsert_node(&Node::file("src/b.rs")).unwrap();
885        let c_id = pg.upsert_node(&Node::file("src/c.rs")).unwrap();
886        pg.upsert_edge(&Edge::new(a_id, b_id, EdgeKind::Imports))
887            .unwrap();
888        pg.upsert_edge(&Edge::new(a_id, c_id, EdgeKind::Imports))
889            .unwrap();
890
891        let mut idx = ProjectIndex::new("/test");
892        for name in &["src/a.rs", "src/b.rs", "src/c.rs"] {
893            idx.files.insert(
894                name.to_string(),
895                FileEntry {
896                    path: name.to_string(),
897                    hash: "h".into(),
898                    language: "rs".into(),
899                    line_count: 1,
900                    token_count: 1,
901                    exports: vec![],
902                    summary: String::new(),
903                },
904            );
905        }
906        idx.edges.push(IndexEdge {
907            from: "src/a.rs".into(),
908            to: "src/b.rs".into(),
909            kind: "import".into(),
910            weight: 1.0,
911        });
912        idx.edges.push(IndexEdge {
913            from: "src/a.rs".into(),
914            to: "src/c.rs".into(),
915            kind: "import".into(),
916            weight: 1.0,
917        });
918
919        let pg_deps = GraphProvider::PropertyGraph(pg);
920        let gi_deps = GraphProvider::GraphIndex(idx);
921
922        let mut pg_result = pg_deps.dependencies("src/a.rs");
923        let mut gi_result = gi_deps.dependencies("src/a.rs");
924        pg_result.sort();
925        gi_result.sort();
926
927        assert_eq!(
928            pg_result, gi_result,
929            "Import edges must match between PG and GraphIndex"
930        );
931
932        let mut pg_dependents = pg_deps.dependents("src/b.rs");
933        let mut gi_dependents = gi_deps.dependents("src/b.rs");
934        pg_dependents.sort();
935        gi_dependents.sort();
936        assert_eq!(
937            pg_dependents, gi_dependents,
938            "Dependents must match between PG and GraphIndex"
939        );
940    }
941
942    /// Round-trip guard for #696 C1: graph_index → PG (mirror) → graph_index
943    /// (materialize) must preserve files (full catalog), symbols (incl. the
944    /// precise `kind` + `is_exported`, which live in node metadata) and import
945    /// edges. Proves the PropertyGraph can be the sole source for the remaining
946    /// legacy `ProjectIndex` consumers — the prerequisite for retiring the JSON
947    /// store.
948    #[test]
949    fn materialize_project_index_round_trips_losslessly() {
950        use super::super::graph_index::{FileEntry, IndexEdge, SymbolEntry};
951        use super::super::property_graph::populate_from_project_index;
952
953        let mut a = ProjectIndex::new("/test");
954        a.files.insert(
955            "src/a.rs".to_string(),
956            FileEntry {
957                path: "src/a.rs".to_string(),
958                hash: "hash-a".to_string(),
959                language: "rs".to_string(),
960                line_count: 42,
961                token_count: 137,
962                exports: vec!["Foo".to_string()],
963                summary: "module a".to_string(),
964            },
965        );
966        a.files.insert(
967            "src/b.rs".to_string(),
968            FileEntry {
969                path: "src/b.rs".to_string(),
970                hash: "hash-b".to_string(),
971                language: "rs".to_string(),
972                line_count: 7,
973                token_count: 19,
974                exports: vec![],
975                summary: String::new(),
976            },
977        );
978        // Two symbols with DIFFERENT kinds and export flags — the fields most at
979        // risk of being flattened by the coarse property-graph `NodeKind`.
980        a.symbols.insert(
981            "src/a.rs::Foo".to_string(),
982            SymbolEntry {
983                file: "src/a.rs".to_string(),
984                name: "Foo".to_string(),
985                kind: "struct".to_string(),
986                start_line: 1,
987                end_line: 9,
988                is_exported: true,
989            },
990        );
991        a.symbols.insert(
992            "src/b.rs::helper".to_string(),
993            SymbolEntry {
994                file: "src/b.rs".to_string(),
995                name: "helper".to_string(),
996                kind: "function".to_string(),
997                start_line: 3,
998                end_line: 6,
999                is_exported: false,
1000            },
1001        );
1002        a.edges.push(IndexEdge {
1003            from: "src/b.rs".to_string(),
1004            to: "src/a.rs".to_string(),
1005            kind: "import".to_string(),
1006            weight: 1.0,
1007        });
1008
1009        let pg = CodeGraph::open_in_memory().unwrap();
1010        populate_from_project_index(&pg, &a).unwrap();
1011        let provider = GraphProvider::PropertyGraph(pg);
1012        let b = provider.materialize_project_index("/test");
1013
1014        // Files: inventory + every catalog field survive.
1015        let mut a_files: Vec<&String> = a.files.keys().collect();
1016        let mut b_files: Vec<&String> = b.files.keys().collect();
1017        a_files.sort();
1018        b_files.sort();
1019        assert_eq!(a_files, b_files, "file inventory must round-trip");
1020        for (path, fa) in &a.files {
1021            let fb = b.files.get(path).expect("file present after round trip");
1022            assert_eq!(fa.hash, fb.hash, "hash {path}");
1023            assert_eq!(fa.language, fb.language, "language {path}");
1024            assert_eq!(fa.line_count, fb.line_count, "line_count {path}");
1025            assert_eq!(fa.token_count, fb.token_count, "token_count {path}");
1026            assert_eq!(fa.exports, fb.exports, "exports {path}");
1027            assert_eq!(fa.summary, fb.summary, "summary {path}");
1028        }
1029
1030        // Symbols: keys + spans + the metadata-carried kind/export flag survive.
1031        let mut a_syms: Vec<&String> = a.symbols.keys().collect();
1032        let mut b_syms: Vec<&String> = b.symbols.keys().collect();
1033        a_syms.sort();
1034        b_syms.sort();
1035        assert_eq!(a_syms, b_syms, "symbol table must round-trip");
1036        for (key, sa) in &a.symbols {
1037            let sb = b.symbols.get(key).expect("symbol present after round trip");
1038            assert_eq!(sa.name, sb.name, "name {key}");
1039            assert_eq!(sa.file, sb.file, "file {key}");
1040            assert_eq!(sa.kind, sb.kind, "kind {key}");
1041            assert_eq!(sa.start_line, sb.start_line, "start_line {key}");
1042            assert_eq!(sa.end_line, sb.end_line, "end_line {key}");
1043            assert_eq!(sa.is_exported, sb.is_exported, "is_exported {key}");
1044        }
1045
1046        // Structural edges: the import edge survives (PG may enrich, never lose).
1047        assert!(
1048            b.edges
1049                .iter()
1050                .any(|e| e.from == "src/b.rs" && e.to == "src/a.rs" && e.kind == "import"),
1051            "import edge must round-trip; got {:?}",
1052            b.edges
1053        );
1054    }
1055}