lean-ctx 3.6.3

Context Runtime for AI Agents with CCP. 51 MCP tools, 10 read modes, 60+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, 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
use std::path::Path;

use crate::core::compressor;
use crate::core::deps as dep_extract;
use crate::core::entropy;
use crate::core::io_boundary;
use crate::core::patterns::deps_cmd;
use crate::core::protocol;
use crate::core::roles;
use crate::core::signatures;

fn resolve_cli_path(raw: &str) -> String {
    if let Ok(abs) = std::path::Path::new(raw).canonicalize() {
        return abs.to_string_lossy().to_string();
    }
    if Path::new(raw).is_relative() {
        if let Ok(cwd) = std::env::current_dir() {
            return cwd.join(raw).to_string_lossy().into_owned();
        }
    }
    raw.to_string()
}
use crate::core::tokens::count_tokens;

use super::common::print_savings;

pub fn cmd_read(args: &[String]) {
    if args.is_empty() {
        eprintln!(
            "Usage: lean-ctx read <file> [--mode auto|full|map|signatures|aggressive|entropy] [--fresh]"
        );
        std::process::exit(1);
    }

    let raw_path = &args[0];
    let path = if Path::new(raw_path).is_relative() {
        std::env::current_dir().ok().map_or_else(
            || raw_path.clone(),
            |cwd| cwd.join(raw_path).to_string_lossy().into_owned(),
        )
    } else {
        raw_path.clone()
    };
    let path = path.as_str();
    let mode = args
        .iter()
        .position(|a| a == "--mode" || a == "-m")
        .and_then(|i| args.get(i + 1))
        .map_or("auto", std::string::String::as_str);
    let force_fresh = args.iter().any(|a| a == "--fresh" || a == "--no-cache");

    let short = protocol::shorten_path(path);

    // Apply the same secret-path policy in CLI mode as in MCP tools.
    // Default is warn; enforce depends on active role/policy.
    if let Ok(abs) = std::fs::canonicalize(path) {
        match io_boundary::check_secret_path_for_tool("cli_read", &abs) {
            Ok(Some(w)) => eprintln!("{w}"),
            Ok(None) => {}
            Err(e) => {
                eprintln!("{e}");
                std::process::exit(1);
            }
        }
    } else {
        // Best-effort: still check the raw path string.
        let raw = std::path::Path::new(path);
        match io_boundary::check_secret_path_for_tool("cli_read", raw) {
            Ok(Some(w)) => eprintln!("{w}"),
            Ok(None) => {}
            Err(e) => {
                eprintln!("{e}");
                std::process::exit(1);
            }
        }
    }

    #[cfg(unix)]
    {
        #[cfg(unix)]
        if let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
            "ctx_read",
            Some(serde_json::json!({
                "path": path,
                "mode": mode,
                "fresh": force_fresh,
            })),
        ) {
            let filtered = super::common::filter_daemon_output(&out);
            if !filtered.trim().is_empty() {
                println!("{filtered}");
                return;
            }
        }
    }
    super::common::daemon_fallback_hint();

    if !force_fresh && mode == "full" {
        use crate::core::cli_cache::{self, CacheResult};
        match cli_cache::check_and_read(path) {
            CacheResult::Hit { entry, file_ref } => {
                let msg = cli_cache::format_hit(&entry, &file_ref, &short);
                println!("{msg}");
                let sent = count_tokens(&msg);
                super::common::cli_track_read_cached(path, "full", entry.original_tokens, sent);
                return;
            }
            CacheResult::Miss { content } if content.is_empty() => {
                eprintln!("Error: could not read {path}");
                std::process::exit(1);
            }
            CacheResult::Miss { content } => {
                let line_count = content.lines().count();
                println!("{short} [{line_count}L]");
                println!("{content}");
                let tok = count_tokens(&content);
                super::common::cli_track_read(path, "full", tok, tok);
                return;
            }
        }
    }

    let content = match crate::tools::ctx_read::read_file_lossy(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    };

    let ext = Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    let line_count = content.lines().count();
    let original_tokens = count_tokens(&content);

    let mode = if mode == "auto" {
        if crate::tools::ctx_read::is_instruction_file(path) {
            "full".to_string()
        } else {
            let sig = crate::core::mode_predictor::FileSignature::from_path(path, original_tokens);
            let predictor = crate::core::mode_predictor::ModePredictor::new();
            predictor
                .predict_best_mode(&sig)
                .unwrap_or_else(|| "full".to_string())
        }
    } else if mode != "full" && crate::tools::ctx_read::is_instruction_file(path) {
        "full".to_string()
    } else {
        mode.to_string()
    };
    let mode = mode.as_str();

    match mode {
        "map" => {
            let sigs = signatures::extract_signatures(&content, ext);
            let dep_info = dep_extract::extract_deps(&content, ext);

            let mut output_buf = format!("{short} [{line_count}L]");
            if !dep_info.imports.is_empty() {
                output_buf.push_str(&format!("\n  deps: {}", dep_info.imports.join(", ")));
            }
            if !dep_info.exports.is_empty() {
                output_buf.push_str(&format!("\n  exports: {}", dep_info.exports.join(", ")));
            }
            let key_sigs: Vec<_> = sigs
                .iter()
                .filter(|s| s.is_exported || s.indent == 0)
                .collect();
            if !key_sigs.is_empty() {
                output_buf.push_str("\n  API:");
                for sig in &key_sigs {
                    output_buf.push_str(&format!("\n    {}", sig.to_compact()));
                }
            }
            println!("{output_buf}");
            let sent = count_tokens(&output_buf);
            print_savings(original_tokens, sent);
            super::common::cli_track_read(path, "map", original_tokens, sent);
        }
        "signatures" => {
            let sigs = signatures::extract_signatures(&content, ext);
            let mut output_buf = format!("{short} [{line_count}L]");
            for sig in &sigs {
                output_buf.push_str(&format!("\n{}", sig.to_compact()));
            }
            println!("{output_buf}");
            let sent = count_tokens(&output_buf);
            print_savings(original_tokens, sent);
            super::common::cli_track_read(path, "signatures", original_tokens, sent);
        }
        "aggressive" => {
            let compressed = compressor::aggressive_compress(&content, Some(ext));
            println!("{short} [{line_count}L]");
            println!("{compressed}");
            let sent = count_tokens(&compressed);
            print_savings(original_tokens, sent);
            super::common::cli_track_read(path, "aggressive", original_tokens, sent);
        }
        "entropy" => {
            let result = entropy::entropy_compress(&content);
            let avg_h = entropy::analyze_entropy(&content).avg_entropy;
            println!("{short} [{line_count}L] (HÌ„={avg_h:.1})");
            for tech in &result.techniques {
                println!("{tech}");
            }
            println!("{}", result.output);
            let sent = count_tokens(&result.output);
            print_savings(original_tokens, sent);
            super::common::cli_track_read(path, "entropy", original_tokens, sent);
        }
        _ => {
            let mut output = format!("{short} [{line_count}L]\n{content}");
            let config = crate::core::config::Config::load();
            let level = crate::core::config::CompressionLevel::effective(&config);
            if level.is_active() {
                let terse_result = crate::core::terse::pipeline::compress(&output, &level, None);
                if terse_result.quality_passed && terse_result.savings_pct >= 3.0 {
                    output = terse_result.output;
                }
            }
            println!("{output}");
            let sent = count_tokens(&output);
            super::common::cli_track_read(path, "full", original_tokens, sent);
        }
    }
}

