lean-ctx 3.9.14

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
489
490
491
use std::cell::RefCell;
use std::sync::atomic::{AtomicUsize, Ordering};

static SESSION_ORIGINAL: AtomicUsize = AtomicUsize::new(0);
static SESSION_SAVED: AtomicUsize = AtomicUsize::new(0);
static SESSION_CALL_COUNT: AtomicUsize = AtomicUsize::new(0);

thread_local! {
    static CURRENT_MODE: RefCell<Option<String>> = const { RefCell::new(None) };
    static CURRENT_DETAIL: RefCell<Option<String>> = const { RefCell::new(None) };
}

pub(crate) struct SavingsInfo<'a> {
    pub original: usize,
    pub compressed: usize,
    pub mode: Option<&'a str>,
    pub detail: Option<&'a str>,
}

pub(crate) struct ModeGuard;

impl ModeGuard {
    pub(crate) fn new(mode: &str) -> Self {
        CURRENT_MODE.with(|m| *m.borrow_mut() = Some(mode.to_string()));
        Self
    }

    pub(crate) fn with_detail(mode: &str, detail: &str) -> Self {
        CURRENT_MODE.with(|m| *m.borrow_mut() = Some(mode.to_string()));
        CURRENT_DETAIL.with(|d| *d.borrow_mut() = Some(detail.to_string()));
        Self
    }
}

impl Drop for ModeGuard {
    fn drop(&mut self) {
        // Must be panic-free: a `borrow_mut` panic while the thread is already
        // unwinding another panic would escalate to a process abort (#378). Use
        // `try_borrow_mut` and silently skip if the slot is somehow in use.
        CURRENT_MODE.with(|m| {
            if let Ok(mut slot) = m.try_borrow_mut() {
                *slot = None;
            }
        });
        CURRENT_DETAIL.with(|d| {
            if let Ok(mut slot) = d.try_borrow_mut() {
                *slot = None;
            }
        });
    }
}

fn current_mode() -> Option<String> {
    CURRENT_MODE.with(|m| m.borrow().clone())
}

fn current_detail() -> Option<String> {
    CURRENT_DETAIL.with(|d| d.borrow().clone())
}

pub(crate) fn record_savings(original: usize, saved: usize) {
    SESSION_ORIGINAL.fetch_add(original, Ordering::Relaxed);
    SESSION_SAVED.fetch_add(saved, Ordering::Relaxed);
    SESSION_CALL_COUNT.fetch_add(1, Ordering::Relaxed);
}

pub(crate) fn session_totals() -> (usize, usize, usize) {
    (
        SESSION_ORIGINAL.load(Ordering::Relaxed),
        SESSION_SAVED.load(Ordering::Relaxed),
        SESSION_CALL_COUNT.load(Ordering::Relaxed),
    )
}

pub(crate) fn reset_session() {
    SESSION_ORIGINAL.store(0, Ordering::Relaxed);
    SESSION_SAVED.store(0, Ordering::Relaxed);
    SESSION_CALL_COUNT.store(0, Ordering::Relaxed);
}

fn format_number(n: usize) -> String {
    if n >= 1_000_000 {
        let m = n as f64 / 1_000_000.0;
        format!("{m:.1}M")
    } else if n >= 10_000 {
        let k = n as f64 / 1_000.0;
        format!("{k:.1}k")
    } else if n >= 1_000 {
        let whole = n / 1_000;
        format!("{whole},{:03}", n % 1_000)
    } else {
        n.to_string()
    }
}

fn is_explicitly_enabled() -> bool {
    matches!(std::env::var("LEAN_CTX_SHOW_SAVINGS"), Ok(v) if v.trim() == "1")
}

fn is_ultra_suppressed() -> bool {
    if is_explicitly_enabled() {
        return false;
    }
    let level = super::config::CompressionLevel::effective(&super::config::Config::load());
    matches!(level, super::config::CompressionLevel::Max)
}

pub(crate) fn format_footer(info: &SavingsInfo<'_>) -> String {
    if !super::protocol::savings_footer_visible() {
        return String::new();
    }
    if is_ultra_suppressed() {
        return String::new();
    }
    format_footer_inner(info)
}

