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::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
20/// Normalize a property-graph edge-kind string back to the graph_index spelling
21/// when materializing a [`ProjectIndex`]. The mirror maps graph_index `import` →
22/// `EdgeKind::Imports`, which serializes as the plural `imports`; the legacy
23/// dependency consumers (`graph_index` BFS, the facade's index-backed
24/// `dependencies`/`dependents`, `ctx_graph`) filter on the singular `import`, so
25/// reverse exactly that one rename. All other kinds already share their spelling
26/// across both stores (#696 C1).
27fn index_edge_kind(pg_kind: &str) -> String {
28    match pg_kind {
29        "imports" => "import".to_string(),
30        other => other.to_string(),
31    }
32}
33
34/// Absolute distance from a symbol's `start` line to a handle's hint `line`.
35/// A missing hint contributes zero distance, so handles without an `@Lline`
36/// suffix neither help nor hurt the tiebreak (all candidates rank equal here).
37fn line_distance(start: usize, target: Option<usize>) -> usize {
38    match target {
39        Some(t) => start.abs_diff(t),
40        None => 0,
41    }
42}
43
44/// Convert a property-graph symbol [`Node`] into a backend-agnostic
45/// [`SymbolInfo`], recovering the precise source `kind` and export flag from the
46/// node metadata (the `Node` itself only carries a coarse `NodeKind`). Single
47/// source of truth for the three facade methods that surface PG symbols, so a
48/// materialized `ProjectIndex` is lossless (#696 C1).
49fn 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// One provider lives for one call on the stack; boxing the graph would add an
88// allocation per open and touch every construction site for no gain.
89#[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
100/// The file an edge end names: a file path, or the file of a
101/// `path::symbol` key (a file path never contains `::`).
102fn edge_file(end: &str) -> &str {
103    end.split_once("::").map_or(end, |(file, _)| file)
104}
105
106/// The tool-facing surface. Every file, symbol and edge it returns has passed
107/// the serve-time source check (`property_graph::served`, G04): the property
108/// graph carries its gate for the request that opened it, the index backend
109/// gets one per call. The `*_unchecked` accessors below are the raw store
110/// reads and stay private to this facade.
111impl 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    /// `paths` found for `anchor`: nothing when the anchor itself may not be
134    /// served, otherwise the paths that may.
135    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    /// Files reached from `file_path` within `depth`. The walk itself runs
163    /// over served files only: nothing is reached through a file that is not
164    /// served now (`property_graph::queries::impact_analysis`,
165    /// `ProjectIndex::get_related_served`).
166    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    /// The file graph a computation over the whole graph may use — community
182    /// detection, a ranking: the files served now and the edges between two
183    /// of them, decided by one gate (`GraphGate::ranking_files`; under
184    /// protection a graph too large to decide in full yields nothing).
185    // pub only for lean-ctx-engine-ext; not public API
186    #[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    /// Every symbol with its file + line span (unfiltered by name).
224    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    /// Scored related files using multi-edge weights (unscored deps and
251    /// dependents for the index backend). Only served neighbours are ranked,
252    /// and `limit` is applied after the check: a file that is not served now
253    /// takes no slot from one that is.
254    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    /// [`Self::related_files_scored`] under the caller's request gate: the
260    /// opened property graph carries its own; the index backend has none and
261    /// is decided by the gate the caller creates once per request, so each
262    /// file is decided once and one bound is spent.
263    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                // Kind is filtered AFTER mapping, not in SQL: the PG `nodes.kind`
373                // column is the coarse `NodeKind` (every code symbol is `"symbol"`),
374                // while the precise source kind (`struct`, `fn`, …) lives in metadata
375                // and is recovered by `symbol_info_from_node`. Passing `kind_filter`
376                // to the SQL query matched it against `"symbol"` and dropped every
377                // hit — an exported struct queried with kind="struct" came back empty
378                // (#889). ponytail: the SQL LIMIT 100 caps candidates pre-kind-filter,
379                // fine until a name substring has >100 cross-kind matches.
380                .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                // Same order and cap as the property graph's SQL (path, line):
389                // a cap over hash order would pick a different 100 per process.
390                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    /// Every symbol with its file + line span (unfiltered). Backend-agnostic
420    /// equivalent of iterating `ProjectIndex::symbols` — used by the call-graph
421    /// builder to attribute call sites to their enclosing symbol.
422    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                // Keys are `rel_path::sym_name` (graph_index, see `mod.rs`). A
449                // file path never contains `::`, but a symbol name does for trait
450                // impls (`std::fmt::Display for T`). Split on the FIRST `::` so
451                // those names round-trip — `rsplitn` mangled them (#682.3).
452                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    /// Resolve a stable `SymbolHandle` to
474    /// its current [`SymbolInfo`], robust to line drift. Resolution order:
475    ///
476    /// 1. Exact `(path, name)` — the unique `{file}::{name}` index key, so the
477    ///    common case is a single `O(1)` lookup that ignores the `@Lline` hint
478    ///    entirely (the symbol may have moved since the handle was emitted).
479    /// 2. Otherwise, same-file candidates whose name matches exactly or by its
480    ///    unqualified tail (`Config::load` ↔ `load`), ranked by exact-name
481    ///    first, then nearest line to the handle hint, then lowest line, then
482    ///    name — a total, deterministic order (#498).
483    ///
484    /// Returns `None` only when no symbol in that file plausibly matches. The
485    /// `@Lline` is never a hard requirement, so this is strictly more robust
486    /// than a brittle line-only reference.
487    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            // Normalize the raw property-graph edge-kind vocabulary back to the
528            // graph_index vocabulary every consumer speaks (notably `imports` →
529            // `import`, queried by impact/overview via `edges_by_kind("import")`).
530            // Without this the facade leaks `EdgeKind::as_str()` plurals and PG
531            // vs legacy backends would answer the same query differently (#696).
532            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    /// Every catalogued file as [`FileInfo`]. Backend-agnostic equivalent of
564    /// iterating `ProjectIndex::files` — used by stats/bootstrap consumers that
565    /// need per-file language + token counts, not just paths.
566    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            // The build stamp lives in `graph.meta.json` beside `graph.db`.
620            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    /// Reconstruct a full [`ProjectIndex`] from this provider — the inverse of
631    /// the graph_index→PG mirror
632    /// ([`populate_from_project_index`](super::property_graph::populate_from_project_index)).
633    /// Lets the
634    /// remaining legacy `ProjectIndex` consumers be sourced from the
635    /// PropertyGraph (parity-proven lossless, #682.3) so the redundant JSON
636    /// store can be retired (#696 phase C). For the GraphIndex backend it clones
637    /// the index it already holds.
638    pub fn materialize_project_index(&self, project_root: &str) -> ProjectIndex {
639        if let GraphProvider::GraphIndex(i) = self {
640            // The index it already holds, without what may not be served now.
641            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        // Stamp `last_scan` from the graph's build time (graph.meta.json) so the
656        // TTL staleness check reflects the real build age, not this
657        // materialization moment (#696 C4). Content-based staleness still keys
658        // off the meta file's mtime independently.
659        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            // `edges()` already normalizes PG kinds to the graph_index
694            // vocabulary, so `e.kind` is ready to store verbatim.
695            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
711/// Open whichever graph is already populated on disk, **without** triggering any
712/// build, plus a flag telling the caller the property graph still wants a
713/// (re)build. Prefers a fully-populated PropertyGraph and falls back to the
714/// in-memory graph_index extractor while the PG is not yet populated (first run
715/// or just after a rebuild), flagging `needs_build` so the caller can warm the
716/// PG for the next call (#696 phase D: the `legacy` backend escape hatch was
717/// retired once PG-only persistence proved lossless in #682.3).
718fn 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    // A graph built by an older engine may hold edges the current engine no
724    // longer derives (e.g. guessed `calls`, engine 6): never serve it — fall
725    // back to the index extractor and let the flagged rebuild replace it.
726    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    // PG is not fully populated: a (re)build would help the next call.
748    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
780/// Open an already-built graph, kicking off a one-shot background build when the
781/// property graph is not fully populated so the *next* call is fast. Returns
782/// `None` on this call when nothing is ready yet. Best-effort callers
783/// (dashboards, context gate, stats, `ctx_graph`) use this; callers that need a
784/// graph *right now* use [`open_or_build`], which builds synchronously instead.
785pub 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
793/// Hot-path open for optional enrichment (post-read hints, silent preload):
794/// only a fully populated property graph, opened from SQLite. Never parses the
795/// JSON index and never builds synchronously — when the graph is not ready it
796/// schedules the background build and returns `None`, so the caller simply
797/// skips its optional work. A read must not wait seconds (or a 30 s build) for
798/// a hint it may not even show.
799pub 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        // Nodes and catalog, not edges: a built graph of a project without
804        // imports (a single file) legitimately has none.
805        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
835/// Triggers a background graph build once per process when the graph is empty.
836fn trigger_lazy_graph_build(project_root: &str) {
837    // Unit tests rewrite the process-global `LEAN_CTX_DATA_DIR` per test (each uses
838    // its own tempdir). A detached, fire-and-forget build thread reads that global
839    // mid-flight and runs concurrently with test bodies that are otherwise
840    // serialized on `test_env_lock` — a source of graph-state concurrency, and the
841    // root of an intermittent macOS-only flake where a freshly-built index appeared
842    // empty to the asserting test. `open_or_build` has a synchronous fallback that
843    // fully covers tests, so skip the background build under `cfg!(test)`. Production
844    // (and integration tests, which run the lib normally) are unaffected.
845    if cfg!(test) {
846        return;
847    }
848    // Preserve the cheap post-trigger fast path, but do not claim the latch
849    // until the root has been validated as an actual project.
850    if GRAPH_BUILD_TRIGGERED.load(Ordering::SeqCst) {
851        return;
852    }
853    let root = Path::new(project_root);
854    // Both probes are TCC-guarded (#356): a non-existent/non-dir path has no
855    // markers, and a launchd-standalone process never stats under ~/Documents.
856    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    // #682.2: build via the same reliable worker that builds the JSON index
865    // (which now mirrors into PG, backend-gated), instead of a dedicated
866    // fire-and-forget thread that silently died in short-lived processes.
867    super::index_orchestrator::ensure_all_background(project_root);
868}
869
870/// Build the property graph from the proven graph_index extractor (#682.1).
871///
872/// Loads the current [`ProjectIndex`] (or scans if absent) and mirrors it into
873/// the SQLite store — files + `file_catalog`, symbols, and structural edges —
874/// then stamps `graph.meta.json`. Sourcing PG from the mature extractor
875/// guarantees PG ⊇ graph_index (so a later backend flip cannot lose data) and
876/// populates the `file_catalog` that the `pg_populated` gate requires.
877///
878/// Synchronous and self-contained in `core` (no `tools` dependency), so callers
879/// can build reliably without the fire-and-forget caveat of the lazy trigger.
880pub 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
887/// Maximum time `open_or_build` will wait for a synchronous graph build before
888/// falling back to "graph unavailable" (#1018). Prevents blocking-pool
889/// exhaustion on large repos with cold indices, especially on Windows with AV.
890const BUILD_TIMEOUT_SECS: u64 = 30;
891
892/// Serialization gate: only one synchronous graph build at a time. Concurrent
893/// callers that cannot acquire the gate return immediately with `None` rather
894/// than queueing (which would exhaust the blocking pool). The background indexer
895/// picks up the build for them asynchronously.
896static 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    // Tests require the documented byte-stable result even when the parallel
905    // suite is building another fixture. Production remains non-blocking.
906    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    // Run the potentially-slow `load_or_build` under a timeout thread so we
922    // don't block the calling tool handler for unbounded time (#1018).
923    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        // The index serves a file only while it exists in the project.
963        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        // Same (path, name) but a stale, drifted line — must still resolve to
1054        // the current symbol at its real line (robust beyond line-only refs).
1055        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        // Handle carries only the unqualified tail `load`; the exact key misses,
1066        // so the same-file tail match + line tiebreak recovers `Config::load`.
1067        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        // #889: a PG symbol's coarse `nodes.kind` is always `"symbol"`; the
1083        // source kind (`struct`) lives in metadata. Filtering by kind="struct"
1084        // must still find it (previously matched the coarse column → empty).
1085        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        // A non-matching kind still filters it out.
1106        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    /// Round-trip guard for #696 C1: graph_index → PG (mirror) → graph_index
1176    /// (materialize) must preserve files (full catalog), symbols (incl. the
1177    /// precise `kind` + `is_exported`, which live in node metadata) and import
1178    /// edges. Proves the PropertyGraph can be the sole source for the remaining
1179    /// legacy `ProjectIndex` consumers — the prerequisite for retiring the JSON
1180    /// store.
1181    #[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        // Two symbols with DIFFERENT kinds and export flags — the fields most at
1212        // risk of being flattened by the coarse property-graph `NodeKind`.
1213        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        // Files: inventory + every catalog field survive.
1248        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        // Symbols: keys + spans + the metadata-carried kind/export flag survive.
1264        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        // Structural edges: the import edge survives (PG may enrich, never lose).
1280        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}