pub fn cmd_diff(args: &[String]) {
    if args.len() < 2 {
        eprintln!("Usage: lean-ctx diff <file1> <file2>");
        std::process::exit(1);
    }

    let content1 = match crate::tools::ctx_read::read_file_lossy(&args[0]) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error reading {}: {e}", args[0]);
            std::process::exit(1);
        }
    };

    let content2 = match crate::tools::ctx_read::read_file_lossy(&args[1]) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error reading {}: {e}", args[1]);
            std::process::exit(1);
        }
    };

    let diff = compressor::diff_content(&content1, &content2);
    let original = count_tokens(&content1) + count_tokens(&content2);
    let sent = count_tokens(&diff);

    println!(
        "diff {} {}",
        protocol::shorten_path(&args[0]),
        protocol::shorten_path(&args[1])
    );
    println!("{diff}");
    print_savings(original, sent);
    crate::core::stats::record("cli_diff", original, sent);
}

pub fn cmd_grep(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: lean-ctx grep <pattern> [path]");
        std::process::exit(1);
    }

    let pattern = &args[0];
    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
    let abs_path = resolve_cli_path(raw_path);
    let path = abs_path.as_str();

    #[cfg(unix)]
    {
        #[cfg(unix)]
        if let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
            "ctx_search",
            Some(serde_json::json!({
                "pattern": pattern,
                "path": path,
            })),
        ) {
            let out = super::common::filter_daemon_output(&out);
            println!("{out}");
            if out.trim_start().starts_with("0 matches") {
                std::process::exit(1);
            }
            return;
        }
    }
    super::common::daemon_fallback_hint();

    let (out, original) = crate::tools::ctx_search::handle(
        pattern,
        path,
        None,
        20,
        crate::tools::CrpMode::effective(),
        true,
        roles::active_role().io.allow_secret_paths,
    );
    println!("{out}");
    super::common::cli_track_search(original, count_tokens(&out));
    if original == 0 && out.trim_start().starts_with("0 matches") {
        std::process::exit(1);
    }
}

