lean-ctx 3.10.2

Local context engine, CLI, MCP server, and proxy for AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Import facts from local AI coding-session histories.

pub mod claude_code;
pub mod codex;
pub mod cursor;
pub mod opencode;

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use chrono::Utc;
use serde_json::Value;

use crate::core::knowledge::KnowledgeFact;

const MAX_FACT_VALUE_CHARS: usize = 500;
const MAX_ERRORS: usize = 100;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportSource {
    ClaudeCode,
    Codex,
    Cursor,
    OpenCode,
}

impl ImportSource {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ClaudeCode => "claude-code",
            Self::Codex => "codex",
            Self::Cursor => "cursor",
            Self::OpenCode => "opencode",
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct ImportResult {
    pub sessions_found: usize,
    pub facts_extracted: usize,
    pub files_touched: usize,
    pub errors: Vec<String>,
    /// Facts remain available to the CLI until it either persists or displays them.
    pub facts: Vec<KnowledgeFact>,
}

impl ImportResult {
    pub(crate) fn merge(&mut self, mut other: Self) {
        self.sessions_found += other.sessions_found;
        self.facts_extracted += other.facts_extracted;
        self.files_touched += other.files_touched;
        self.errors.append(&mut other.errors);
        self.facts.append(&mut other.facts);
    }
}

pub(crate) fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME").map(PathBuf::from)
}

pub(crate) fn read_jsonl_files(source: ImportSource, files: Vec<PathBuf>) -> ImportResult {
    let mut result = ImportResult {
        sessions_found: files.len(),
        ..ImportResult::default()
    };
    let mut touched = HashSet::new();
    let mut seen = HashSet::new();

    for path in files {
        let session = session_id(source, &path);
        match std::fs::read_to_string(&path) {
            Ok(content) => {
                for (line_number, line) in content.lines().enumerate() {
                    if line.trim().is_empty() {
                        continue;
                    }
                    match serde_json::from_str::<Value>(line) {
                        Ok(value) => process_value(
                            source,
                            &session,
                            &value,
                            &mut result,
                            &mut touched,
                            &mut seen,
                        ),
                        Err(error) => push_error(
                            &mut result,
                            format!(
                                "{}:{}: invalid JSONL: {error}",
                                path.display(),
                                line_number + 1
                            ),
                        ),
                    }
                }
            }
            Err(error) => push_error(&mut result, format!("{}: {error}", path.display())),
        }
    }

    result.files_touched = touched.len();
    result.facts_extracted = result.facts.len();
    result
}

pub(crate) fn read_json_file(source: ImportSource, path: &Path) -> ImportResult {
    let mut result = ImportResult {
        sessions_found: 1,
        ..ImportResult::default()
    };
    let mut touched = HashSet::new();
    let mut seen = HashSet::new();
    let session = session_id(source, path);

    match std::fs::read_to_string(path) {
        Ok(content) => match serde_json::from_str::<Value>(&content) {
            Ok(value) => process_value(
                source,
                &session,
                &value,
                &mut result,
                &mut touched,
                &mut seen,
            ),
            Err(error) => push_error(
                &mut result,
                format!("{}: invalid JSON: {error}", path.display()),
            ),
        },
        Err(error) => push_error(&mut result, format!("{}: {error}", path.display())),
    }

    result.files_touched = touched.len();
    result.facts_extracted = result.facts.len();
    result
}

pub(crate) fn process_value(
    source: ImportSource,
    session: &str,
    value: &Value,
    result: &mut ImportResult,
    touched: &mut HashSet<String>,
    seen: &mut HashSet<(String, String)>,
) {
    let mut paths = Vec::new();
    collect_file_paths(value, &mut paths);
    for path in paths {
        if touched.insert(path.clone()) {
            push_fact(
                result,
                seen,
                source,
                session,
                "imported-observation",
                &format!("Touched file: {path}"),
                0.6,
            );
        }
    }

    let mut strings = Vec::new();
    collect_strings(value, &mut strings);
    let assistant = contains_assistant_message(value);
    for text in strings {
        if assistant {
            for decision in matching_snippets(&text, is_decision) {
                push_fact(
                    result,
                    seen,
                    source,
                    session,
                    "imported-decision",
                    &decision,
                    0.65,
                );
            }
        }
        for error in matching_snippets(&text, is_error) {
            push_fact(
                result,
                seen,
                source,
                session,
                "imported-observation",
                &format!("Observed error: {error}"),
                0.55,
            );
        }
    }
}

pub(crate) fn finish_result(result: &mut ImportResult, touched: &HashSet<String>) {
    result.files_touched = touched.len();
    result.facts_extracted = result.facts.len();
}

pub(crate) fn push_error(result: &mut ImportResult, error: String) {
    if result.errors.len() < MAX_ERRORS {
        result.errors.push(error);
    }
}

pub(crate) fn session_id(source: ImportSource, path: &Path) -> String {
    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("unknown-session");
    format!("{}:{name}", source.as_str())
}

