lean-ctx 3.9.17

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::io::{self, IsTerminal, Write};

const LOGO: [&str; 6] = [
    r"  ██╗     ███████╗ █████╗ ███╗   ██╗     ██████╗████████╗██╗  ██╗",
    r"  ██║     ██╔════╝██╔══██╗████╗  ██║    ██╔════╝╚══██╔══╝╚██╗██╔╝",
    r"  ██║     █████╗  ███████║██╔██╗ ██║    ██║        ██║    ╚███╔╝ ",
    r"  ██║     ██╔══╝  ██╔══██║██║╚██╗██║    ██║        ██║    ██╔██╗ ",
    r"  ███████╗███████╗██║  ██║██║ ╚████║    ╚██████╗   ██║   ██╔╝ ██╗",
    r"  ╚══════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═══╝     ╚═════╝   ╚═╝   ╚═╝  ╚═╝",
];

const TAGLINE: &str = "Context Runtime for AI Agents";

pub fn print_logo_animated() {
    let cfg = crate::core::config::Config::load();
    let t = crate::core::theme::load_theme(&cfg.theme);
    print_logo_animated_themed(&t);
}

pub fn print_logo_animated_themed(t: &crate::core::theme::Theme) {
    if crate::core::theme::no_color() {
        print_logo_plain();
        return;
    }
    if !io::stdout().is_terminal() {
        print_logo_themed_static(t);
        return;
    }

    let mut stdout = io::stdout();
    let frames = 28;
    let frame_ms = 45;
    let top_padding = 2;

    let _ = writeln!(stdout);
    let _ = writeln!(stdout);

    for frame in 0..frames {
        if frame > 0 {
            print!("\x1b[{}A", LOGO.len() + 2 + top_padding);
            for _ in 0..top_padding {
                let _ = writeln!(stdout);
            }
        }

        let wave_offset = frame as f64 / frames as f64;

        for (i, line) in LOGO.iter().enumerate() {
            let chars: Vec<char> = line.chars().collect();
            let max_j = chars.len().max(1) as f64;
            let mut buf = String::with_capacity(chars.len() * 20);

            for (j, ch) in chars.iter().enumerate() {
                if *ch == ' ' {
                    buf.push(' ');
                    continue;
                }
                let pos = j as f64 / max_j + i as f64 * 0.15;
                let blend = ((pos + wave_offset * 2.0) * std::f64::consts::PI)
                    .sin()
                    .mul_add(0.5, 0.5);
                let c = t.primary.lerp(&t.secondary, blend);
                buf.push_str(&c.fg());
                buf.push(*ch);
            }
            buf.push_str("\x1b[0m");
            let _ = writeln!(stdout, "{buf}");
        }

        let tag_blend = ((wave_offset * 2.0 + 1.0) * std::f64::consts::PI)
            .sin()
            .mul_add(0.5, 0.5);
        let tag_color = t.muted.lerp(&t.accent, tag_blend * 0.5);
        let _ = writeln!(stdout, "{}             {TAGLINE}\x1b[0m", tag_color.fg());
        let _ = writeln!(stdout);

        let _ = stdout.flush();
        std::thread::sleep(std::time::Duration::from_millis(frame_ms));
    }

    print!("\x1b[{}A", LOGO.len() + 2 + top_padding);
    print_logo_themed_static(t);
}

pub fn print_logo_static() {
    let cfg = crate::core::config::Config::load();
    let t = crate::core::theme::load_theme(&cfg.theme);
    print_logo_themed_static(&t);
}

fn print_logo_themed_static(t: &crate::core::theme::Theme) {
    if crate::core::theme::no_color() {
        print_logo_plain();
        return;
    }
    let mut stdout = io::stdout();

    let _ = writeln!(stdout);
    let _ = writeln!(stdout);

    for (i, line) in LOGO.iter().enumerate() {
        let chars: Vec<char> = line.chars().collect();
        let mut buf = String::with_capacity(chars.len() * 20);

        for (j, ch) in chars.iter().enumerate() {
            if *ch == ' ' {
                buf.push(' ');
                continue;
            }
            let progress = if chars.len() > 1 {
                j as f64 / (chars.len() - 1) as f64
            } else {
                0.5
            };
            let row_t = i as f64 / (LOGO.len() - 1).max(1) as f64;
            let blend = (progress + row_t * 0.3).min(1.0);
            let c = t.primary.lerp(&t.secondary, blend);
            buf.push_str(&c.fg());
            buf.push(*ch);
        }
        buf.push_str("\x1b[0m");
        let _ = writeln!(stdout, "{buf}");
    }

    let _ = writeln!(stdout, "{}             {TAGLINE}\x1b[0m", t.muted.fg());
    let _ = writeln!(stdout);
    let _ = stdout.flush();
}

