lean-ctx 3.5.5

Context Runtime for AI Agents with CCP. 57 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing + diaries, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24 AI tools. Reduces LLM token consumption by up to 99%.
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
415
416
417
418
419
420
421
422
423
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use serde::Serialize;

use crate::core::artifacts::ResolvedArtifact;
use crate::core::tokens::count_tokens;

const DEFAULT_IMPACT_DEPTH: usize = 3;
const MAX_CHANGED_FILES_SHOWN: usize = 200;
const MAX_DIFF_BYTES: usize = 1_048_576; // 1 MiB

#[derive(Debug, Clone, Serialize)]
struct ChangedFile {
    path: String,
    status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    old_path: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
struct ImpactEntry {
    file: String,
    affected_files: Vec<String>,
}

#[derive(Debug, Serialize)]
struct PrPackJson {
    kind: &'static str,
    project_root: String,
    base: String,
    impact_depth: usize,
    changed_files: Vec<ChangedFile>,
    related_tests: Vec<String>,
    impacts: Vec<ImpactEntry>,
    context_artifacts: Vec<ResolvedArtifact>,
    warnings: Vec<String>,
    tokens: u64,
}

pub fn handle(
    action: &str,
    project_root: &str,
    base: Option<&str>,
    format: Option<&str>,
    depth: Option<usize>,
    diff: Option<&str>,
) -> String {
    match action {
        "pr" => handle_pr(project_root, base, format, depth, diff),
        _ => "Unknown action. Use: pr".to_string(),
    }
}

fn handle_pr(
    project_root: &str,
    base: Option<&str>,
    format: Option<&str>,
    depth: Option<usize>,
    diff: Option<&str>,
) -> String {
    let root = project_root.to_string();
    let base = base.map_or_else(
        || detect_default_base(&root).unwrap_or_else(|| "HEAD~1".to_string()),
        ToString::to_string,
    );
    let impact_depth = depth.unwrap_or(DEFAULT_IMPACT_DEPTH).max(1);

    let mut warnings: Vec<String> = Vec::new();
    let mut changed = if let Some(d) = diff {
        if d.len() > MAX_DIFF_BYTES {
            warnings.push(format!(
                "Diff input too large ({} bytes, limit {MAX_DIFF_BYTES}). Truncating at char boundary.",
                d.len()
            ));
            let mut boundary = MAX_DIFF_BYTES;
            while boundary > 0 && !d.is_char_boundary(boundary) {
                boundary -= 1;
            }
            let truncated = &d[..boundary];
            parse_changes_from_input(truncated)
        } else {
            parse_changes_from_input(d)
        }
    } else {
        git_diff_name_status(&root, &base, &mut warnings)
    };

    if changed.len() > MAX_CHANGED_FILES_SHOWN {
        warnings.push(format!(
            "Too many changed files ({}). Truncating to {MAX_CHANGED_FILES_SHOWN}.",
            changed.len()
        ));
        changed.truncate(MAX_CHANGED_FILES_SHOWN);
    }

    let related_tests = collect_related_tests(&changed, &root);
    let impacts = collect_impacts(&changed, &root, impact_depth);
    let context_artifacts = collect_relevant_artifacts(&changed, &root, &mut warnings);

    let format = format.unwrap_or("markdown");
    match format {
        "json" => {
            let mut json = PrPackJson {
                kind: "leanctx.pr_pack",
                project_root: root,
                base,
                impact_depth,
                changed_files: changed,
                related_tests,
                impacts,
                context_artifacts,
                warnings,
                tokens: 0,
            };
            match serde_json::to_string_pretty(&json) {
                Ok(s) => {
                    json.tokens = count_tokens(&s) as u64;
                    serde_json::to_string_pretty(&json)
                        .unwrap_or_else(|e| format!("{{\"error\": \"serialization failed: {e}\"}}"))
                }
                Err(e) => format!("{{\"error\": \"serialization failed: {e}\"}}"),
            }
        }
        _ => format_markdown(
            project_root,
            &base,
            impact_depth,
            &changed,
            &related_tests,
            &impacts,
            &context_artifacts,
            &warnings,
        ),
    }
}

fn format_markdown(
    project_root: &str,
    base: &str,
    impact_depth: usize,
    changed: &[ChangedFile],
    related_tests: &[String],
    impacts: &[ImpactEntry],
    artifacts: &[ResolvedArtifact],
    warnings: &[String],
) -> String {
    let mut out = String::new();
    out.push_str("# PR Context Pack\n\n");
    out.push_str(&format!("- Project root: `{project_root}`\n"));
    out.push_str(&format!("- Base: `{base}`\n"));
    out.push_str(&format!("- Impact depth: `{impact_depth}`\n\n"));

    if !warnings.is_empty() {
        out.push_str("## Warnings\n");
        for w in warnings {
            out.push_str(&format!("- {w}\n"));
        }
        out.push('\n');
    }

    out.push_str("## Changed files\n");
    for c in changed {
        match &c.old_path {
            Some(old) => out.push_str(&format!("- `{}` ({}) ← `{old}`\n", c.path, c.status)),
            None => out.push_str(&format!("- `{}` ({})\n", c.path, c.status)),
        }
    }
    out.push('\n');

    if !artifacts.is_empty() {
        out.push_str("## Context artifacts\n");
        for a in artifacts {
            let kind = if a.is_dir { "dir" } else { "file" };
            let exists = if a.exists { "exists" } else { "missing" };
            out.push_str(&format!(
                "- `{}` ({kind}, {exists}) — {}\n",
                a.path, a.description
            ));
        }
        out.push('\n');
    }

    if !related_tests.is_empty() {
        out.push_str("## Related tests\n");
        for t in related_tests {
            out.push_str(&format!("- `{t}`\n"));
        }
        out.push('\n');
    }

    if !impacts.is_empty() {
        out.push_str("## Impact (property graph)\n");
        for imp in impacts {
            out.push_str(&format!(
                "- `{}`: {} affected files\n",
                imp.file,
                imp.affected_files.len()
            ));
            for f in imp.affected_files.iter().take(30) {
                out.push_str(&format!("  - `{f}`\n"));
            }
            if imp.affected_files.len() > 30 {
                out.push_str("  - ...\n");
            }
        }
        out.push('\n');
    }

    let tokens = count_tokens(&out);
    out.push_str(&format!("[ctx_pack pr: {tokens} tok]\n"));
    out
}

fn collect_related_tests(changed: &[ChangedFile], project_root: &str) -> Vec<String> {
    let mut all: BTreeSet<String> = BTreeSet::new();
    for c in changed {
        for t in crate::tools::ctx_review::find_related_tests(&c.path, project_root) {
            all.insert(t);
        }
    }
    all.into_iter().collect()
}

fn collect_impacts(changed: &[ChangedFile], project_root: &str, depth: usize) -> Vec<ImpactEntry> {
    let mut out = Vec::new();
    for c in changed {
        if c.status == "D" {
            continue;
        }
        let raw = crate::tools::ctx_impact::handle(
            "analyze",
            Some(&c.path),
            project_root,
            Some(depth),
            None,
        );
        let affected = parse_ctx_impact_output(&raw);
        out.push(ImpactEntry {
            file: c.path.clone(),
            affected_files: affected,
        });
    }
    out
}

fn parse_ctx_impact_output(raw: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for line in raw.lines() {
        let l = line.trim_end();
        if let Some(rest) = l.strip_prefix("  ") {
            let item = rest.trim().to_string();
            if item.starts_with("...") {
                continue;
            }
            if !item.is_empty() {
                out.push(item);
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

fn collect_relevant_artifacts(
    changed: &[ChangedFile],
    project_root: &str,
    warnings: &mut Vec<String>,
) -> Vec<ResolvedArtifact> {
    let root = Path::new(project_root);
    let resolved = crate::core::artifacts::load_resolved(root);
    warnings.extend(resolved.warnings);

    let mut out: Vec<ResolvedArtifact> = Vec::new();
    for a in resolved.artifacts {
        if !a.exists {
            continue;
        }
        if is_artifact_relevant(&a, changed) {
            out.push(a);
        }
    }
    out.sort_by(|a, b| a.path.cmp(&b.path).then_with(|| a.name.cmp(&b.name)));
    out
}

fn is_artifact_relevant(a: &ResolvedArtifact, changed: &[ChangedFile]) -> bool {
    if a.path.is_empty() {
        return false;
    }
    if a.is_dir {
        let prefix = if a.path.ends_with('/') {
            a.path.clone()
        } else {
            format!("{}/", a.path)
        };
        return changed.iter().any(|c| c.path.starts_with(&prefix));
    }
    changed.iter().any(|c| c.path == a.path)
}

fn parse_changes_from_input(input: &str) -> Vec<ChangedFile> {
    if input.contains("diff --git") || input.contains("\n+++ ") || input.starts_with("diff --git") {
        let paths = parse_unified_diff_paths(input);
        let mut out = Vec::new();
        for p in paths {
            out.push(ChangedFile {
                path: p,
                status: "M".to_string(),
                old_path: None,
            });
        }
        return dedup_changes(out);
    }

    let mut out = Vec::new();
    for line in input.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let parts: Vec<&str> = trimmed.split_whitespace().collect();
        if parts.len() >= 2 {
            let status = parts[0].to_string();
            if status.starts_with('R') && parts.len() >= 3 {
                out.push(ChangedFile {
                    path: parts[2].to_string(),
                    status: "R".to_string(),
                    old_path: Some(parts[1].to_string()),
                });
            } else {
                out.push(ChangedFile {
                    path: parts[1].to_string(),
                    status: status.chars().next().unwrap_or('M').to_string(),
                    old_path: None,
                });
            }
        } else {
            out.push(ChangedFile {
                path: trimmed.to_string(),
                status: "M".to_string(),
                old_path: None,
            });
        }
    }
    dedup_changes(out)
}

fn parse_unified_diff_paths(diff: &str) -> Vec<String> {
    let mut out: BTreeSet<String> = BTreeSet::new();
    for line in diff.lines() {
        if let Some(rest) = line.strip_prefix("+++ b/") {
            let p = rest.trim();
            if !p.is_empty() && p != "/dev/null" {
                out.insert(p.to_string());
            }
        }
        if let Some(rest) = line.strip_prefix("--- a/") {
            let p = rest.trim();
            if !p.is_empty() && p != "/dev/null" {
                out.insert(p.to_string());
            }
        }
    }
    out.into_iter().collect()
}

fn git_diff_name_status(
    project_root: &str,
    base: &str,
    warnings: &mut Vec<String>,
) -> Vec<ChangedFile> {
    let out = std::process::Command::new("git")
        .args(["diff", "--name-status", &format!("{base}...HEAD")])
        .current_dir(project_root)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .output();
    let Ok(o) = out else {
        warnings.push("Failed to execute git diff".to_string());
        return Vec::new();
    };
    if !o.status.success() {
        let stderr = String::from_utf8_lossy(&o.stderr);
        warnings.push(format!("git diff failed: {}", stderr.trim()));
        return Vec::new();
    }
    let s = String::from_utf8_lossy(&o.stdout);
    parse_changes_from_input(&s)
}

fn detect_default_base(project_root: &str) -> Option<String> {
    for cand in ["origin/main", "origin/master", "main", "master"] {
        let ok = std::process::Command::new("git")
            .args(["rev-parse", "--verify", cand])
            .current_dir(project_root)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .ok()
            .is_some_and(|s| s.success());
        if ok {
            return Some(cand.to_string());
        }
    }
    None
}

fn dedup_changes(mut changes: Vec<ChangedFile>) -> Vec<ChangedFile> {
    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
    let mut out: Vec<ChangedFile> = Vec::new();
    for c in changes.drain(..) {
        let key = c.path.clone();
        if let Some(i) = seen.get(&key) {
            out[*i] = c;
            continue;
        }
        seen.insert(key, out.len());
        out.push(c);
    }
    out
}