Skip to main content

lean_ctx/core/property_graph/
mod.rs

1//! Property Graph Engine — SQLite-backed code knowledge graph.
2//!
3//! Stores nodes (File, Symbol, Module) and edges (imports, calls, defines,
4//! exports) extracted by `deep_queries` + `import_resolver`.  Provides
5//! efficient traversal queries for impact analysis, architecture discovery,
6//! and graph-driven context loading.
7
8mod cross_source;
9mod edge;
10pub mod file_catalog;
11mod meta;
12mod node;
13mod path_id;
14mod queries;
15mod schema;
16pub mod semantic_cache;
17pub(crate) mod served;
18pub mod snapshot;
19mod sync;
20
21pub use edge::{Edge, EdgeKind};
22pub use file_catalog::FileCatalogEntry;
23pub use meta::{PropertyGraphMetaV1, load_meta, meta_path, write_meta};
24pub use node::{Node, NodeKind};
25pub use queries::{
26    DependencyChain, GraphQuery, ImpactResult, Served, edge_weight, file_connectivity,
27    related_files,
28};
29pub use semantic_cache::CachedResolution;
30pub use served::GraphSource;
31pub use sync::{mirror_index, parse_symbol_metadata, populate_from_project_index};
32
33use rusqlite::Connection;
34use std::path::{Path, PathBuf};
35
36/// Resolve the directory for graph.db and graph.meta.json.
37///
38/// Uses `$LEAN_CTX_DATA_DIR/graphs/<project_hash>/` (consistent with
39/// `ProjectIndex::index_dir`).  Falls back to `<project>/.lean-ctx/`
40/// only when the global data directory cannot be resolved.
41pub fn graph_dir(project_root: &str) -> PathBuf {
42    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
43        let normalized = crate::core::graph_index::normalize_project_root(project_root);
44        let hash = crate::core::project_hash::hash_project_root(&normalized);
45        data_dir.join("graphs").join(hash)
46    } else {
47        Path::new(project_root).join(".lean-ctx")
48    }
49}
50
51/// Transparently migrate graph.db and graph.meta.json from the old
52/// per-project `.lean-ctx/` directory to the new `$DATA_DIR/graphs/` path.
53fn migrate_if_needed(project_root: &str, new_dir: &Path) {
54    let old_dir = Path::new(project_root).join(".lean-ctx");
55    if old_dir == new_dir {
56        return;
57    }
58    for file in &["graph.db", "graph.meta.json"] {
59        let old = old_dir.join(file);
60        let new = new_dir.join(file);
61        if old.exists()
62            && !new.exists()
63            && std::fs::rename(&old, &new).is_err()
64            && std::fs::copy(&old, &new).is_ok()
65        {
66            let _ = std::fs::remove_file(&old);
67        }
68    }
69}
70
71/// Property-graph engine generation. Bump whenever edge extraction changes
72/// (e.g. the `type_ref` edges that connect C#/Java same-namespace consumers to
73/// their definers, GH #398) so an existing graph built by an older engine is
74/// transparently rebuilt on the next query instead of being served without the
75/// new edges. Graphs whose `graph.meta.json` predates this stamp deserialize to
76/// engine version `0`, so the first query after an upgrade rebuilds once.
77///
78/// History:
79/// - `2`: `type_ref` edges added to the `ctx_impact` builder (v3.8.3).
80/// - `3`: `type_ref` edges moved into the durable `graph_index` mirror so a
81///   background reindex can no longer wipe the C# blast radius (GH #398); every
82///   graph stamped by an engine that predates the mirror fix must rebuild.
83/// - `4`: same-package `type_ref` edges extended to Go (directory-scoped) and
84///   Kotlin (GH #398 bug class); graphs built before they existed must rebuild.
85/// - `5`: PropertyGraph file paths use interned IDs; pre-ID databases rebuild.
86/// - `6`: `calls` edges carry typed evidence and are no longer guessed (the
87///   `ctx_impact` builder bound ambiguous callees to the alphabetically first
88///   definition); graphs holding unannotated guessed edges must rebuild.
89/// - `7`: `calls` edges bind only within the caller's language family (a Rust
90///   call no longer lands on a same-named shell function); graphs holding
91///   such cross-language edges must rebuild.
92/// - `8`: path calls (`crate::config_io::write(..)`) bind to the file their
93///   own module path names; graphs built without those `calls` edges must
94///   rebuild.
95pub const GRAPH_ENGINE_VERSION: u32 = 8;
96
97/// `true` when the persisted graph was built by another engine generation than
98/// [`GRAPH_ENGINE_VERSION`] — older, NEWER, or before the version stamp existed
99/// (missing or unreadable meta) — and must therefore be rebuilt before its
100/// edges can be trusted. A newer stamp is what an installation finds after a
101/// rollback to an earlier release: that graph holds edges this engine's rules
102/// did not produce and cannot interpret, so it is rebuilt, not read. Callers
103/// pair this with a node-count check: an empty graph is rebuilt regardless; a
104/// non-empty graph of another generation is rebuilt by this gate.
105pub fn engine_outdated(project_root: &str) -> bool {
106    load_meta(project_root).is_none_or(|m| m.engine_version != GRAPH_ENGINE_VERSION)
107}
108
109/// Whether an open error is a transient SQLite lock (BUSY/LOCKED) that a brief
110/// retry can clear — notably the `PRAGMA journal_mode=WAL` and initial-DDL races
111/// that SQLite reports *without* invoking the busy handler (so `busy_timeout`
112/// does not cover them).
113fn is_transient_lock(err: &anyhow::Error) -> bool {
114    use rusqlite::ErrorCode;
115    if let Some(rusqlite::Error::SqliteFailure(e, _)) = err.downcast_ref::<rusqlite::Error>()
116        && matches!(e.code, ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked)
117    {
118        return true;
119    }
120    // The schema initializer may surface the same condition wrapped; match the
121    // full error chain's text as a fallback.
122    let msg = format!("{err:#}").to_ascii_lowercase();
123    msg.contains("database is locked") || msg.contains("table is locked")
124}
125
126pub struct CodeGraph {
127    conn: Connection,
128    db_path: PathBuf,
129    /// Serve-time source check of a graph opened for a project root
130    /// (`served`, G04); `None` for an in-memory graph.
131    gate: Option<served::GraphGate>,
132}
133
134impl CodeGraph {
135    pub fn open(project_root: &str) -> anyhow::Result<Self> {
136        let db_dir = graph_dir(project_root);
137        std::fs::create_dir_all(&db_dir)?;
138        migrate_if_needed(project_root, &db_dir);
139        let db_path = db_dir.join("graph.db");
140
141        // Concurrent opens race on `PRAGMA journal_mode=WAL` and the initial DDL,
142        // which SQLite reports as SQLITE_BUSY without invoking the busy handler
143        // (`busy_timeout` therefore does not apply). Deeper addon integration can
144        // have a gateway ingest thread and the main session's graph build open
145        // the same db at once (#1102); retry briefly so neither silently loses
146        // its writes. Once WAL is recorded in the file header, opens stop racing.
147        const MAX_ATTEMPTS: u32 = 12;
148        let mut attempt = 0;
149        loop {
150            attempt += 1;
151            match Self::try_open(&db_path) {
152                Ok(mut graph) => {
153                    graph.gate = Some(served::GraphGate::for_root(project_root));
154                    return Ok(graph);
155                }
156                Err(e) if attempt < MAX_ATTEMPTS && is_transient_lock(&e) => {
157                    std::thread::sleep(std::time::Duration::from_millis(40 * u64::from(attempt)));
158                }
159                Err(e) => return Err(e),
160            }
161        }
162    }
163
164    /// One open attempt: connect, register the busy handler, ensure the schema.
165    fn try_open(db_path: &Path) -> anyhow::Result<Self> {
166        let conn = Connection::open(db_path)?;
167        conn.busy_timeout(std::time::Duration::from_secs(5))?;
168        schema::initialize(&conn)?;
169        Ok(Self {
170            conn,
171            db_path: db_path.to_path_buf(),
172            gate: None,
173        })
174    }
175
176    pub fn open_in_memory() -> anyhow::Result<Self> {
177        let conn = Connection::open_in_memory()?;
178        schema::initialize(&conn)?;
179        Ok(Self {
180            conn,
181            db_path: PathBuf::from(":memory:"),
182            gate: None,
183        })
184    }
185
186    pub fn db_path(&self) -> &Path {
187        &self.db_path
188    }
189
190    pub fn connection(&self) -> &Connection {
191        &self.conn
192    }
193
194    pub fn upsert_node(&self, node: &Node) -> anyhow::Result<i64> {
195        node::upsert(&self.conn, node)
196    }
197
198    pub fn upsert_edge(&self, edge: &Edge) -> anyhow::Result<()> {
199        edge::upsert(&self.conn, edge)
200    }
201
202    pub fn get_node_by_path(&self, file_path: &str) -> anyhow::Result<Option<Node>> {
203        node::get_by_path(&self.conn, file_path)
204    }
205
206    pub fn get_node_by_symbol(&self, name: &str, file_path: &str) -> anyhow::Result<Option<Node>> {
207        node::get_by_symbol(&self.conn, name, file_path)
208    }
209
210    pub fn remove_file_nodes(&self, file_path: &str) -> anyhow::Result<()> {
211        node::remove_by_file(&self.conn, file_path)
212    }
213
214    pub fn edges_from(&self, node_id: i64) -> anyhow::Result<Vec<Edge>> {
215        edge::from_node(&self.conn, node_id)
216    }
217
218    pub fn edges_to(&self, node_id: i64) -> anyhow::Result<Vec<Edge>> {
219        edge::to_node(&self.conn, node_id)
220    }
221
222    // The five queries below run under this graph's serve-time source check
223    // (`served`, G04): a file that is not served now is neither returned nor
224    // walked through, and contributes no weight, count or rank slot.
225
226    pub fn dependents(&self, file_path: &str) -> anyhow::Result<Vec<String>> {
227        Ok(self.served_neighbours(file_path, queries::dependents(&self.conn, file_path)?))
228    }
229
230    pub fn dependencies(&self, file_path: &str) -> anyhow::Result<Vec<String>> {
231        Ok(self.served_neighbours(file_path, queries::dependencies(&self.conn, file_path)?))
232    }
233
234    pub fn impact_analysis(
235        &self,
236        file_path: &str,
237        max_depth: usize,
238    ) -> anyhow::Result<ImpactResult> {
239        queries::impact_analysis(&self.conn, file_path, max_depth, &|path: &str| {
240            self.serves_file(path)
241        })
242    }
243
244    pub fn dependency_chain(
245        &self,
246        from: &str,
247        to: &str,
248    ) -> anyhow::Result<Option<DependencyChain>> {
249        queries::dependency_chain(&self.conn, from, to, &|path: &str| self.serves_file(path))
250    }
251
252    pub fn related_files(
253        &self,
254        file_path: &str,
255        limit: usize,
256    ) -> anyhow::Result<Vec<(String, f64)>> {
257        queries::related_files(&self.conn, file_path, limit, &|path: &str| {
258            self.serves_file(path)
259        })
260    }
261
262    pub fn file_connectivity(
263        &self,
264        file_path: &str,
265    ) -> anyhow::Result<std::collections::HashMap<String, (usize, usize)>> {
266        queries::file_connectivity(&self.conn, file_path, &|path: &str| self.serves_file(path))
267    }
268
269    pub fn node_count(&self) -> anyhow::Result<usize> {
270        node::count(&self.conn)
271    }
272
273    pub fn edge_count(&self) -> anyhow::Result<usize> {
274        edge::count(&self.conn)
275    }
276
277    /// Cached semantic answer for a call site, if the caller is unchanged and
278    /// every file the answer derives from — the caller and each target — is
279    /// served now (`semantic_cache::lookup_served`, G04). A withheld answer
280    /// is a miss: the backend is asked again.
281    pub fn semantic_lookup(
282        &self,
283        site: semantic_cache::SiteKey<'_>,
284        caller_hash: &str,
285    ) -> anyhow::Result<Option<CachedResolution>> {
286        semantic_cache::lookup_served(&self.conn, site, caller_hash, |file| self.serves_file(file))
287    }
288
289    /// Keeps a semantic answer when its persisted text passes storage
290    /// admission under `admission` — one policy snapshot per enrichment run,
291    /// taken where the run starts, not per row. `Ok(false)`: admission
292    /// refused the row and nothing was written.
293    pub fn semantic_store(
294        &self,
295        site: semantic_cache::SiteKey<'_>,
296        caller_hash: &str,
297        value: &CachedResolution,
298        admission: &crate::core::context_admission::stores::StoreAdmission,
299    ) -> anyhow::Result<bool> {
300        semantic_cache::store_admitted(&self.conn, site, caller_hash, value, admission)
301    }
302
303    /// Whether a semantic backend has answered for this graph at all.
304    pub fn has_semantic_answers(&self) -> anyhow::Result<bool> {
305        semantic_cache::any(&self.conn)
306    }
307
308    /// Removes cached answers for vanished or changed caller files.
309    pub fn semantic_prune(
310        &self,
311        live_hashes: &std::collections::HashMap<String, String>,
312    ) -> anyhow::Result<usize> {
313        semantic_cache::prune(&self.conn, live_hashes)
314    }
315
316    /// File→file edges of `kind` with their metadata, as
317    /// `(source path, target path, metadata)` — sorted for determinism.
318    pub fn file_edges_of_kind(
319        &self,
320        kind: &EdgeKind,
321    ) -> anyhow::Result<Vec<(String, String, Option<String>)>> {
322        edge::file_edges_of_kind(&self.conn, kind)
323    }
324
325    /// Upserts an edge carrying typed evidence. The incoming producer's
326    /// contribution replaces only its own earlier one; other producers'
327    /// contributions on the same edge are kept
328    /// ([`crate::core::semantic::EdgeEvidence::merge`]).
329    pub fn upsert_edge_with_evidence(
330        &self,
331        source_id: i64,
332        target_id: i64,
333        kind: &EdgeKind,
334        evidence: &crate::core::semantic::EdgeEvidence,
335    ) -> anyhow::Result<()> {
336        use crate::core::semantic::EdgeEvidence;
337        self.atomically(|| {
338            let existing = edge::metadata_of(&self.conn, source_id, target_id, kind)?;
339            let merged = EdgeEvidence::merge(
340                EdgeEvidence::from_metadata(existing.as_deref()),
341                evidence.clone(),
342            );
343            edge::upsert(
344                &self.conn,
345                &Edge::new(source_id, target_id, kind.clone()).with_metadata(&merged.to_metadata()),
346            )
347        })
348    }
349
350    /// Runs a read-modify-write as one unit. Another process (daemon vs. MCP
351    /// server) may update the same edge concurrently; `BEGIN IMMEDIATE` takes
352    /// the write lock before the read, so no contribution is lost. Inside an
353    /// outer transaction that one already provides atomicity.
354    fn atomically<T>(&self, f: impl FnOnce() -> anyhow::Result<T>) -> anyhow::Result<T> {
355        if !self.conn.is_autocommit() {
356            return f();
357        }
358        self.conn.execute_batch("BEGIN IMMEDIATE")?;
359        let outcome = f().and_then(|value| {
360            self.conn.execute_batch("COMMIT")?;
361            Ok(value)
362        });
363        // A failed body *or* a failed COMMIT must not leave the connection
364        // inside a transaction: the next call would see !is_autocommit, skip
365        // BEGIN and never commit, while holding the writer lock.
366        if outcome.is_err() && !self.conn.is_autocommit() {
367            let _ = self.conn.execute_batch("ROLLBACK");
368        }
369        outcome
370    }
371
372    /// Withdraws `origin`'s contribution from the file→file edge
373    /// `source → target`: the edge is deleted only when no other producer
374    /// still derives it. Edges without typed evidence are left untouched.
375    pub fn withdraw_file_edge(
376        &self,
377        source: &str,
378        target: &str,
379        kind: &EdgeKind,
380        origin: crate::core::semantic::EvidenceOrigin,
381    ) -> anyhow::Result<()> {
382        use crate::core::semantic::EdgeEvidence;
383        let (Some(s), Some(t)) = (
384            self.get_node_by_path(source)?.and_then(|n| n.id),
385            self.get_node_by_path(target)?.and_then(|n| n.id),
386        ) else {
387            return Ok(());
388        };
389        self.atomically(|| {
390            let existing = edge::metadata_of(&self.conn, s, t, kind)?;
391            let Some(evidence) = EdgeEvidence::from_metadata(existing.as_deref()) else {
392                return Ok(());
393            };
394            if !evidence.has(origin) {
395                return Ok(());
396            }
397            match evidence.without(origin) {
398                Some(rest) => edge::upsert(
399                    &self.conn,
400                    &Edge::new(s, t, kind.clone()).with_metadata(&rest.to_metadata()),
401                ),
402                None => edge::remove_file_edge(&self.conn, source, target, kind),
403            }
404        })
405    }
406
407    /// Persist a cross-source edge (code file ↔ external source URI) into the
408    /// dedicated `cross_source_edges` table. Keeps the higher weight on conflict
409    /// so repeated provider ingests don't downgrade an established link (#682).
410    pub fn upsert_cross_source_edge(
411        &self,
412        from: &str,
413        to: &str,
414        kind: &str,
415        weight: f32,
416    ) -> anyhow::Result<()> {
417        cross_source::upsert(&self.conn, from, to, kind, weight)
418    }
419
420    /// All cross-source edges as `IndexEdge`s, ready for `cross_source_hints`.
421    pub fn all_cross_source_edges(&self) -> Vec<crate::core::graph_index::IndexEdge> {
422        cross_source::all(&self.conn).unwrap_or_default()
423    }
424
425    pub fn cross_source_edge_count(&self) -> anyhow::Result<usize> {
426        cross_source::count(&self.conn)
427    }
428
429    /// Delete every cross-source edge of a given `kind`. Used by the code-health
430    /// fabric to replace its `health_hotspot` edges on each pass so resolved
431    /// hotspots never persist as stale hints. Returns the number removed.
432    pub fn delete_cross_source_edges_by_kind(&self, kind: &str) -> anyhow::Result<usize> {
433        cross_source::delete_by_kind(&self.conn, kind)
434    }
435
436    pub fn clear(&self) -> anyhow::Result<()> {
437        self.conn.execute_batch(
438            "DELETE FROM edges; DELETE FROM nodes; DELETE FROM file_catalog; DELETE FROM paths; \
439             DELETE FROM cross_source_edges;",
440        )?;
441        Ok(())
442    }
443
444    /// Clear only the code graph (nodes, edges, file catalog), preserving
445    /// provider `cross_source_edges`. Used by the graph_index→PG mirror (#682.1)
446    /// so rebuilding the code graph never drops lateral provider hints, which
447    /// live in their own table and are repopulated on a separate ingest cycle.
448    pub fn clear_code_graph(&self) -> anyhow::Result<()> {
449        self.conn.execute_batch(
450            "DELETE FROM edges; DELETE FROM nodes; DELETE FROM file_catalog; DELETE FROM paths;",
451        )?;
452        Ok(())
453    }
454
455    pub fn upsert_file_catalog(&self, entry: &FileCatalogEntry) -> anyhow::Result<()> {
456        file_catalog::upsert(&self.conn, entry)
457    }
458
459    pub fn get_file_catalog(&self, path: &str) -> anyhow::Result<Option<FileCatalogEntry>> {
460        file_catalog::get(&self.conn, path)
461    }
462
463    pub fn file_catalog_count(&self) -> anyhow::Result<usize> {
464        file_catalog::count(&self.conn)
465    }
466
467    pub fn file_catalog_paths(&self) -> anyhow::Result<Vec<String>> {
468        file_catalog::all_paths(&self.conn)
469    }
470
471    pub fn find_symbols(
472        &self,
473        name: &str,
474        file_filter: Option<&str>,
475        kind_filter: Option<&str>,
476    ) -> anyhow::Result<Vec<Node>> {
477        node::find_symbols(&self.conn, name, file_filter, kind_filter)
478    }
479
480    /// Files that define a symbol named exactly `name` (GH #398 symbol-name
481    /// `ctx_impact analyze` fallback). Backed by `node::resolve_symbol_def_files`.
482    pub fn resolve_symbol_def_files(&self, name: &str) -> anyhow::Result<Vec<String>> {
483        node::resolve_symbol_def_files(&self.conn, name)
484    }
485
486    pub fn symbol_count(&self) -> anyhow::Result<usize> {
487        node::symbol_count(&self.conn)
488    }
489
490    /// Count of `file` nodes (accurate on both builder paths). Backed by
491    /// `node::file_count`.
492    pub fn file_node_count(&self) -> anyhow::Result<usize> {
493        node::file_count(&self.conn)
494    }
495
496    /// Every symbol node with its line span (unfiltered). Backend for the
497    /// call-graph symbol table after the `graph_index` teardown (#696).
498    pub fn all_symbols(&self) -> anyhow::Result<Vec<Node>> {
499        node::all_symbols(&self.conn)
500    }
501
502    pub fn all_edges_flat(&self) -> anyhow::Result<Vec<(String, String, String, f64)>> {
503        node::all_edges_flat(&self.conn)
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510    use crate::core::data_dir::test_env_lock;
511
512    fn test_graph() -> CodeGraph {
513        CodeGraph::open_in_memory().unwrap()
514    }
515
516    #[test]
517    fn create_and_query_nodes() {
518        let g = test_graph();
519
520        let id = g.upsert_node(&Node::file("src/main.rs")).unwrap();
521        assert!(id > 0);
522
523        let found = g.get_node_by_path("src/main.rs").unwrap();
524        assert!(found.is_some());
525        assert_eq!(found.unwrap().file_path, "src/main.rs");
526    }
527
528    #[test]
529    fn create_and_query_edges() {
530        let g = test_graph();
531
532        let a = g.upsert_node(&Node::file("src/a.rs")).unwrap();
533        let b = g.upsert_node(&Node::file("src/b.rs")).unwrap();
534
535        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
536
537        let from_a = g.edges_from(a).unwrap();
538        assert_eq!(from_a.len(), 1);
539        assert_eq!(from_a[0].target_id, b);
540
541        let to_b = g.edges_to(b).unwrap();
542        assert_eq!(to_b.len(), 1);
543        assert_eq!(to_b[0].source_id, a);
544    }
545
546    #[test]
547    fn dependents_query() {
548        let g = test_graph();
549
550        let main = g.upsert_node(&Node::file("src/main.rs")).unwrap();
551        let lib = g.upsert_node(&Node::file("src/lib.rs")).unwrap();
552        let utils = g.upsert_node(&Node::file("src/utils.rs")).unwrap();
553
554        g.upsert_edge(&Edge::new(main, lib, EdgeKind::Imports))
555            .unwrap();
556        g.upsert_edge(&Edge::new(utils, lib, EdgeKind::Imports))
557            .unwrap();
558
559        let deps = g.dependents("src/lib.rs").unwrap();
560        assert_eq!(deps.len(), 2);
561        assert!(deps.contains(&"src/main.rs".to_string()));
562        assert!(deps.contains(&"src/utils.rs".to_string()));
563    }
564
565    #[test]
566    fn dependencies_query() {
567        let g = test_graph();
568
569        let main = g.upsert_node(&Node::file("src/main.rs")).unwrap();
570        let lib = g.upsert_node(&Node::file("src/lib.rs")).unwrap();
571        let config = g.upsert_node(&Node::file("src/config.rs")).unwrap();
572
573        g.upsert_edge(&Edge::new(main, lib, EdgeKind::Imports))
574            .unwrap();
575        g.upsert_edge(&Edge::new(main, config, EdgeKind::Imports))
576            .unwrap();
577
578        let deps = g.dependencies("src/main.rs").unwrap();
579        assert_eq!(deps.len(), 2);
580    }
581
582    #[test]
583    #[allow(clippy::many_single_char_names)] // graph test nodes: a, b, c, d, e
584    fn impact_analysis_depth() {
585        let g = test_graph();
586
587        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
588        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
589        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
590        let d = g.upsert_node(&Node::file("d.rs")).unwrap();
591
592        g.upsert_edge(&Edge::new(b, a, EdgeKind::Imports)).unwrap();
593        g.upsert_edge(&Edge::new(c, b, EdgeKind::Imports)).unwrap();
594        g.upsert_edge(&Edge::new(d, c, EdgeKind::Imports)).unwrap();
595
596        let impact = g.impact_analysis("a.rs", 2).unwrap();
597        assert!(impact.affected_files.contains(&"b.rs".to_string()));
598        assert!(impact.affected_files.contains(&"c.rs".to_string()));
599        assert!(!impact.affected_files.contains(&"d.rs".to_string()));
600
601        let deep = g.impact_analysis("a.rs", 10).unwrap();
602        assert!(deep.affected_files.contains(&"d.rs".to_string()));
603    }
604
605    /// Weighted propagation is exact and separates name-match-only reach:
606    /// a heavier path found later still propagates, and a guess on a pair
607    /// never lends its weight to that pair's evidence-backed edge.
608    #[test]
609    #[allow(clippy::many_single_char_names)] // graph test nodes
610    fn impact_propagates_the_heaviest_path_and_marks_guess_only_reach() {
611        use crate::core::semantic::{EdgeEvidence, EvidenceGrade, EvidenceOrigin};
612        let g = test_graph();
613        let id = |p: &str| g.upsert_node(&Node::file(p)).unwrap();
614        let (a, b, c, x, y, z) = (id("a"), id("b"), id("c"), id("x"), id("y"), id("z"));
615        let edge = |from, to, kind| g.upsert_edge(&Edge::new(from, to, kind)).unwrap();
616        // b → a: a name-match call guess (0.8 × 0.5 = 0.4) plus a fact
617        // (sibling, 0.25); c → b: co-change (0.35). Over all edges c gets
618        // 0.4 × 0.35 = 0.14, over facts only 0.25 × 0.35 < 0.1.
619        let guess = EdgeEvidence::new(
620            EvidenceGrade::HeuristicStructural,
621            EvidenceOrigin::Enrichment,
622            None,
623            1,
624        );
625        g.upsert_edge_with_evidence(b, a, &EdgeKind::Calls, &guess)
626            .unwrap();
627        edge(b, a, EdgeKind::Sibling);
628        edge(c, b, EdgeKind::Cochange);
629        // x is first reached lightly (sibling, 0.25), then fully via y at
630        // depth 2; only the full weight carries on to z (0.35).
631        edge(x, a, EdgeKind::Sibling);
632        edge(y, a, EdgeKind::Imports);
633        edge(x, y, EdgeKind::Imports);
634        edge(z, x, EdgeKind::Cochange);
635
636        let impact = g.impact_analysis("a", 5).unwrap();
637        assert_eq!(impact.affected_files, ["b", "c", "x", "y", "z"]);
638        assert_eq!(impact.weak_files, ["c"]);
639        assert_eq!(impact.max_depth_reached, 3);
640    }
641
642    #[test]
643    fn upsert_idempotent() {
644        let g = test_graph();
645
646        let id1 = g.upsert_node(&Node::file("src/main.rs")).unwrap();
647        let id2 = g.upsert_node(&Node::file("src/main.rs")).unwrap();
648        assert_eq!(id1, id2);
649        assert_eq!(g.node_count().unwrap(), 1);
650    }
651
652    #[test]
653    fn remove_file_cascades() {
654        let g = test_graph();
655
656        let a = g.upsert_node(&Node::file("src/a.rs")).unwrap();
657        let b = g.upsert_node(&Node::file("src/b.rs")).unwrap();
658        let sym = g
659            .upsert_node(&Node::symbol("MyStruct", "src/a.rs", NodeKind::Symbol))
660            .unwrap();
661
662        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
663        g.upsert_edge(&Edge::new(sym, b, EdgeKind::Calls)).unwrap();
664
665        g.remove_file_nodes("src/a.rs").unwrap();
666
667        assert!(g.get_node_by_path("src/a.rs").unwrap().is_none());
668        assert_eq!(g.edge_count().unwrap(), 0);
669    }
670
671    #[test]
672    fn dependency_chain_found() {
673        let g = test_graph();
674
675        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
676        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
677        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
678
679        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
680        g.upsert_edge(&Edge::new(b, c, EdgeKind::Imports)).unwrap();
681
682        let chain = g.dependency_chain("a.rs", "c.rs").unwrap();
683        assert!(chain.is_some());
684        let chain = chain.unwrap();
685        assert_eq!(chain.path, vec!["a.rs", "b.rs", "c.rs"]);
686    }
687
688    #[test]
689    fn counts() {
690        let g = test_graph();
691        assert_eq!(g.node_count().unwrap(), 0);
692        assert_eq!(g.edge_count().unwrap(), 0);
693
694        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
695        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
696        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
697
698        assert_eq!(g.node_count().unwrap(), 2);
699        assert_eq!(g.edge_count().unwrap(), 1);
700    }
701
702    #[test]
703    fn multi_edge_dependents() {
704        let g = test_graph();
705
706        let a = g.upsert_node(&Node::file("src/a.rs")).unwrap();
707        let b = g.upsert_node(&Node::file("src/b.rs")).unwrap();
708        let c = g.upsert_node(&Node::file("src/c.rs")).unwrap();
709
710        g.upsert_edge(&Edge::new(b, a, EdgeKind::Imports)).unwrap();
711        g.upsert_edge(&Edge::new(c, a, EdgeKind::Calls)).unwrap();
712
713        let deps = g.dependents("src/a.rs").unwrap();
714        assert_eq!(deps.len(), 2);
715        assert!(deps.contains(&"src/b.rs".to_string()));
716        assert!(deps.contains(&"src/c.rs".to_string()));
717    }
718
719    #[test]
720    fn multi_edge_impact_analysis() {
721        let g = test_graph();
722
723        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
724        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
725        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
726
727        g.upsert_edge(&Edge::new(b, a, EdgeKind::Imports)).unwrap();
728        g.upsert_edge(&Edge::new(c, b, EdgeKind::Calls)).unwrap();
729
730        let impact = g.impact_analysis("a.rs", 10).unwrap();
731        assert!(impact.affected_files.contains(&"b.rs".to_string()));
732        assert!(impact.affected_files.contains(&"c.rs".to_string()));
733    }
734
735    #[test]
736    fn related_files_scored() {
737        let g = test_graph();
738
739        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
740        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
741        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
742
743        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
744        g.upsert_edge(&Edge::new(a, b, EdgeKind::Calls)).unwrap();
745        g.upsert_edge(&Edge::new(a, c, EdgeKind::TypeRef)).unwrap();
746
747        let related = g.related_files("a.rs", 10).unwrap();
748        assert_eq!(related.len(), 2);
749        let b_score = related.iter().find(|(p, _)| p == "b.rs").unwrap().1;
750        let c_score = related.iter().find(|(p, _)| p == "c.rs").unwrap().1;
751        assert!(
752            b_score > c_score,
753            "b.rs has imports+calls, should rank higher than c.rs with type_ref"
754        );
755    }
756
757    /// The same call relationship stored at file and symbol granularity must
758    /// count once (at its strongest evidence), and a name-only guess must not
759    /// outrank a verified relationship.
760    #[test]
761    fn related_files_counts_each_relationship_once_weighted_by_evidence() {
762        use crate::core::semantic::{EdgeEvidence, EvidenceGrade, EvidenceOrigin};
763        let g = test_graph();
764        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
765        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
766        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
767        let evidence = |grade| EdgeEvidence::new(grade, EvidenceOrigin::Enrichment, None, 1);
768
769        // a→b: one verified call, also mirrored by three symbol→symbol edges.
770        g.upsert_edge_with_evidence(
771            a,
772            b,
773            &EdgeKind::Calls,
774            &evidence(EvidenceGrade::VerifiedSemantic),
775        )
776        .unwrap();
777        for i in 0..3 {
778            let caller = g
779                .upsert_node(&Node::symbol(&format!("f{i}"), "a.rs", NodeKind::Symbol))
780                .unwrap();
781            let callee = g
782                .upsert_node(&Node::symbol(&format!("g{i}"), "b.rs", NodeKind::Symbol))
783                .unwrap();
784            g.upsert_edge_with_evidence(
785                caller,
786                callee,
787                &EdgeKind::Calls,
788                &evidence(EvidenceGrade::ResolvedStructural),
789            )
790            .unwrap();
791        }
792        // a→c: a heuristic name match only.
793        g.upsert_edge_with_evidence(
794            a,
795            c,
796            &EdgeKind::Calls,
797            &evidence(EvidenceGrade::HeuristicStructural),
798        )
799        .unwrap();
800
801        let related = g.related_files("a.rs", 10).unwrap();
802        let score = |p: &str| related.iter().find(|(f, _)| f == p).unwrap().1;
803        assert!(
804            (score("b.rs") - edge_weight("calls")).abs() < 1e-9,
805            "counted once"
806        );
807        assert!(score("b.rs") > score("c.rs"), "verified outranks heuristic");
808    }
809
810    #[test]
811    fn graph_dir_uses_data_dir_when_set() {
812        let tmp = tempfile::tempdir().unwrap();
813        let project = tmp.path().join("myproject");
814        std::fs::create_dir_all(&project).unwrap();
815
816        let data_dir = tmp.path().join("data");
817        std::fs::create_dir_all(&data_dir).unwrap();
818
819        let _guard = test_env_lock();
820        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
821
822        let dir = graph_dir(project.to_str().unwrap());
823        assert!(dir.starts_with(&data_dir));
824        assert!(dir.to_string_lossy().contains("graphs"));
825
826        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
827    }
828
829    #[test]
830    fn graph_dir_returns_consistent_hash_dir() {
831        let tmp = tempfile::tempdir().unwrap();
832        let project = tmp.path().join("hash_project");
833        std::fs::create_dir_all(&project).unwrap();
834
835        let data_dir = tmp.path().join("data2");
836        std::fs::create_dir_all(&data_dir).unwrap();
837
838        let _guard = test_env_lock();
839        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
840
841        let dir1 = graph_dir(project.to_str().unwrap());
842        let dir2 = graph_dir(project.to_str().unwrap());
843        assert_eq!(dir1, dir2, "graph_dir should be deterministic");
844        assert!(dir1.to_string_lossy().contains("graphs"));
845
846        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
847    }
848
849    #[test]
850    fn migration_moves_old_files() {
851        let tmp = tempfile::tempdir().unwrap();
852        let project = tmp.path().join("migtest");
853        let old_dir = project.join(".lean-ctx");
854        std::fs::create_dir_all(&old_dir).unwrap();
855        std::fs::write(old_dir.join("graph.db"), b"old-db-content").unwrap();
856        std::fs::write(old_dir.join("graph.meta.json"), b"old-meta").unwrap();
857
858        let new_dir = tmp.path().join("newloc");
859        std::fs::create_dir_all(&new_dir).unwrap();
860
861        migrate_if_needed(project.to_str().unwrap(), &new_dir);
862
863        assert!(new_dir.join("graph.db").exists());
864        assert!(new_dir.join("graph.meta.json").exists());
865        assert!(!old_dir.join("graph.db").exists());
866        assert!(!old_dir.join("graph.meta.json").exists());
867        assert_eq!(
868            std::fs::read_to_string(new_dir.join("graph.db")).unwrap(),
869            "old-db-content"
870        );
871    }
872
873    #[test]
874    fn migration_skips_when_new_exists() {
875        let tmp = tempfile::tempdir().unwrap();
876        let project = tmp.path().join("skiptest");
877        let old_dir = project.join(".lean-ctx");
878        std::fs::create_dir_all(&old_dir).unwrap();
879        std::fs::write(old_dir.join("graph.db"), b"old").unwrap();
880
881        let new_dir = tmp.path().join("newloc2");
882        std::fs::create_dir_all(&new_dir).unwrap();
883        std::fs::write(new_dir.join("graph.db"), b"already-there").unwrap();
884
885        migrate_if_needed(project.to_str().unwrap(), &new_dir);
886
887        assert_eq!(
888            std::fs::read_to_string(new_dir.join("graph.db")).unwrap(),
889            "already-there"
890        );
891        assert!(old_dir.join("graph.db").exists());
892    }
893
894    #[test]
895    fn open_with_data_dir() {
896        let tmp = tempfile::tempdir().unwrap();
897        let project = tmp.path().join("opentest");
898        std::fs::create_dir_all(&project).unwrap();
899
900        let data_dir = tmp.path().join("xdata");
901        std::fs::create_dir_all(&data_dir).unwrap();
902
903        let _guard = test_env_lock();
904        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
905
906        let g = CodeGraph::open(project.to_str().unwrap()).unwrap();
907        assert!(g.db_path().starts_with(&data_dir));
908        assert!(g.db_path().to_string_lossy().contains("graph.db"));
909
910        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
911    }
912
913    #[test]
914    fn meta_path_uses_graph_dir() {
915        let tmp = tempfile::tempdir().unwrap();
916        let project = tmp.path().join("metatest");
917        std::fs::create_dir_all(&project).unwrap();
918
919        let data_dir = tmp.path().join("mdata");
920        std::fs::create_dir_all(&data_dir).unwrap();
921
922        let _guard = test_env_lock();
923        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
924
925        let mp = meta::meta_path(project.to_str().unwrap());
926        assert!(mp.starts_with(&data_dir));
927        assert!(mp.to_string_lossy().contains("graph.meta.json"));
928
929        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
930    }
931
932    #[test]
933    fn engine_outdated_flags_old_and_missing_meta() {
934        let _iso = crate::core::data_dir::isolated_data_dir();
935        let proj = tempfile::tempdir().unwrap();
936        let root = proj.path().to_str().unwrap();
937
938        // No meta on disk yet -> outdated (an unbuilt graph forces a build).
939        assert!(engine_outdated(root), "missing meta must read as outdated");
940
941        // Meta from an engine generation before the version stamp -> outdated.
942        let mut meta = PropertyGraphMetaV1 {
943            built_at: "2026-01-01T00:00:00Z".to_string(),
944            engine_version: 0,
945            ..Default::default()
946        };
947        write_meta(root, &meta).unwrap();
948        assert!(
949            engine_outdated(root),
950            "engine_version 0 must read as outdated"
951        );
952
953        // Meta stamped with the current engine -> up to date.
954        meta.engine_version = GRAPH_ENGINE_VERSION;
955        write_meta(root, &meta).unwrap();
956        assert!(
957            !engine_outdated(root),
958            "current engine_version must read as up to date"
959        );
960
961        // Meta stamped by a later engine (the state after a rollback) -> rebuilt.
962        meta.engine_version = GRAPH_ENGINE_VERSION + 1;
963        write_meta(root, &meta).unwrap();
964        assert!(
965            engine_outdated(root),
966            "a graph of a newer engine must not be read by this one"
967        );
968    }
969}