pub fn cmd_find(args: &[String]) {
    if args.is_empty() {
        eprintln!("Usage: lean-ctx find <pattern> [path]");
        std::process::exit(1);
    }

    let raw_pattern = &args[0];
    let path = args.get(1).map_or(".", std::string::String::as_str);

    let is_glob = raw_pattern.contains('*') || raw_pattern.contains('?');
    let glob_matcher = if is_glob {
        glob::Pattern::new(&raw_pattern.to_lowercase()).ok()
    } else {
        None
    };
    let substring = raw_pattern.to_lowercase();

    let mut found = false;
    for entry in ignore::WalkBuilder::new(path)
        .hidden(true)
        .git_ignore(true)
        .git_global(true)
        .git_exclude(true)
        .max_depth(Some(10))
        .build()
        .flatten()
    {
        let name = entry.file_name().to_string_lossy().to_lowercase();
        let matches = if let Some(ref g) = glob_matcher {
            g.matches(&name)
        } else {
            name.contains(&substring)
        };
        if matches {
            println!("{}", entry.path().display());
            found = true;
        }
    }

    crate::core::stats::record("cli_find", 0, 0);

    if !found {
        std::process::exit(1);
    }
}

pub fn cmd_ls(args: &[String]) {
    let mut raw_path = ".";
    let mut depth = 3usize;
    let mut show_hidden = false;
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        if arg == "--depth" {
            i += 1;
            if let Some(d) = args.get(i).and_then(|s| s.parse::<usize>().ok()) {
                depth = d.min(10);
            }
        } else if arg == "--all" || arg == "-a" {
            show_hidden = true;
        } else if arg.starts_with('-') {
            eprintln!("Error: lean-ctx ls does not support flag '{arg}'.\n");
            eprintln!("lean-ctx ls is a compressed directory tree viewer for AI context, not a drop-in ls replacement.");
            eprintln!("The shell hook (lean-ctx -t ls {arg} ...) passes flags to system ls transparently.\n");
            eprintln!("Usage: lean-ctx ls [path] [--depth N] [--all]");
            std::process::exit(1);
        } else {
            raw_path = arg;
        }
        i += 1;
    }

    let abs_path = resolve_cli_path(raw_path);
    let path = abs_path.as_str();

    #[cfg(unix)]
    {
        #[cfg(unix)]
        if let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
            "ctx_tree",
            Some(serde_json::json!({
                "path": path,
                "depth": depth,
                "show_hidden": show_hidden,
            })),
        ) {
            println!("{}", super::common::filter_daemon_output(&out));
            return;
        }
    }
    super::common::daemon_fallback_hint();

    let (out, _original) = crate::tools::ctx_tree::handle(path, depth, show_hidden);
    println!("{out}");
    super::common::cli_track_tree(0, count_tokens(&out));
}

pub fn cmd_deps(args: &[String]) {
    let path = args.first().map_or(".", std::string::String::as_str);

    if let Some(result) = deps_cmd::detect_and_compress(path) {
        println!("{result}");
        crate::core::stats::record("cli_deps", 0, 0);
    } else {
        eprintln!("No dependency file found in {path}");
        std::process::exit(1);
    }
}