Skip to main content

lean_ctx/cli/
import_cmd.rs

1//! Import AI coding-session history into the project knowledge store.
2
3use crate::core::import;
4use crate::core::knowledge::{KnowledgeFact, ProjectKnowledge};
5
6pub fn cmd_import(args: &[String]) {
7    if args
8        .iter()
9        .any(|arg| matches!(arg.as_str(), "--help" | "-h"))
10    {
11        print_help();
12        return;
13    }
14
15    let dry_run = args.iter().any(|arg| arg == "--dry-run");
16    let all = args.iter().any(|arg| arg == "--all");
17    let sources: Vec<&str> = args
18        .iter()
19        .filter_map(|arg| (!arg.starts_with('-')).then_some(arg.as_str()))
20        .collect();
21
22    if (all && !sources.is_empty()) || sources.len() > 1 {
23        eprintln!("Use one source (claude-code, codex, cursor) or --all.");
24        print_help();
25        return;
26    }
27
28    let (label, mut result) = if all {
29        let mut result = import::claude_code::import();
30        result.merge(import::codex::import());
31        result.merge(import::cursor::import());
32        ("all sources", result)
33    } else {
34        match sources.first().copied() {
35            Some("claude-code") => ("claude-code", import::claude_code::import()),
36            Some("codex") => ("codex", import::codex::import()),
37            Some("cursor") => ("cursor", import::cursor::import()),
38            _ => {
39                eprintln!("Choose a source: claude-code, codex, cursor, or --all.");
40                print_help();
41                return;
42            }
43        }
44    };
45
46    let extracted = result.facts_extracted;
47    let persisted = if dry_run {
48        0
49    } else {
50        let project_root = match std::env::current_dir() {
51            Ok(path) => path.to_string_lossy().into_owned(),
52            Err(error) => {
53                eprintln!("Import failed: cannot determine project root: {error}");
54                return;
55            }
56        };
57        match persist_facts(&project_root, std::mem::take(&mut result.facts)) {
58            Ok(count) => count,
59            Err(error) => {
60                eprintln!("Import failed: {error}");
61                return;
62            }
63        }
64    };
65
66    if dry_run {
67        println!("[DRY RUN] {label}: no facts written");
68    } else {
69        println!("Imported {persisted} new fact(s) from {label}.");
70    }
71    println!(
72        "Sessions: {}; facts extracted: {extracted}; files touched: {}",
73        result.sessions_found, result.files_touched
74    );
75    for error in &result.errors {
76        eprintln!("Import warning: {error}");
77    }
78}
79
80fn persist_facts(project_root: &str, facts: Vec<KnowledgeFact>) -> Result<usize, String> {
81    ProjectKnowledge::mutate_locked(project_root, |knowledge| {
82        let mut added = 0;
83        for fact in facts {
84            let exists = knowledge.facts.iter().any(|existing| {
85                existing.category == fact.category
86                    && existing.value == fact.value
87                    && existing.imported_from == fact.imported_from
88            });
89            if !exists {
90                knowledge.facts.push(fact);
91                added += 1;
92            }
93        }
94        added
95    })
96    .map(|(_, added)| added)
97}
98
99fn print_help() {
100    println!("Usage: lean-ctx import <claude-code|codex|cursor> [--dry-run]");
101    println!("       lean-ctx import --all [--dry-run]");
102}
103
104#[cfg(test)]
105mod tests {
106    use crate::core::import::ImportSource;
107
108    #[test]
109    fn source_names_match_import_engine() {
110        assert_eq!(ImportSource::ClaudeCode.as_str(), "claude-code");
111        assert_eq!(ImportSource::Codex.as_str(), "codex");
112        assert_eq!(ImportSource::Cursor.as_str(), "cursor");
113    }
114}