Skip to main content

lean_ctx_cli/cli/
import_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Import AI coding-session history into the project knowledge store.
3
4use std::path::Path;
5
6use lean_ctx::core::import;
7use lean_ctx::core::knowledge::{KnowledgeFact, ProjectKnowledge};
8
9pub fn cmd_import(args: &[String]) {
10    let code = run(args);
11    if code != 0 {
12        std::process::exit(code);
13    }
14}
15
16/// Exit status: 0 on success, 2 for a usage error, 1 when the import itself
17/// fails (F9c: an error never exits 0). Per-source read warnings stay
18/// warnings.
19fn run(args: &[String]) -> i32 {
20    if args
21        .iter()
22        .any(|arg| matches!(arg.as_str(), "--help" | "-h"))
23    {
24        print_help();
25        return 0;
26    }
27
28    let dry_run = args.iter().any(|arg| arg == "--dry-run");
29    let all = args.iter().any(|arg| arg == "--all");
30    let limit_value = args
31        .iter()
32        .position(|arg| arg == "--limit")
33        .and_then(|index| args.get(index + 1));
34    let sources: Vec<&str> = args
35        .iter()
36        .filter(|arg| Some(*arg) != limit_value)
37        .filter_map(|arg| (!arg.starts_with('-')).then_some(arg.as_str()))
38        .collect();
39
40    // The project's own sources (K1): `docs [paths…]` and `git [--limit N]`.
41    let repo_source = matches!(sources.first().copied(), Some("docs" | "git"));
42    if !repo_source && ((all && !sources.is_empty()) || sources.len() > 1) {
43        eprintln!("Use one source (claude-code, codex, cursor, opencode, docs, git) or --all.");
44        print_help();
45        return 2;
46    }
47
48    let (label, mut result) = if repo_source {
49        let project_root = match super::common::require_project_root() {
50            Ok(root) => root,
51            Err(error) => {
52                eprintln!("Import failed: {error}");
53                return 1;
54            }
55        };
56        let root = std::path::Path::new(&project_root);
57        if sources[0] == "docs" {
58            let paths: Vec<std::path::PathBuf> =
59                sources[1..].iter().map(std::path::PathBuf::from).collect();
60            ("docs", import::markdown::import(root, &paths))
61        } else {
62            let limit = match limit_value.map(|value| value.parse::<usize>()) {
63                None => import::git_history::DEFAULT_LIMIT,
64                Some(Ok(limit)) if limit > 0 => limit,
65                Some(_) => {
66                    eprintln!("--limit takes a positive number of commits.");
67                    return 2;
68                }
69            };
70            ("git", import::git_history::import(root, limit))
71        }
72    } else if all {
73        let mut result = import::claude_code::import();
74        result.merge(import::codex::import());
75        result.merge(import::cursor::import());
76        result.merge(import::opencode::import());
77        ("all sources", result)
78    } else {
79        match sources.first().copied() {
80            Some("claude-code") => ("claude-code", import::claude_code::import()),
81            Some("codex") => ("codex", import::codex::import()),
82            Some("cursor") => ("cursor", import::cursor::import()),
83            Some("opencode") => ("opencode", import::opencode::import()),
84            _ => {
85                eprintln!(
86                    "Choose a source: claude-code, codex, cursor, opencode, docs, git, or --all."
87                );
88                print_help();
89                return 2;
90            }
91        }
92    };
93
94    let extracted = result.facts_extracted;
95    let persisted = if dry_run {
96        0
97    } else {
98        let project_root = match super::common::require_project_root() {
99            Ok(root) => root,
100            Err(error) => {
101                eprintln!("Import failed: {error}");
102                return 1;
103            }
104        };
105        let scope = result.repo_scope.take();
106        match persist_facts(
107            &project_root,
108            std::mem::take(&mut result.facts),
109            scope.as_ref(),
110        ) {
111            Ok(count) => count,
112            Err(error) => {
113                eprintln!("Import failed: {error}");
114                return 1;
115            }
116        }
117    };
118
119    let summary = import_summary(dry_run, label, persisted, extracted, &result);
120    super::common::print_released(&released_summary(summary));
121    for error in &result.errors {
122        eprintln!("Import warning: {error}");
123    }
124    if repo_source && !dry_run {
125        queue_import_drafts();
126    }
127    0
128}
129
130/// A connected machine proposes what the repository import brought to the
131/// project's Cloud repo (queued only; `lean-ctx cloud sync` or the
132/// scheduler sends it). Counts only on stdout.
133fn queue_import_drafts() {
134    use lean_ctx_cloud::CloudStore;
135    use lean_ctx_cloud::knowledge::{import_draft, screening::Screen};
136    let Ok(store) = CloudStore::open() else {
137        return;
138    };
139    if !matches!(store.instance(), Ok(Some(_))) {
140        return;
141    }
142    let Ok(project_root) = super::common::require_project_root() else {
143        return;
144    };
145    let config = lean_ctx::core::config::Config::load().cloud.clone();
146    let mut screen = Screen::for_installation();
147    match import_draft::enqueue_import_drafts(
148        &store,
149        &config,
150        Path::new(&project_root),
151        "cli-import",
152        &mut screen,
153        lean_ctx_time::UtcDateTime::now(),
154    ) {
155        Ok(ids) if !ids.is_empty() => println!(
156            "Queued {} import draft(s) for LeanCTX Cloud review (sent with `lean-ctx cloud sync`).",
157            ids.len()
158        ),
159        Ok(_) => {}
160        Err(error) => eprintln!("LeanCTX Cloud: import drafts not queued: {error}"),
161    }
162}
163
164/// What the command reports on stdout. Counts and the source label only: a
165/// fact that admission did not let into the store appears as a number
166/// (`facts skipped`), never by its value; a history source that was not
167/// read appears as a number (`sources skipped` — above the read cap or
168/// unreadable; `sources refused` — outside every named root or withheld),
169/// never by its path.
170fn import_summary(
171    dry_run: bool,
172    label: &str,
173    persisted: usize,
174    extracted: usize,
175    result: &import::ImportResult,
176) -> String {
177    let outcome = if dry_run {
178        format!("[DRY RUN] {label}: no facts written")
179    } else {
180        format!("Imported {persisted} new fact(s) from {label}.")
181    };
182    format!(
183        "{outcome}\nSessions: {}; facts extracted: {extracted}; facts skipped: {}; \
184         sources skipped: {}; sources refused: {}; files touched: {}",
185        result.sessions_found,
186        result.facts_skipped,
187        result.sources_skipped,
188        result.sources_refused,
189        result.files_touched
190    )
191}
192
193/// The import summary is counts and the source label — a report for the
194/// person at the terminal: released, never recorded as a delivery.
195fn released_summary(summary: String) -> String {
196    let root = super::common::detect_project_root(&[]);
197    super::common::CliToolRun::new("ctx_knowledge", &root, None)
198        .human_facing()
199        .deliver_text(|| summary)
200}
201
202fn persist_facts(
203    project_root: &str,
204    facts: Vec<KnowledgeFact>,
205    scope: Option<&import::RepoScope>,
206) -> Result<usize, String> {
207    let now = lean_ctx_time::UtcDateTime::now();
208    ProjectKnowledge::mutate_locked(project_root, |knowledge| {
209        if let Some(scope) = scope {
210            mark_removed_sections(knowledge, &facts, scope, Path::new(project_root), now);
211        }
212        let mut added = 0;
213        // The facts arrive admitted for a store: `core::import` admits each
214        // value where the fact is built, for every caller (E3).
215        for fact in facts {
216            let exists = knowledge.facts.iter().any(|existing| {
217                existing.category == fact.category
218                    && existing.value == fact.value
219                    && existing.imported_from == fact.imported_from
220            });
221            if exists {
222                // Found again: a section that was gone is back.
223                for existing in knowledge.facts.iter_mut().filter(|existing| {
224                    existing.key == fact.key && existing.imported_from == fact.imported_from
225                }) {
226                    clear_source_removed(existing);
227                    if !fact.anchors.is_empty() {
228                        existing.anchors.clone_from(&fact.anchors);
229                    }
230                }
231                continue;
232            }
233            // A repository source (docs, git) anchors each fact (`key`): a
234            // changed text at the same anchor updates that fact instead of
235            // adding a second one next to it.
236            let anchored = (!fact.key.is_empty())
237                .then(|| {
238                    knowledge.facts.iter_mut().find(|existing| {
239                        existing.is_current()
240                            && existing.key == fact.key
241                            && existing.imported_from == fact.imported_from
242                    })
243                })
244                .flatten();
245            match anchored {
246                Some(existing) => {
247                    existing.category.clone_from(&fact.category);
248                    existing.value = fact.value;
249                    existing.archetype = fact.archetype;
250                    existing.last_confirmed = fact.last_confirmed;
251                    existing.revision_count += 1;
252                    existing.anchors = fact.anchors;
253                    clear_source_removed(existing);
254                }
255                None => knowledge.facts.push(fact),
256            }
257            added += 1;
258        }
259        added
260    })
261    .map(|(_, added)| added)
262}
263
264/// A docs fact whose file this run read (or, for a whole-project run, whose
265/// file is gone) but whose anchor did not come back lost its section: it is
266/// *to verify* (`source_removed`), still recalled, never deleted (K1).
267fn mark_removed_sections(
268    knowledge: &mut ProjectKnowledge,
269    found: &[KnowledgeFact],
270    scope: &import::RepoScope,
271    root: &Path,
272    now: lean_ctx_time::UtcDateTime,
273) {
274    use lean_ctx::core::knowledge::{FactReviewReason, FactReviewState};
275    let docs = Some(import::ImportSource::Docs.as_str());
276    let keys: std::collections::HashSet<&str> = found
277        .iter()
278        .filter(|fact| fact.imported_from.as_deref() == docs)
279        .map(|fact| fact.key.as_str())
280        .collect();
281    for fact in knowledge.facts.iter_mut().filter(|fact| {
282        fact.is_current()
283            && fact.imported_from.as_deref() == docs
284            && !keys.contains(fact.key.as_str())
285    }) {
286        let Some((file, _)) = fact.key.split_once('#') else {
287            continue;
288        };
289        let covered = scope.files.iter().any(|read| read == file)
290            || (scope.whole && !root.join(file).exists());
291        if covered {
292            fact.mark_review(
293                FactReviewState::ToVerify,
294                FactReviewReason::SourceRemoved,
295                now,
296            );
297        }
298    }
299}
300
301fn clear_source_removed(fact: &mut KnowledgeFact) {
302    if fact.review.as_ref().is_some_and(|review| {
303        review.reason == lean_ctx::core::knowledge::FactReviewReason::SourceRemoved
304    }) {
305        fact.clear_review();
306    }
307}
308
309fn print_help() {
310    println!("Usage: lean-ctx import <claude-code|codex|cursor|opencode> [--dry-run]");
311    println!("       lean-ctx import --all [--dry-run]");
312    println!("       lean-ctx import docs [<file|dir>...] [--dry-run]");
313    println!("         AGENTS.md, CLAUDE.md, .cursorrules, .cursor/rules and docs/ by default");
314    println!(
315        "       lean-ctx import git [--limit N] [--dry-run]   (reverts, fixes and decisions; default {})",
316        import::git_history::DEFAULT_LIMIT
317    );
318}
319
320#[cfg(test)]
321mod tests {
322    use lean_ctx::core::import::ImportSource;
323
324    #[test]
325    fn source_names_match_import_engine() {
326        assert_eq!(ImportSource::ClaudeCode.as_str(), "claude-code");
327        assert_eq!(ImportSource::Codex.as_str(), "codex");
328        assert_eq!(ImportSource::Cursor.as_str(), "cursor");
329        assert_eq!(ImportSource::OpenCode.as_str(), "opencode");
330    }
331
332    /// F9c: a usage error exits non-zero instead of printing and exiting 0.
333    #[test]
334    fn a_usage_error_exits_non_zero() {
335        let args = |list: &[&str]| list.iter().map(ToString::to_string).collect::<Vec<_>>();
336        assert_eq!(super::run(&args(&[])), 2, "no source");
337        assert_eq!(super::run(&args(&["codex", "cursor"])), 2, "two sources");
338        assert_eq!(super::run(&args(&["nowhere"])), 2, "unknown source");
339        assert_eq!(super::run(&args(&["--help"])), 0);
340    }
341
342    use crate::cli::common::carrier_tests_support::{AWS_KEY, governed, lineage};
343
344    /// The import summary is counts and a label: released, never registered.
345    #[test]
346    fn the_import_summary_is_human_facing() {
347        let _data = lean_ctx::core::data_dir::isolated_data_dir();
348        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
349        governed();
350        let root = crate::cli::common::detect_project_root(&[]);
351        let summary =
352            "Imported 3 new fact(s) from codex.\nSessions: 2; facts extracted: 5; files touched: 4";
353        let printed = super::released_summary(summary.to_string());
354        assert_eq!(printed, summary, "the summary keeps its bytes");
355        assert_eq!(lineage(&root, &printed), None);
356        let leaked = super::released_summary(format!("Imported 1 new fact(s) from {AWS_KEY}."));
357        assert!(!leaked.contains(AWS_KEY), "{leaked}");
358    }
359
360    /// End to end through the shared import and the CLI's store step: a
361    /// clean fact is stored with its bytes, a key-shaped value is never
362    /// stored raw, and the facts the store receives are the admitted ones.
363    #[test]
364    fn imported_facts_reach_the_store_admitted() {
365        let _data = lean_ctx::core::data_dir::isolated_data_dir();
366        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
367        let history = tempfile::tempdir().expect("history dir");
368        let history_root = history.path().canonicalize().expect("history root");
369        let session_dir = history_root.join("project-a");
370        std::fs::create_dir_all(&session_dir).expect("session dir");
371        let line = |text: &str| {
372            serde_json::json!({ "message": { "role": "assistant", "content": text } }).to_string()
373        };
374        std::fs::write(
375            session_dir.join("session.jsonl"),
376            format!(
377                "{}\n{}\n",
378                line("We decided to use JWT RS256 for the session tokens."),
379                line(&format!(
380                    "We decided to deploy with the key {AWS_KEY} today."
381                )),
382            ),
383        )
384        .expect("transcript");
385        let mut result = lean_ctx::core::import::claude_code::import_from_root(&history_root);
386        assert!(result.errors.is_empty(), "{:?}", result.errors);
387        assert!(
388            result
389                .facts
390                .iter()
391                .all(|fact| !fact.value.contains(AWS_KEY))
392        );
393
394        // The summary states counts only.
395        let summary =
396            super::import_summary(false, "claude-code", 1, result.facts_extracted, &result);
397        assert!(
398            summary.contains(&format!("facts skipped: {}", result.facts_skipped)),
399            "{summary}"
400        );
401        assert!(!summary.contains(AWS_KEY), "{summary}");
402        assert!(!summary.contains("JWT"), "{summary}");
403
404        // Sources that were not read are counts too — no path of theirs.
405        let refused = lean_ctx::core::import::ImportResult {
406            sources_refused: 2,
407            sources_skipped: 1,
408            ..Default::default()
409        };
410        let summary = super::import_summary(true, "opencode", 0, 0, &refused);
411        assert_eq!(
412            summary,
413            "[DRY RUN] opencode: no facts written\nSessions: 0; facts extracted: 0; \
414             facts skipped: 0; sources skipped: 1; sources refused: 2; files touched: 0"
415        );
416
417        let project = tempfile::tempdir().expect("project dir");
418        let root = project.path().to_string_lossy().into_owned();
419        let facts = std::mem::take(&mut result.facts);
420        let offered = facts.len();
421        let added = super::persist_facts(&root, facts, None).expect("persist");
422        assert_eq!(added, offered, "one store step, no second filter");
423        let stored = lean_ctx::core::knowledge::ProjectKnowledge::load(&root).expect("stored");
424        assert!(
425            stored
426                .facts
427                .iter()
428                .any(|fact| fact.value.contains("JWT RS256")),
429            "a clean fact is stored"
430        );
431        assert!(
432            stored
433                .facts
434                .iter()
435                .all(|fact| !fact.value.contains(AWS_KEY)),
436            "a masked value is never stored raw"
437        );
438    }
439
440    /// K1 + J2: an imported section is anchored; a section that disappears
441    /// leaves its facts *to verify* (`source_removed`), and they are current
442    /// again when it comes back.
443    #[test]
444    fn a_removed_section_leaves_its_facts_to_verify_until_it_returns() {
445        use lean_ctx::core::knowledge::{FactReviewReason, FactReviewState, ProjectKnowledge};
446        let _data = lean_ctx::core::data_dir::isolated_data_dir();
447        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
448        let project = tempfile::tempdir().unwrap();
449        let root = project.path().canonicalize().unwrap();
450        let root_text = root.to_string_lossy().into_owned();
451        let agents = root.join("AGENTS.md");
452        let both = "# Agents\n\n## Conventions\n\n- Run cargo fmt before every commit.\n\n\
453                    ## Gotchas\n\n- Never run lean-ctx stop before a build.\n";
454        let import = |root: &std::path::Path| {
455            let mut result = lean_ctx::core::import::markdown::import(root, &[]);
456            let scope = result.repo_scope.take();
457            super::persist_facts(
458                &root_text,
459                std::mem::take(&mut result.facts),
460                scope.as_ref(),
461            )
462            .unwrap();
463        };
464        let fact = |needle: &str| {
465            ProjectKnowledge::load(&root_text)
466                .unwrap()
467                .facts
468                .into_iter()
469                .find(|fact| fact.value.contains(needle))
470                .unwrap()
471        };
472        std::fs::write(&agents, both).unwrap();
473        import(&root);
474        let gotcha = fact("lean-ctx stop");
475        assert_eq!(gotcha.key, "AGENTS.md#agents/gotchas/1");
476        assert_eq!(gotcha.anchors.len(), 1);
477        assert_eq!(gotcha.anchors[0].symbol.as_deref(), Some("agents/gotchas"));
478        assert_eq!(gotcha.review, None);
479
480        std::fs::write(
481            &agents,
482            "# Agents\n\n## Conventions\n\n- Run cargo fmt before every commit.\n",
483        )
484        .unwrap();
485        import(&root);
486        let review = fact("lean-ctx stop").review.expect("marked");
487        assert_eq!(
488            (review.state, review.reason),
489            (FactReviewState::ToVerify, FactReviewReason::SourceRemoved)
490        );
491        assert_eq!(
492            fact("cargo fmt").review,
493            None,
494            "the kept section stays current"
495        );
496
497        std::fs::write(&agents, both).unwrap();
498        import(&root);
499        assert_eq!(fact("lean-ctx stop").review, None, "back again: current");
500
501        std::fs::remove_file(&agents).unwrap();
502        import(&root);
503        assert!(
504            fact("cargo fmt").review.is_some(),
505            "a removed file loses all its facts"
506        );
507    }
508}