fn format_footer_inner(info: &SavingsInfo<'_>) -> String {
    if info.original == 0 {
        return String::new();
    }
    let saved = info.original.saturating_sub(info.compressed);
    if saved == 0 {
        return String::new();
    }
    let pct = (saved as f64 / info.original as f64 * 100.0).round() as usize;

    let annotation = super::config::CompressionAnnotation::effective();
    let threshold = super::config::Config::load().annotation_threshold_pct as usize;

    if matches!(annotation, super::config::CompressionAnnotation::None) {
        record_savings(info.original, saved);
        return String::new();
    }

    if pct < threshold {
        record_savings(info.original, saved);
        return String::new();
    }

    let orig_str = format_number(info.original);
    let comp_str = format_number(info.compressed);

    let pct_display = match annotation {
        super::config::CompressionAnnotation::Quantized => {
            let quantized = ((pct + 5) / 10) * 10;
            format!("~{quantized}")
        }
        _ => pct.to_string(),
    };

    let mut parts = vec![format!(
        "{orig_str} \u{2192} {comp_str} tok (\u{2193}{pct_display}%)"
    )];

    if let Some(mode) = info.mode {
        parts.push(format!("mode: {mode}"));
    }
    if let Some(detail) = info.detail {
        parts.push(detail.to_string());
    }

    record_savings(info.original, saved);

    let body = parts.join(" | ");
    format!("\u{2500}\u{2500}\u{2500} {body} \u{2500}\u{2500}\u{2500}")
}

pub(crate) fn format_footer_basic(original: usize, compressed: usize) -> String {
    let mode = current_mode();
    let detail = current_detail();
    format_footer(&SavingsInfo {
        original,
        compressed,
        mode: mode.as_deref(),
        detail: detail.as_deref(),
    })
}

pub(crate) fn append_footer(output: &str, info: &SavingsInfo<'_>) -> String {
    let footer = format_footer(info);
    if footer.is_empty() {
        output.to_string()
    } else {
        format!("{output}\n{footer}")
    }
}