fn print_logo_plain() {
    println!();
    println!();
    for line in &LOGO {
        println!("{line}");
    }
    println!("             {TAGLINE}");
    println!();
}

#[allow(clippy::many_single_char_names)] // ANSI formatting: t=theme, r=reset, b=bold, d=dim
pub fn print_command_box() {
    use crate::core::theme;
    let cfg = crate::core::config::Config::load();
    let theme = theme::load_theme(&cfg.theme);
    let dim = theme::dim();
    let bold = theme::bold();
    let rst = theme::rst();
    let cmd = theme.accent.fg();
    let ok = theme.success.fg();
    let m = theme.muted.fg();

    println!("  {dim}┌─────────────────────────────────────────────────────────┐{rst}");
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx gain{rst}        {m}Token savings dashboard{rst}         {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx dashboard{rst}   {m}Web analytics (browser){rst}        {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx heatmap{rst}     {m}Project context heat map{rst}        {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx benchmark{rst}   {m}Test compression quality{rst}        {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx config{rst}      {m}Edit settings{rst}                   {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx doctor{rst}      {m}Verify installation{rst}             {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx update{rst}      {m}Self-update to latest{rst}           {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}LEAN_CTX_DISABLED=1{rst}  {m}Disable compression{rst}             {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx report-issue{rst} {m}Report a bug (auto-diagnostics){rst} {dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx contribute{rst}  {m}Share anonymized compression stats{rst}{dim}│{rst}"
    );
    println!(
        "  {dim}│{rst}  {cmd}{bold}lean-ctx uninstall{rst}   {m}Clean removal{rst}                   {dim}│{rst}"
    );
    println!("  {dim}└─────────────────────────────────────────────────────────┘{rst}");
    println!("  {ok}Ready!{rst} Your next AI command will be automatically optimized.");
    println!("  {dim}Docs: https://leanctx.com/docs{rst}");
    println!();
}

pub fn print_step_header(step: u8, total: u8, title: &str) {
    let dim = "\x1b[2m";
    let bold = "\x1b[1m";
    let cyan = "\x1b[36m";
    let rst = "\x1b[0m";
    println!();
    println!("  {cyan}{bold}[{step}/{total}]{rst} {bold}{title}{rst}");
    println!("  {dim}─────────────────────────────────────────────────────{rst}");
}

pub fn print_status_ok(msg: &str) {
    println!("  \x1b[32m✓\x1b[0m {msg}");
}

pub fn print_status_skip(msg: &str) {
    println!("  \x1b[2m○\x1b[0m \x1b[2m{msg}\x1b[0m");
}

pub fn print_status_new(msg: &str) {
    println!("  \x1b[1;32m✓\x1b[0m \x1b[1m{msg}\x1b[0m");
}

pub fn print_status_warn(msg: &str) {
    println!("  \x1b[33m⚠\x1b[0m {msg}");
}

pub fn spinner_tick(msg: &str, frame: usize) {
    let frames = ['', '', '', '', '', '', '', '', '', ''];
    let ch = frames[frame % frames.len()];
    print!("\r  \x1b[36m{ch}\x1b[0m {msg}");
    let _ = io::stdout().flush();
}

pub fn spinner_done(msg: &str) {
    print!("\r  \x1b[32m✓\x1b[0m {msg}\x1b[K\n");
    let _ = io::stdout().flush();
}

// ── Unified progress indicator (index builds, long CLI work) ──────────

/// Interior width of the progress bar (characters between `[` and `]`).
const PROGRESS_BAR_WIDTH: usize = 20;

/// Shared CLI progress renderer for measurable and indeterminate work.
///
/// * **Determinate** (`total > 0`): `label [=======>        ]  42%`
/// * **Indeterminate** (`total == 0`): bouncing arrow L↔R inside the bar
///
/// Renders on stderr so stdout stays free for machine-readable output.
/// Non-TTY: silent ticks; only \[`finish`\] prints a line.
#[derive(Debug)]
pub struct ProgressIndicator {
    label: String,
    done: u64,
    /// `0` → indeterminate (bouncing arrow).
    total: u64,
    frame: usize,
    tty: bool,
    finished: bool,
}

impl ProgressIndicator {
    /// Start a progress indicator with `label` (e.g. `"BM25"`, `"semantic"`).
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            done: 0,
            total: 0,
            frame: 0,
            tty: io::stderr().is_terminal(),
            finished: false,
        }
    }

    /// Change the stage label without finishing (shared indicator across phases).
    pub fn set_label(&mut self, label: impl Into<String>) {
        self.label = label.into();
    }

    /// Set determinate progress. `total == 0` switches to indeterminate.
    pub fn set(&mut self, done: u64, total: u64) {
        self.done = done;
        self.total = total;
    }

    /// Switch to indeterminate (infinite bouncing arrow).
    pub fn indeterminate(&mut self) {
        self.done = 0;
        self.total = 0;
    }

    /// Advance animation / redraw. Call ~10–20×/s while work runs.
    pub fn tick(&mut self) {
        if self.finished {
            return;
        }
        self.frame = self.frame.wrapping_add(1);
        if !self.tty {
            return;
        }
        let line = self.render_line();
        eprint!("\r{line}\x1b[K");
        let _ = io::stderr().flush();
    }

    /// Clear the bar and print a final success/status line.
    pub fn finish(&mut self, msg: &str) {
        if self.finished {
            return;
        }
        self.finished = true;
        if self.tty {
            eprint!("\r\x1b[K");
            let _ = io::stderr().flush();
        }
        eprintln!("{msg}");
    }

    /// Render the current bar line (no `\r`). Public for tests.
    pub fn render_line(&self) -> String {
        if self.total > 0 {
            Self::render_determinate(&self.label, self.done, self.total)
        } else {
            Self::render_indeterminate(&self.label, self.frame)
        }
    }

    fn render_determinate(label: &str, done: u64, total: u64) -> String {
        let total = total.max(1);
        let pct = ((done as f64 / total as f64) * 100.0).min(100.0).round() as u32;
        let filled = (((done as f64 / total as f64) * PROGRESS_BAR_WIDTH as f64).round() as usize)
            .min(PROGRESS_BAR_WIDTH);

        let mut bar = String::with_capacity(PROGRESS_BAR_WIDTH);
        for i in 0..PROGRESS_BAR_WIDTH {
            if filled == 0 {
                bar.push(' ');
            } else if i + 1 < filled {
                bar.push('=');
            } else if i + 1 == filled {
                bar.push('');
            } else {
                bar.push(' ');
            }
        }
        format!("  {label} [{bar}] {pct:>3}%")
    }

    fn render_indeterminate(label: &str, frame: usize) -> String {
        let max = PROGRESS_BAR_WIDTH.saturating_sub(1).max(1);
        let cycle = max * 2;
        let t = frame % cycle;
        let (pos, arrow) = if t <= max {
            (t, '')
        } else {
            (cycle - t, '')
        };
        let mut bar: Vec<char> = vec![' '; PROGRESS_BAR_WIDTH];
        let idx = pos.min(PROGRESS_BAR_WIDTH.saturating_sub(1));
        bar[idx] = arrow;
        let bar: String = bar.into_iter().collect();
        format!("  {label} [{bar}]")
    }
}

/// Animated dashboard intro: logo wave, then KPI count-up, then section-by-section reveal.
/// `header_box` is the pre-rendered KPI box (with placeholder values for frame 0).
/// `kpi_values` are (final_value, width) for the 4 KPI counters.
/// `sections` are the remaining dashboard sections to reveal sequentially.
pub fn animate_dashboard_intro(
    t: &crate::core::theme::Theme,
    kpi_box_builder: &dyn Fn(&[String]) -> String,
    kpi_final: &[(u64, f64, u64, f64)], // (tokens, pct, commands, usd)
    sections: &[String],
) {
    use std::io::Write;
    let is_tty = std::io::stdout().is_terminal();
    if crate::core::theme::no_color() || !is_tty {
        if let &[(tokens, pct, commands, usd)] = kpi_final {
            let kw = 14;
            let vals = [
                crate::core::theme::animate_countup(tokens, kw)
                    .pop()
                    .unwrap_or_default(),
                crate::core::theme::animate_countup_pct(pct, kw)
                    .pop()
                    .unwrap_or_default(),
                crate::core::theme::animate_countup(commands, kw)
                    .pop()
                    .unwrap_or_default(),
                crate::core::theme::animate_countup_usd(usd, kw)
                    .pop()
                    .unwrap_or_default(),
            ];
            println!("{}", kpi_box_builder(&vals));
        }
        for s in sections {
            println!("{s}");
        }
        return;
    }

    print_logo_animated_themed(t);

    let mut stdout = std::io::stdout();
    let frames = 11;
    let frame_ms = 70;

    if let &[(tokens, pct, commands, usd)] = kpi_final {
        let kw = 14;
        let tok_frames = crate::core::theme::animate_countup(tokens, kw);
        let pct_frames = crate::core::theme::animate_countup_pct(pct, kw);
        let cmd_frames = crate::core::theme::animate_countup(commands, kw);
        let usd_frames = crate::core::theme::animate_countup_usd(usd, kw);

        let mut last_line_count = 0usize;
        for f in 0..frames {
            if last_line_count > 0 {
                print!("\x1b[{last_line_count}A\x1b[J");
            }
            let vals = [
                tok_frames[f].clone(),
                pct_frames[f].clone(),
                cmd_frames[f].clone(),
                usd_frames[f].clone(),
            ];
            let box_str = kpi_box_builder(&vals);
            last_line_count = box_str.lines().count();
            print!("{box_str}");
            let _ = stdout.flush();
            std::thread::sleep(std::time::Duration::from_millis(frame_ms));
        }
    }

    for s in sections {
        let _ = writeln!(stdout, "{s}");
        let _ = stdout.flush();
        std::thread::sleep(std::time::Duration::from_millis(60));
    }
}

pub fn print_setup_header() {
    let dim = "\x1b[2m";
    let bold = "\x1b[1m";
    let green = "\x1b[32m";
    let rst = "\x1b[0m";
    println!();
    println!("  {dim}╭──────────────────────────────────────────╮{rst}");
    println!(
        "  {dim}{rst}  {green}{bold}◆ lean-ctx setup{rst}                         {dim}{rst}"
    );
    println!("  {dim}{rst}  {dim}Configuring your development environment{rst} {dim}{rst}");
    println!("  {dim}╰──────────────────────────────────────────╯{rst}");
    println!();
}

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

    #[test]
    fn determinate_includes_arrow_and_percent() {
        let line = ProgressIndicator::render_determinate("BM25", 50, 100);
        assert!(line.contains("BM25"), "{line}");
        assert!(line.contains(''), "{line}");
        assert!(line.contains("50%"), "{line}");
        assert!(line.contains('['), "{line}");
    }

    #[test]
    fn determinate_full_is_100() {
        let line = ProgressIndicator::render_determinate("semantic", 10, 10);
        assert!(line.contains("100%"), "{line}");
        assert!(line.contains(''), "{line}");
    }

    #[test]
    fn indeterminate_bounces_left_and_right() {
        let right = ProgressIndicator::render_indeterminate("graph", 0);
        assert!(right.contains(''), "{right}");
        assert!(!right.contains('%'), "{right}");

        let max = PROGRESS_BAR_WIDTH.saturating_sub(1).max(1);
        let left = ProgressIndicator::render_indeterminate("graph", max + 1);
        assert!(left.contains(''), "{left}");
    }

    #[test]
    fn set_and_indeterminate_toggle() {
        let mut p = ProgressIndicator::new("BM25");
        p.tty = false;
        p.set(2, 8);
        assert!(p.render_line().contains("25%"));
        p.indeterminate();
        assert!(!p.render_line().contains('%'));
    }
}