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        origin: crate::core::knowledge::FactOrigin::Unverified,
231        category: category.to_owned(),
232        key: String::new(),
233        value,
234        source_session: session.to_owned(),
235        confidence,
236        created_at: now,
237        last_confirmed: now,
238        retrieval_count: 0,
239        last_retrieved: None,
240        valid_from: None,
241        valid_until: None,
242        supersedes: None,
243        confirmation_count: 0,
244        feedback_up: 0,
245        feedback_down: 0,
246        last_feedback: None,
247        privacy: Default::default(),
248        sensitivity: Default::default(),
249        imported_from: Some(source.as_str().to_owned()),
250        archetype: Default::default(),
251        fidelity: None,
252        revision_count: 0,
253    });
254}
255
256fn collect_file_paths(value: &Value, out: &mut Vec<String>) {
257    match value {
258        Value::Array(values) => {
259            for value in values {
260                collect_file_paths(value, out);
261            }
262        }
263        Value::Object(map) => {
264            for (key, value) in map {
265                if matches!(
266                    key.as_str(),
267                    "file_path" | "filePath" | "path" | "filename" | "file_name"
268                ) {
269                    if let Some(path) = value
270                        .as_str()
271                        .map(str::trim)
272                        .filter(|path| !path.is_empty())
273                    {
274                        out.push(path.to_owned());
275                    }
276                }
277                collect_file_paths(value, out);
278            }
279        }
280        _ => {}
281    }
282}
283
284fn collect_strings(value: &Value, out: &mut Vec<String>) {
285    match value {
286        Value::String(text) => out.push(text.to_owned()),
287        Value::Array(values) => {
288            for value in values {
289                collect_strings(value, out);
290            }
291        }
292        Value::Object(map) => {
293            for value in map.values() {
294                collect_strings(value, out);
295            }
296        }
297        _ => {}
298    }
299}
300
301fn contains_assistant_message(value: &Value) -> bool {
302    match value {
303        Value::Array(values) => values.iter().any(contains_assistant_message),
304        Value::Object(map) => {
305            map.get("role").and_then(Value::as_str) == Some("assistant")
306                || matches!(
307                    map.get("type").and_then(Value::as_str),
308                    Some("assistant" | "assistant_message")
309                )
310                || map.values().any(contains_assistant_message)
311        }
312        _ => false,
313    }
314}
315
316fn matching_snippets(text: &str, predicate: fn(&str) -> bool) -> Vec<String> {
317    text.split(['\n', '.', '!', '?'])
318        .map(str::trim)
319        .filter(|snippet| snippet.len() >= 4 && predicate(snippet))
320        .map(str::to_owned)
321        .collect()
322}
323
324fn is_decision(text: &str) -> bool {
325    let text = text.to_ascii_lowercase();
326    [
327        "decision",
328        "decided",
329        "we chose",
330        "i chose",
331        "chosen",
332        "will use",
333        "we'll use",
334        "we will use",
335        "going with",
336        "approach is",
337    ]
338    .iter()
339    .any(|marker| text.contains(marker))
340}
341
342fn is_error(text: &str) -> bool {
343    let text = text.to_ascii_lowercase();
344    [
345        "error",
346        "failed",
347        "failure",
348        "panic",
349        "unable to",
350        "cannot ",
351        "can't ",
352    ]
353    .iter()
354    .any(|marker| text.contains(marker))
355}
356
357fn truncate(value: &str) -> String {
358    // The first char boundary *at or past* the cap can land one byte over it:
359    // with 2-byte characters starting at an odd offset the boundaries are
360    // 11, 13, … 499, 501, so a 500-byte cap yielded a 501-byte slice. Take the
361    // last boundary at or below the cap instead — the same idiom already used
362    // in `ctx_search` and `ctx_preload`.
363    value[..value.floor_char_boundary(MAX_FACT_VALUE_CHARS)]
364        .trim()
365        .to_owned()
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    #[test]
373    fn truncates_multibyte_facts_without_panicking() {
374        let value = format!("We decided {}", "é".repeat(300));
375        let truncated = truncate(&value);
376        assert!(truncated.len() <= MAX_FACT_VALUE_CHARS);
377        assert!(truncated.is_char_boundary(truncated.len()));
378    }
379
380    #[test]
381    fn extracts_touches_decisions_and_errors() {
382        let value: Value = serde_json::json!({
383            "role": "assistant",
384            "content": "We decided to use a cache. Build failed because input is invalid.",
385            "tool_input": { "file_path": "rust/src/lib.rs" }
386        });
387        let mut result = ImportResult::default();
388        let mut touched = HashSet::new();
389        let mut seen = HashSet::new();
390
391        process_value(
392            ImportSource::Codex,
393            "codex:test",
394            &value,
395            &mut result,
396            &mut touched,
397            &mut seen,
398        );
399        finish_result(&mut result, &touched);
400
401        assert_eq!(result.files_touched, 1);
402        assert!(
403            result
404                .facts
405                .iter()
406                .any(|fact| fact.category == "imported-decision")
407        );
408        assert!(
409            result
410                .facts
411                .iter()
412                .any(|fact| fact.value.starts_with("Observed error:"))
413        );
414    }
415}