pub(crate) fn append_footer_basic(output: &str, original: usize, compressed: usize) -> String {
    let footer = format_footer_basic(original, compressed);
    if footer.is_empty() {
        output.to_string()
    } else {
        format!("{output}\n{footer}")
    }
}

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

    #[test]
    fn format_number_small() {
        assert_eq!(format_number(42), "42");
        assert_eq!(format_number(999), "999");
    }

    #[test]
    fn format_number_thousands() {
        assert_eq!(format_number(1_000), "1,000");
        assert_eq!(format_number(4_200), "4,200");
        assert_eq!(format_number(9_999), "9,999");
    }

    #[test]
    fn format_number_large() {
        assert_eq!(format_number(12_300), "12.3k");
        assert_eq!(format_number(45_200), "45.2k");
    }

    #[test]
    fn format_number_millions() {
        assert_eq!(format_number(1_500_000), "1.5M");
    }

    #[test]
    fn basic_footer_format() {
        let _lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "full");

        let info = SavingsInfo {
            original: 4200,
            compressed: 840,
            mode: Some("map"),
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(
            result.starts_with("\u{2500}\u{2500}\u{2500} "),
            "should start with box-drawing: {result}"
        );
        assert!(
            result.ends_with(" \u{2500}\u{2500}\u{2500}"),
            "should end with box-drawing: {result}"
        );
        assert!(
            result.contains("4,200"),
            "should contain formatted original: {result}"
        );
        assert!(
            result.contains("840"),
            "should contain compressed: {result}"
        );
        assert!(
            result.contains("\u{2193}80%"),
            "should contain percentage: {result}"
        );
        assert!(
            result.contains("mode: map"),
            "should contain mode: {result}"
        );

        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
    }

    #[test]
    fn footer_with_detail() {
        let _lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "full");

        let info = SavingsInfo {
            original: 12300,
            compressed: 620,
            mode: None,
            detail: Some("3 patterns matched"),
        };
        let result = format_footer_inner(&info);
        assert!(
            result.contains("3 patterns matched"),
            "detail missing: {result}"
        );
        assert!(
            result.contains("12.3k"),
            "should format large numbers: {result}"
        );

        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
    }

    #[test]
    fn footer_returns_empty_when_no_savings() {
        let result = format_footer_inner(&SavingsInfo {
            original: 100,
            compressed: 100,
            mode: None,
            detail: None,
        });
        assert!(
            result.is_empty(),
            "should be empty with 0 savings: {result}"
        );
    }

    #[test]
    fn footer_returns_empty_when_zero_original() {
        let result = format_footer_inner(&SavingsInfo {
            original: 0,
            compressed: 0,
            mode: None,
            detail: None,
        });
        assert!(
            result.is_empty(),
            "should be empty with 0 original: {result}"
        );
    }

    #[test]
    fn visibility_gated_tests() {
        let _lock = crate::core::data_dir::test_env_lock();

        crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "0");
        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "never");
        let result = format_footer_basic(100, 50);
        assert!(
            result.is_empty(),
            "should be empty with never mode: {result}"
        );

        let result = append_footer_basic("hello", 100, 50);
        assert_eq!(result, "hello");

        crate::test_env::set_var("LEAN_CTX_SHOW_SAVINGS", "1");
        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "always");
        crate::test_env::remove_var("LEAN_CTX_QUIET");
        super::super::protocol::set_mcp_context(false);

        let result = append_footer_basic("hello", 100, 50);
        assert!(
            result.starts_with("hello\n"),
            "should start with original: {result}"
        );
        assert!(
            result.contains("\u{2500}\u{2500}\u{2500}"),
            "should contain box-drawing: {result}"
        );

        // Restore ALL touched env — leaking LEAN_CTX_SAVINGS_FOOTER=always
        // made footers visible in unrelated tests (GL #556 flakiness).
        crate::test_env::remove_var("LEAN_CTX_SHOW_SAVINGS");
        crate::test_env::remove_var("LEAN_CTX_SAVINGS_FOOTER");
    }

    #[test]
    fn session_accumulator_tracks() {
        reset_session();
        record_savings(100, 50);
        record_savings(200, 80);
        let (orig, saved, calls) = session_totals();
        assert_eq!(orig, 300);
        assert_eq!(saved, 130);
        assert_eq!(calls, 2);
        reset_session();
    }

    #[test]
    fn session_counter_removed_from_footer() {
        let _lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "full");

        reset_session();
        for _ in 0..20 {
            record_savings(100, 50);
        }
        let info = SavingsInfo {
            original: 100,
            compressed: 50,
            mode: None,
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(
            !result.contains("session:"),
            "session counter must not appear in footer (breaks prefix stability): {result}"
        );
        reset_session();
        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
    }

    #[test]
    fn quantized_mode_rounds_to_nearest_10() {
        let _lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "quantized");

        let info = SavingsInfo {
            original: 100,
            compressed: 58,
            mode: None,
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(
            result.contains("~40%"),
            "42% should quantize to ~40%: {result}"
        );

        let info = SavingsInfo {
            original: 100,
            compressed: 13,
            mode: None,
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(
            result.contains("~90%"),
            "87% should quantize to ~90%: {result}"
        );

        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
    }

    #[test]
    fn none_mode_suppresses_all_annotations() {
        let _lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "none");

        let info = SavingsInfo {
            original: 100,
            compressed: 20,
            mode: Some("map"),
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(result.is_empty(), "none mode should suppress all: {result}");

        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
    }

    #[test]
    fn threshold_suppresses_small_savings() {
        let _lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_COMPRESSION_ANNOTATION", "full");

        let info = SavingsInfo {
            original: 100,
            compressed: 97,
            mode: None,
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(
            result.is_empty(),
            "3% savings (below default 5% threshold) should be suppressed: {result}"
        );

        let info = SavingsInfo {
            original: 100,
            compressed: 90,
            mode: None,
            detail: None,
        };
        let result = format_footer_inner(&info);
        assert!(
            result.contains("10%"),
            "10% savings (above 5% threshold) should appear: {result}"
        );

        crate::test_env::remove_var("LEAN_CTX_COMPRESSION_ANNOTATION");
    }

    #[test]
    fn mode_guard_sets_and_clears() {
        assert!(current_mode().is_none());
        {
            let _guard = ModeGuard::new("map");
            assert_eq!(current_mode().as_deref(), Some("map"));
        }
        assert!(current_mode().is_none());
    }

    #[test]
    fn mode_guard_with_detail() {
        {
            let _guard = ModeGuard::with_detail("shell", "3 patterns");
            assert_eq!(current_mode().as_deref(), Some("shell"));
            assert_eq!(current_detail().as_deref(), Some("3 patterns"));
        }
        assert!(current_mode().is_none());
        assert!(current_detail().is_none());
    }
}