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