fn push_fact(
    result: &mut ImportResult,
    seen: &mut HashSet<(String, String)>,
    source: ImportSource,
    session: &str,
    category: &str,
    value: &str,
    confidence: f32,
) {
    let value = truncate(value);
    if value.is_empty() || !seen.insert((category.to_owned(), value.clone())) {
        return;
    }

    let now = Utc::now();
    result.facts.push(KnowledgeFact {
        category: category.to_owned(),
        key: String::new(),
        value,
        source_session: session.to_owned(),
        confidence,
        created_at: now,
        last_confirmed: now,
        retrieval_count: 0,
        last_retrieved: None,
        valid_from: None,
        valid_until: None,
        supersedes: None,
        confirmation_count: 0,
        feedback_up: 0,
        feedback_down: 0,
        last_feedback: None,
        privacy: Default::default(),
        sensitivity: Default::default(),
        imported_from: Some(source.as_str().to_owned()),
        archetype: Default::default(),
        fidelity: None,
        revision_count: 0,
    });
}

fn collect_file_paths(value: &Value, out: &mut Vec<String>) {
    match value {
        Value::Array(values) => {
            for value in values {
                collect_file_paths(value, out);
            }
        }
        Value::Object(map) => {
            for (key, value) in map {
                if matches!(
                    key.as_str(),
                    "file_path" | "filePath" | "path" | "filename" | "file_name"
                ) {
                    if let Some(path) = value
                        .as_str()
                        .map(str::trim)
                        .filter(|path| !path.is_empty())
                    {
                        out.push(path.to_owned());
                    }
                }
                collect_file_paths(value, out);
            }
        }
        _ => {}
    }
}

fn collect_strings(value: &Value, out: &mut Vec<String>) {
    match value {
        Value::String(text) => out.push(text.to_owned()),
        Value::Array(values) => {
            for value in values {
                collect_strings(value, out);
            }
        }
        Value::Object(map) => {
            for value in map.values() {
                collect_strings(value, out);
            }
        }
        _ => {}
    }
}

fn contains_assistant_message(value: &Value) -> bool {
    match value {
        Value::Array(values) => values.iter().any(contains_assistant_message),
        Value::Object(map) => {
            map.get("role").and_then(Value::as_str) == Some("assistant")
                || matches!(
                    map.get("type").and_then(Value::as_str),
                    Some("assistant" | "assistant_message")
                )
                || map.values().any(contains_assistant_message)
        }
        _ => false,
    }
}

fn matching_snippets(text: &str, predicate: fn(&str) -> bool) -> Vec<String> {
    text.split(['\n', '.', '!', '?'])
        .map(str::trim)
        .filter(|snippet| snippet.len() >= 4 && predicate(snippet))
        .map(str::to_owned)
        .collect()
}

fn is_decision(text: &str) -> bool {
    let text = text.to_ascii_lowercase();
    [
        "decision",
        "decided",
        "we chose",
        "i chose",
        "chosen",
        "will use",
        "we'll use",
        "we will use",
        "going with",
        "approach is",
    ]
    .iter()
    .any(|marker| text.contains(marker))
}

fn is_error(text: &str) -> bool {
    let text = text.to_ascii_lowercase();
    [
        "error",
        "failed",
        "failure",
        "panic",
        "unable to",
        "cannot ",
        "can't ",
    ]
    .iter()
    .any(|marker| text.contains(marker))
}

fn truncate(value: &str) -> String {
    // The first char boundary *at or past* the cap can land one byte over it:
    // with 2-byte characters starting at an odd offset the boundaries are
    // 11, 13, … 499, 501, so a 500-byte cap yielded a 501-byte slice. Take the
    // last boundary at or below the cap instead — the same idiom already used
    // in `ctx_search` and `ctx_preload`.
    value[..value.floor_char_boundary(MAX_FACT_VALUE_CHARS)]
        .trim()
        .to_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn truncates_multibyte_facts_without_panicking() {
        let value = format!("We decided {}", "é".repeat(300));
        let truncated = truncate(&value);
        assert!(truncated.len() <= MAX_FACT_VALUE_CHARS);
        assert!(truncated.is_char_boundary(truncated.len()));
    }

    #[test]
    fn extracts_touches_decisions_and_errors() {
        let value: Value = serde_json::json!({
            "role": "assistant",
            "content": "We decided to use a cache. Build failed because input is invalid.",
            "tool_input": { "file_path": "rust/src/lib.rs" }
        });
        let mut result = ImportResult::default();
        let mut touched = HashSet::new();
        let mut seen = HashSet::new();

        process_value(
            ImportSource::Codex,
            "codex:test",
            &value,
            &mut result,
            &mut touched,
            &mut seen,
        );
        finish_result(&mut result, &touched);

        assert_eq!(result.files_touched, 1);
        assert!(
            result
                .facts
                .iter()
                .any(|fact| fact.category == "imported-decision")
        );
        assert!(
            result
                .facts
                .iter()
                .any(|fact| fact.value.starts_with("Observed error:"))
        );
    }
}