Skip to main content

lean_ctx/core/
graph_enricher.rs

1//! Unified Graph Enricher — indexes Git history, tests, and knowledge into the PropertyGraph.
2//!
3//! Three enrichment passes:
4//! 1. **Git commits**: `git log` → Commit nodes + `changed_in` edges
5//! 2. **Test files**: naming/annotation heuristics → Test nodes + `tested_by` edges
6//! 3. **Knowledge bridge**: `ctx_knowledge` facts → Knowledge nodes + `mentioned_in` edges
7
8use crate::core::property_graph::{CodeGraph, Edge, EdgeKind, Node};
9use std::collections::HashSet;
10use std::path::Path;
11
12// ---------------------------------------------------------------------------
13// Git History Indexer
14// ---------------------------------------------------------------------------
15
16#[derive(Debug, Clone)]
17pub struct CommitInfo {
18    pub hash: String,
19    pub short_hash: String,
20    pub author: String,
21    pub date: String,
22    pub message: String,
23    pub files_changed: Vec<String>,
24}
25
26pub fn index_git_history(
27    graph: &CodeGraph,
28    project_root: &Path,
29    max_commits: usize,
30) -> anyhow::Result<EnrichmentStats> {
31    let mut stats = EnrichmentStats::default();
32
33    let output = std::process::Command::new("git")
34        .args([
35            "log",
36            &format!("-{max_commits}"),
37            "--format=%H%n%h%n%an%n%ai%n%s",
38            "--name-only",
39        ])
40        .current_dir(project_root)
41        .output();
42
43    let output = match output {
44        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
45        _ => return Ok(stats),
46    };
47
48    let commits = parse_git_log(&output);
49    for commit in &commits {
50        let commit_node =
51            Node::commit(&commit.short_hash, &commit.message).with_metadata(&format!(
52                "{{\"author\":\"{}\",\"date\":\"{}\",\"hash\":\"{}\"}}",
53                commit.author, commit.date, commit.hash
54            ));
55
56        let commit_id = graph.upsert_node(&commit_node)?;
57        stats.commits_indexed += 1;
58
59        for file in &commit.files_changed {
60            if let Some(file_node) = graph.get_node_by_path(file)?
61                && let Some(file_id) = file_node.id
62            {
63                graph.upsert_edge(&Edge::new(file_id, commit_id, EdgeKind::ChangedIn))?;
64                stats.edges_created += 1;
65            }
66        }
67    }
68
69    Ok(stats)
70}
71
72fn parse_git_log(output: &str) -> Vec<CommitInfo> {
73    let mut commits = Vec::new();
74    let mut lines = output.lines().peekable();
75
76    while lines.peek().is_some() {
77        let hash = match lines.next() {
78            Some(h) if !h.is_empty() && h.len() >= 7 => h.to_string(),
79            _ => {
80                lines.next();
81                continue;
82            }
83        };
84
85        let short_hash = match lines.next() {
86            Some(s) => s.to_string(),
87            None => break,
88        };
89        let author = match lines.next() {
90            Some(a) => a.to_string(),
91            None => break,
92        };
93        let date = match lines.next() {
94            Some(d) => d.to_string(),
95            None => break,
96        };
97        let message = match lines.next() {
98            Some(m) => m.to_string(),
99            None => break,
100        };
101
102        let mut files_changed = Vec::new();
103        while let Some(line) = lines.peek() {
104            if line.is_empty() {
105                lines.next();
106                break;
107            }
108            files_changed.push(line.to_string());
109            lines.next();
110        }
111
112        commits.push(CommitInfo {
113            hash,
114            short_hash,
115            author,
116            date,
117            message,
118            files_changed,
119        });
120    }
121
122    commits
123}
124
125// ---------------------------------------------------------------------------
126// Test Indexer
127// ---------------------------------------------------------------------------
128
129const TEST_PATTERNS: &[&str] = &[
130    "_test.",
131    "test_",
132    ".test.",
133    ".spec.",
134    "_spec.",
135    "tests/",
136    "__tests__/",
137];
138
139pub fn index_tests(graph: &CodeGraph, project_root: &Path) -> anyhow::Result<EnrichmentStats> {
140    let mut stats = EnrichmentStats::default();
141
142    let output = std::process::Command::new("git")
143        .args(["ls-files"])
144        .current_dir(project_root)
145        .output();
146
147    let files: Vec<String> = match output {
148        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
149            .lines()
150            .map(ToString::to_string)
151            .collect(),
152        _ => return Ok(stats),
153    };
154
155    for file in &files {
156        if !is_test_file(file) {
157            continue;
158        }
159
160        let test_node = Node::test(file, file);
161        let test_id = graph.upsert_node(&test_node)?;
162        stats.tests_indexed += 1;
163
164        let tested_file = infer_tested_file(file);
165        if let Some(ref tested) = tested_file
166            && files.contains(tested)
167        {
168            let target_node = graph.get_node_by_path(tested)?;
169            if let Some(target) = target_node {
170                if let Some(target_id) = target.id {
171                    graph.upsert_edge(&Edge::new(target_id, test_id, EdgeKind::TestedBy))?;
172                    stats.edges_created += 1;
173                }
174            } else {
175                let file_id = graph.upsert_node(&Node::file(tested))?;
176                graph.upsert_edge(&Edge::new(file_id, test_id, EdgeKind::TestedBy))?;
177                stats.edges_created += 1;
178            }
179        }
180    }
181
182    Ok(stats)
183}
184
185fn is_test_file(path: &str) -> bool {
186    let lower = path.to_lowercase();
187    TEST_PATTERNS.iter().any(|p| lower.contains(p))
188}
189
190fn infer_tested_file(test_path: &str) -> Option<String> {
191    let name = Path::new(test_path).file_name()?.to_str()?;
192
193    for pattern in &["_test.", ".test.", "_spec.", ".spec."] {
194        if let Some(pos) = name.find(pattern) {
195            let base = &name[..pos];
196            let ext = &name[pos + pattern.len() - 1..];
197            let parent = Path::new(test_path).parent()?;
198
199            let candidate = parent.join(format!("{base}{ext}"));
200            if let Some(s) = candidate.to_str() {
201                return Some(s.replace('\\', "/"));
202            }
203
204            if let Some(pp) = parent.parent() {
205                let src_candidate = pp.join("src").join(format!("{base}{ext}"));
206                if let Some(s) = src_candidate.to_str() {
207                    return Some(s.replace('\\', "/"));
208                }
209            }
210        }
211    }
212
213    if let Some(base) = name.strip_prefix("test_") {
214        let parent = Path::new(test_path).parent()?;
215        let candidate = parent.join(base);
216        return candidate.to_str().map(|s| s.replace('\\', "/"));
217    }
218
219    None
220}
221
222// ---------------------------------------------------------------------------
223// Knowledge Bridge
224// ---------------------------------------------------------------------------
225
226pub fn index_knowledge(graph: &CodeGraph, project_root: &str) -> anyhow::Result<EnrichmentStats> {
227    let mut stats = EnrichmentStats::default();
228
229    let knowledge = crate::core::knowledge::ProjectKnowledge::load(project_root);
230    let Some(knowledge) = knowledge else {
231        return Ok(stats);
232    };
233
234    let mut mentioned_files: HashSet<String> = HashSet::new();
235
236    for fact in &knowledge.facts {
237        let node = Node::knowledge(&fact.key, &format!("[{}] {}", fact.category, fact.value));
238        let knowledge_id = graph.upsert_node(&node)?;
239        stats.knowledge_indexed += 1;
240
241        for file_ref in extract_file_refs(&fact.value) {
242            if mentioned_files.insert(format!("{}:{}", fact.key, file_ref))
243                && let Some(file_node) = graph.get_node_by_path(&file_ref)?
244                && let Some(file_id) = file_node.id
245            {
246                graph.upsert_edge(&Edge::new(file_id, knowledge_id, EdgeKind::MentionedIn))?;
247                stats.edges_created += 1;
248            }
249        }
250    }
251
252    Ok(stats)
253}
254
255fn extract_file_refs(text: &str) -> Vec<String> {
256    let mut refs = Vec::new();
257    for word in text.split_whitespace() {
258        let cleaned = word.trim_matches(|c: char| c == '`' || c == '\'' || c == '"' || c == ',');
259        if looks_like_file_path(cleaned) {
260            refs.push(cleaned.to_string());
261        }
262    }
263    refs
264}
265
266fn looks_like_file_path(s: &str) -> bool {
267    if s.len() < 4 || s.len() > 200 {
268        return false;
269    }
270    let path = Path::new(s);
271    let has_sep = s.contains('/') || s.contains('\\');
272    match path.extension().and_then(|e| e.to_str()) {
273        Some(ext) => {
274            let ext_lower = ext.to_ascii_lowercase();
275            has_sep
276                || matches!(
277                    ext_lower.as_str(),
278                    "rs" | "ts"
279                        | "py"
280                        | "js"
281                        | "go"
282                        | "java"
283                        | "tsx"
284                        | "jsx"
285                        | "rb"
286                        | "c"
287                        | "cpp"
288                        | "h"
289                        | "cs"
290                        | "swift"
291                        | "kt"
292                )
293        }
294        None => false,
295    }
296}
297
298// ---------------------------------------------------------------------------
299// Full enrichment pipeline
300// ---------------------------------------------------------------------------
301
302#[derive(Debug, Default)]
303pub struct EnrichmentStats {
304    pub commits_indexed: usize,
305    pub tests_indexed: usize,
306    pub knowledge_indexed: usize,
307    pub edges_created: usize,
308}
309
310impl EnrichmentStats {
311    pub fn merge(&mut self, other: &Self) {
312        self.commits_indexed += other.commits_indexed;
313        self.tests_indexed += other.tests_indexed;
314        self.knowledge_indexed += other.knowledge_indexed;
315        self.edges_created += other.edges_created;
316    }
317
318    pub fn format_summary(&self) -> String {
319        format!(
320            "Graph enriched: {} commits, {} tests, {} knowledge entries, {} edges",
321            self.commits_indexed, self.tests_indexed, self.knowledge_indexed, self.edges_created
322        )
323    }
324}
325
326pub fn enrich_graph(
327    graph: &CodeGraph,
328    project_root: &Path,
329    max_commits: usize,
330) -> anyhow::Result<EnrichmentStats> {
331    let mut total = EnrichmentStats::default();
332
333    let git_stats = index_git_history(graph, project_root, max_commits)?;
334    total.merge(&git_stats);
335
336    let test_stats = index_tests(graph, project_root)?;
337    total.merge(&test_stats);
338
339    if let Some(root_str) = project_root.to_str() {
340        let knowledge_stats = index_knowledge(graph, root_str)?;
341        total.merge(&knowledge_stats);
342
343        let callgraph_stats = consolidate_callgraph(graph, root_str)?;
344        total.merge(&callgraph_stats);
345    }
346
347    Ok(total)
348}
349
350fn consolidate_callgraph(graph: &CodeGraph, project_root: &str) -> anyhow::Result<EnrichmentStats> {
351    let mut stats = EnrichmentStats::default();
352
353    let inputs = crate::core::call_graph::CallGraphInputs::open(project_root);
354    let call_graph = crate::core::call_graph::CallGraph::load_or_build(project_root, &inputs);
355
356    // Symbols now come from the PropertyGraph via the facade (#696, resolving
357    // opt1415): the call-graph inputs already carry the full symbol table.
358    let callee_to_file: std::collections::HashMap<&str, &str> = inputs
359        .symbols
360        .iter()
361        .map(|s| (s.name.as_str(), s.file.as_str()))
362        .collect();
363
364    for edge in &call_graph.edges {
365        let from_file = &edge.caller_file;
366        let to_file = match callee_to_file.get(edge.callee_name.as_str()) {
367            Some(f) => *f,
368            None => continue,
369        };
370
371        if from_file == to_file {
372            continue;
373        }
374
375        let from_node = graph.get_node_by_path(from_file)?;
376        let to_node = graph.get_node_by_path(to_file)?;
377
378        if let (Some(from_n), Some(to_n)) = (from_node, to_node)
379            && let (Some(from_id), Some(to_id)) = (from_n.id, to_n.id)
380        {
381            graph.upsert_edge(&Edge::new(from_id, to_id, EdgeKind::Calls))?;
382            stats.edges_created += 1;
383        }
384    }
385
386    Ok(stats)
387}
388
389// ---------------------------------------------------------------------------
390// Tests
391// ---------------------------------------------------------------------------
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396    use crate::core::property_graph::NodeKind;
397
398    #[test]
399    fn parse_git_log_basic() {
400        let log = "abc1234567890abcdef1234567890abcdef12345678\nabc1234\nJohn Doe\n2026-04-28 12:00:00 +0200\nfeat: add feature\nsrc/main.rs\nsrc/lib.rs\n\n";
401        let commits = parse_git_log(log);
402        assert_eq!(commits.len(), 1);
403        assert_eq!(commits[0].short_hash, "abc1234");
404        assert_eq!(commits[0].author, "John Doe");
405        assert_eq!(commits[0].files_changed.len(), 2);
406    }
407
408    #[test]
409    fn parse_git_log_multiple() {
410        let log = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2\na1b2c3d\nAlice\n2026-04-27\nfirst\nfile1.rs\n\nf6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5\nf6e5d4c\nBob\n2026-04-28\nsecond\nfile2.rs\nfile3.rs\n\n";
411        let commits = parse_git_log(log);
412        assert_eq!(commits.len(), 2);
413        assert_eq!(commits[1].files_changed.len(), 2);
414    }
415
416    #[test]
417    fn is_test_file_detection() {
418        assert!(is_test_file("src/utils_test.rs"));
419        assert!(is_test_file("tests/integration.rs"));
420        assert!(is_test_file("src/component.test.ts"));
421        assert!(is_test_file("src/component.spec.js"));
422        assert!(is_test_file("__tests__/app.js"));
423        assert!(!is_test_file("src/main.rs"));
424        assert!(!is_test_file("src/utils.rs"));
425    }
426
427    #[test]
428    fn infer_tested_file_from_test() {
429        assert_eq!(
430            infer_tested_file("src/utils_test.rs"),
431            Some("src/utils.rs".to_string())
432        );
433        assert_eq!(
434            infer_tested_file("src/component.test.ts"),
435            Some("src/component.ts".to_string())
436        );
437        assert_eq!(
438            infer_tested_file("src/app.spec.js"),
439            Some("src/app.js".to_string())
440        );
441    }
442
443    #[test]
444    fn infer_tested_file_prefix() {
445        assert_eq!(
446            infer_tested_file("tests/test_parser.py"),
447            Some("tests/parser.py".to_string())
448        );
449    }
450
451    #[test]
452    fn looks_like_file_path_detection() {
453        assert!(looks_like_file_path("src/main.rs"));
454        assert!(looks_like_file_path("core/utils.ts"));
455        assert!(looks_like_file_path("main.py"));
456        assert!(!looks_like_file_path("hello"));
457        assert!(!looks_like_file_path("a.b"));
458        assert!(!looks_like_file_path(".hidden"));
459    }
460
461    #[test]
462    fn extract_file_refs_from_text() {
463        let text = "Changed `src/main.rs` and core/utils.ts for the fix";
464        let refs = extract_file_refs(text);
465        assert!(refs.contains(&"src/main.rs".to_string()));
466        assert!(refs.contains(&"core/utils.ts".to_string()));
467    }
468
469    #[test]
470    fn enrichment_stats_merge() {
471        let mut a = EnrichmentStats {
472            commits_indexed: 5,
473            tests_indexed: 3,
474            knowledge_indexed: 2,
475            edges_created: 10,
476        };
477        let b = EnrichmentStats {
478            commits_indexed: 2,
479            tests_indexed: 1,
480            knowledge_indexed: 0,
481            edges_created: 4,
482        };
483        a.merge(&b);
484        assert_eq!(a.commits_indexed, 7);
485        assert_eq!(a.edges_created, 14);
486    }
487
488    #[test]
489    fn enrichment_stats_format() {
490        let s = EnrichmentStats {
491            commits_indexed: 10,
492            tests_indexed: 5,
493            knowledge_indexed: 3,
494            edges_created: 20,
495        };
496        let fmt = s.format_summary();
497        assert!(fmt.contains("10 commits"));
498        assert!(fmt.contains("5 tests"));
499    }
500
501    #[test]
502    fn commit_node_construction() {
503        let node = Node::commit("abc1234", "feat: add feature");
504        assert_eq!(node.kind, NodeKind::Commit);
505        assert_eq!(node.name, "abc1234");
506    }
507
508    #[test]
509    fn test_node_construction() {
510        let node = Node::test("src/utils_test.rs", "src/utils_test.rs");
511        assert_eq!(node.kind, NodeKind::Test);
512        assert_eq!(node.file_path, "src/utils_test.rs");
513    }
514
515    #[test]
516    fn knowledge_node_construction() {
517        let node = Node::knowledge("k1", "Database uses PostgreSQL");
518        assert_eq!(node.kind, NodeKind::Knowledge);
519        assert!(node.metadata.unwrap().contains("PostgreSQL"));
520    }
521
522    #[test]
523    fn graph_commit_and_edge() {
524        let g = CodeGraph::open_in_memory().unwrap();
525        let file_id = g.upsert_node(&Node::file("src/main.rs")).unwrap();
526        let commit_id = g.upsert_node(&Node::commit("abc1234", "fix bug")).unwrap();
527        g.upsert_edge(&Edge::new(file_id, commit_id, EdgeKind::ChangedIn))
528            .unwrap();
529
530        let edges = g.edges_from(file_id).unwrap();
531        assert_eq!(edges.len(), 1);
532        assert_eq!(edges[0].kind, EdgeKind::ChangedIn);
533    }
534
535    #[test]
536    fn graph_test_edge() {
537        let g = CodeGraph::open_in_memory().unwrap();
538        let code_id = g.upsert_node(&Node::file("src/utils.rs")).unwrap();
539        let test_id = g
540            .upsert_node(&Node::test("src/utils_test.rs", "test_parse"))
541            .unwrap();
542        g.upsert_edge(&Edge::new(code_id, test_id, EdgeKind::TestedBy))
543            .unwrap();
544
545        let edges = g.edges_from(code_id).unwrap();
546        assert_eq!(edges[0].kind, EdgeKind::TestedBy);
547    }
548
549    #[test]
550    fn graph_knowledge_edge() {
551        let g = CodeGraph::open_in_memory().unwrap();
552        let file_id = g.upsert_node(&Node::file("src/db.rs")).unwrap();
553        let k_id = g
554            .upsert_node(&Node::knowledge("db_type", "Uses PostgreSQL"))
555            .unwrap();
556        g.upsert_edge(&Edge::new(file_id, k_id, EdgeKind::MentionedIn))
557            .unwrap();
558
559        let edges = g.edges_from(file_id).unwrap();
560        assert_eq!(edges[0].kind, EdgeKind::MentionedIn);
561    }
562}