Skip to main content

lean_ctx/core/import/
mod.rs

1//! Import facts from local AI coding-session histories.
2
3pub mod claude_code;
4pub mod codex;
5pub mod cursor;
6
7use std::collections::HashSet;
8use std::path::{Path, PathBuf};
9
10use chrono::Utc;
11use serde_json::Value;
12
13use crate::core::knowledge::KnowledgeFact;
14
15const MAX_FACT_VALUE_CHARS: usize = 500;
16const MAX_ERRORS: usize = 100;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ImportSource {
20    ClaudeCode,
21    Codex,
22    Cursor,
23}
24
25impl ImportSource {
26    #[must_use]
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::ClaudeCode => "claude-code",
30            Self::Codex => "codex",
31            Self::Cursor => "cursor",
32        }
33    }
34}
35
36#[derive(Debug, Clone, Default)]
37pub struct ImportResult {
38    pub sessions_found: usize,
39    pub facts_extracted: usize,
40    pub files_touched: usize,
41    pub errors: Vec<String>,
42    /// Facts remain available to the CLI until it either persists or displays them.
43    pub facts: Vec<KnowledgeFact>,
44}
45
46impl ImportResult {
47    pub(crate) fn merge(&mut self, mut other: Self) {
48        self.sessions_found += other.sessions_found;
49        self.facts_extracted += other.facts_extracted;
50        self.files_touched += other.files_touched;
51        self.errors.append(&mut other.errors);
52        self.facts.append(&mut other.facts);
53    }
54}
55
56pub(crate) fn home_dir() -> Option<PathBuf> {
57    std::env::var_os("HOME").map(PathBuf::from)
58}
59
60pub(crate) fn read_jsonl_files(source: ImportSource, files: Vec<PathBuf>) -> ImportResult {
61    let mut result = ImportResult {
62        sessions_found: files.len(),
63        ..ImportResult::default()
64    };
65    let mut touched = HashSet::new();
66    let mut seen = HashSet::new();
67
68    for path in files {
69        let session = session_id(source, &path);
70        match std::fs::read_to_string(&path) {
71            Ok(content) => {
72                for (line_number, line) in content.lines().enumerate() {
73                    if line.trim().is_empty() {
74                        continue;
75                    }
76                    match serde_json::from_str::<Value>(line) {
77                        Ok(value) => process_value(
78                            source,
79                            &session,
80                            &value,
81                            &mut result,
82                            &mut touched,
83                            &mut seen,
84                        ),
85                        Err(error) => push_error(
86                            &mut result,
87                            format!(
88                                "{}:{}: invalid JSONL: {error}",
89                                path.display(),
90                                line_number + 1
91                            ),
92                        ),
93                    }
94                }
95            }
96            Err(error) => push_error(&mut result, format!("{}: {error}", path.display())),
97        }
98    }
99
100    result.files_touched = touched.len();
101    result.facts_extracted = result.facts.len();
102    result
103}
104
105pub(crate) fn read_json_file(source: ImportSource, path: &Path) -> ImportResult {
106    let mut result = ImportResult {
107        sessions_found: 1,
108        ..ImportResult::default()
109    };
110    let mut touched = HashSet::new();
111    let mut seen = HashSet::new();
112    let session = session_id(source, path);
113
114    match std::fs::read_to_string(path) {
115        Ok(content) => match serde_json::from_str::<Value>(&content) {
116            Ok(value) => process_value(
117                source,
118                &session,
119                &value,
120                &mut result,
121                &mut touched,
122                &mut seen,
123            ),
124            Err(error) => push_error(
125                &mut result,
126                format!("{}: invalid JSON: {error}", path.display()),
127            ),
128        },
129        Err(error) => push_error(&mut result, format!("{}: {error}", path.display())),
130    }
131
132    result.files_touched = touched.len();
133    result.facts_extracted = result.facts.len();
134    result
135}
136
137pub(crate) fn process_value(
138    source: ImportSource,
139    session: &str,
140    value: &Value,
141    result: &mut ImportResult,
142    touched: &mut HashSet<String>,
143    seen: &mut HashSet<(String, String)>,
144) {
145    let mut paths = Vec::new();
146    collect_file_paths(value, &mut paths);
147    for path in paths {
148        if touched.insert(path.clone()) {
149            push_fact(
150                result,
151                seen,
152                source,
153                session,
154                "imported-observation",
155                format!("Touched file: {path}"),
156                0.6,
157            );
158        }
159    }
160
161    let mut strings = Vec::new();
162    collect_strings(value, &mut strings);
163    let assistant = contains_assistant_message(value);
164    for text in strings {
165        if assistant {
166            for decision in matching_snippets(&text, is_decision) {
167                push_fact(
168                    result,
169                    seen,
170                    source,
171                    session,
172                    "imported-decision",
173                    decision,
174                    0.65,
175                );
176            }
177        }
178        for error in matching_snippets(&text, is_error) {
179            push_fact(
180                result,
181                seen,
182                source,
183                session,
184                "imported-observation",
185                format!("Observed error: {error}"),
186                0.55,
187            );
188        }
189    }
190}
191
192pub(crate) fn finish_result(result: &mut ImportResult, touched: &HashSet<String>) {
193    result.files_touched = touched.len();
194    result.facts_extracted = result.facts.len();
195}
196
197pub(crate) fn push_error(result: &mut ImportResult, error: String) {
198    if result.errors.len() < MAX_ERRORS {
199        result.errors.push(error);
200    }
201}
202
203pub(crate) fn session_id(source: ImportSource, path: &Path) -> String {
204    let name = path
205        .file_name()
206        .and_then(|name| name.to_str())
207        .unwrap_or("unknown-session");
208    format!("{}:{name}", source.as_str())
209}
210
211fn push_fact(
212    result: &mut ImportResult,
213    seen: &mut HashSet<(String, String)>,
214    source: ImportSource,
215    session: &str,
216    category: &str,
217    value: String,
218    confidence: f32,
219) {
220    let value = truncate(value);
221    if value.is_empty() || !seen.insert((category.to_owned(), value.clone())) {
222        return;
223    }
224
225    let now = Utc::now();
226    result.facts.push(KnowledgeFact {
227        category: category.to_owned(),
228        key: String::new(),
229        value,
230        source_session: session.to_owned(),
231        confidence,
232        created_at: now,
233        last_confirmed: now,
234        retrieval_count: 0,
235        last_retrieved: None,
236        valid_from: None,
237        valid_until: None,
238        supersedes: None,
239        confirmation_count: 0,
240        feedback_up: 0,
241        feedback_down: 0,
242        last_feedback: None,
243        privacy: Default::default(),
244        sensitivity: Default::default(),
245        imported_from: Some(source.as_str().to_owned()),
246        archetype: Default::default(),
247        fidelity: None,
248        revision_count: 0,
249    });
250}
251
252fn collect_file_paths(value: &Value, out: &mut Vec<String>) {
253    match value {
254        Value::Array(values) => {
255            for value in values {
256                collect_file_paths(value, out);
257            }
258        }
259        Value::Object(map) => {
260            for (key, value) in map {
261                if matches!(
262                    key.as_str(),
263                    "file_path" | "filePath" | "path" | "filename" | "file_name"
264                ) {
265                    if let Some(path) = value
266                        .as_str()
267                        .map(str::trim)
268                        .filter(|path| !path.is_empty())
269                    {
270                        out.push(path.to_owned());
271                    }
272                }
273                collect_file_paths(value, out);
274            }
275        }
276        _ => {}
277    }
278}
279
280fn collect_strings(value: &Value, out: &mut Vec<String>) {
281    match value {
282        Value::String(text) => out.push(text.to_owned()),
283        Value::Array(values) => {
284            for value in values {
285                collect_strings(value, out);
286            }
287        }
288        Value::Object(map) => {
289            for value in map.values() {
290                collect_strings(value, out);
291            }
292        }
293        _ => {}
294    }
295}
296
297fn contains_assistant_message(value: &Value) -> bool {
298    match value {
299        Value::Array(values) => values.iter().any(contains_assistant_message),
300        Value::Object(map) => {
301            map.get("role").and_then(Value::as_str) == Some("assistant")
302                || matches!(
303                    map.get("type").and_then(Value::as_str),
304                    Some("assistant" | "assistant_message")
305                )
306                || map.values().any(contains_assistant_message)
307        }
308        _ => false,
309    }
310}
311
312fn matching_snippets(text: &str, predicate: fn(&str) -> bool) -> Vec<String> {
313    text.split(['\n', '.', '!', '?'])
314        .map(str::trim)
315        .filter(|snippet| snippet.len() >= 4 && predicate(snippet))
316        .map(str::to_owned)
317        .collect()
318}
319
320fn is_decision(text: &str) -> bool {
321    let text = text.to_ascii_lowercase();
322    [
323        "decision",
324        "decided",
325        "we chose",
326        "i chose",
327        "chosen",
328        "will use",
329        "we'll use",
330        "we will use",
331        "going with",
332        "approach is",
333    ]
334    .iter()
335    .any(|marker| text.contains(marker))
336}
337
338fn is_error(text: &str) -> bool {
339    let text = text.to_ascii_lowercase();
340    [
341        "error",
342        "failed",
343        "failure",
344        "panic",
345        "unable to",
346        "cannot ",
347        "can't ",
348    ]
349    .iter()
350    .any(|marker| text.contains(marker))
351}
352
353fn truncate(mut value: String) -> String {
354    value.truncate(MAX_FACT_VALUE_CHARS);
355    value.trim().to_owned()
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn extracts_touches_decisions_and_errors() {
364        let value: Value = serde_json::json!({
365            "role": "assistant",
366            "content": "We decided to use a cache. Build failed because input is invalid.",
367            "tool_input": { "file_path": "rust/src/lib.rs" }
368        });
369        let mut result = ImportResult::default();
370        let mut touched = HashSet::new();
371        let mut seen = HashSet::new();
372
373        process_value(
374            ImportSource::Codex,
375            "codex:test",
376            &value,
377            &mut result,
378            &mut touched,
379            &mut seen,
380        );
381        finish_result(&mut result, &touched);
382
383        assert_eq!(result.files_touched, 1);
384        assert!(
385            result
386                .facts
387                .iter()
388                .any(|fact| fact.category == "imported-decision")
389        );
390        assert!(
391            result
392                .facts
393                .iter()
394                .any(|fact| fact.value.starts_with("Observed error:"))
395        );
396    }
397}