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