lean-ctx 3.9.19

Context Runtime for AI Agents with CCP. 79 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%.
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
use md5::{Digest, Md5};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};

const CACHE_TTL_SECS: u64 = 300;
const MAX_ENTRIES: usize = 200;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct CliCacheEntry {
    pub path: String,
    pub hash: String,
    pub line_count: usize,
    pub original_tokens: usize,
    pub timestamp: u64,
    pub read_count: u32,
    /// Process-lifetime nonce scoping a hit to the process that actually
    /// delivered the file's full content. A fresh process carries a different
    /// nonce, so it always misses and receives content instead of a
    /// `cached … [NL]` stub (#1459). `serde(default)` keeps older on-disk
    /// entries (written before this field existed) parseable; they simply never
    /// match and are overwritten on the next read.
    #[serde(default)]
    pub nonce: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub(crate) struct CliCacheStore {
    pub entries: HashMap<String, CliCacheEntry>,
    pub total_hits: u64,
    pub total_reads: u64,
}

pub(crate) enum CacheResult {
    Hit {
        entry: CliCacheEntry,
        file_ref: String,
    },
    Miss {
        content: String,
    },
}

fn cache_dir() -> Option<PathBuf> {
    crate::core::data_dir::lean_ctx_data_dir()
        .ok()
        .map(|d| d.join("cli-cache"))
}

fn cache_file() -> Option<PathBuf> {
    cache_dir().map(|d| d.join("cache.json"))
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// A value unique to this process for its whole lifetime, generated once and
/// reused. Scopes cache hits to the process that first delivered the content:
/// a one-shot `lean-ctx read` invocation is its own process, so a subsequent
/// invocation (new nonce) can never be served a stub from a previous run (#1459).
fn process_nonce() -> &'static str {
    static NONCE: OnceLock<String> = OnceLock::new();
    NONCE
        .get_or_init(|| {
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos();
            format!("{}-{}", std::process::id(), nanos)
        })
        .as_str()
}

fn compute_md5(content: &str) -> String {
    let mut hasher = Md5::new();
    hasher.update(content.as_bytes());
    crate::core::agent_identity::hex_encode(&hasher.finalize())
}

fn normalize_key(path: &str) -> String {
    crate::core::pathutil::normalize_tool_path(path)
}

fn load_store() -> CliCacheStore {
    let Some(path) = cache_file() else {
        return CliCacheStore::default();
    };
    match std::fs::read_to_string(&path) {
        Ok(data) => serde_json::from_str(&data).unwrap_or_default(),
        Err(_) => CliCacheStore::default(),
    }
}

fn save_store(store: &CliCacheStore) {
    let Some(dir) = cache_dir() else { return };
    let _ = std::fs::create_dir_all(&dir);
    let path = dir.join("cache.json");
    if let Ok(data) = serde_json::to_string(store) {
        let _ = std::fs::write(path, data);
    }
}

fn file_ref(key: &str, store: &CliCacheStore) -> String {
    let keys: Vec<&String> = store.entries.keys().collect();
    let idx = keys
        .iter()
        .position(|k| k.as_str() == key)
        .unwrap_or(store.entries.len());
    format!("F{}", idx + 1)
}

pub(crate) fn check_and_read(path: &str) -> CacheResult {
    let Ok(content) = crate::core::io_boundary::read_file_lossy(path) else {
        return CacheResult::Miss {
            content: String::new(),
        };
    };

    let key = normalize_key(path);
    let hash = compute_md5(&content);
    let now = now_secs();
    let mut store = load_store();

    store.total_reads += 1;

    if let Some(entry) = store.entries.get_mut(&key)
        && entry.hash == hash
        && entry.nonce == process_nonce()
        && (now - entry.timestamp) < CACHE_TTL_SECS
    {
        entry.read_count += 1;
        entry.timestamp = now;
        store.total_hits += 1;
        let result = CacheResult::Hit {
            entry: entry.clone(),
            file_ref: file_ref(&key, &store),
        };
        save_store(&store);
        return result;
    }

    let line_count = content.lines().count();
    let original_tokens = crate::core::tokens::count_tokens(&content);

    let entry = CliCacheEntry {
        path: key.clone(),
        hash,
        line_count,
        original_tokens,
        timestamp: now,
        read_count: 1,
        nonce: process_nonce().to_string(),
    };
    store.entries.insert(key, entry);

    evict_stale(&mut store, now);

    save_store(&store);
    CacheResult::Miss { content }
}

pub(crate) fn invalidate(path: &str) {
    let key = normalize_key(path);
    let mut store = load_store();
    store.entries.remove(&key);
    save_store(&store);
}

pub(crate) fn clear() -> usize {
    let mut store = load_store();
    let count = store.entries.len();
    store.entries.clear();
    save_store(&store);
    count
}

pub(crate) fn clear_project(project_root: &str) -> usize {
    let mut store = load_store();
    let prefix = normalize_key(project_root);
    let before = store.entries.len();
    store
        .entries
        .retain(|key, entry| !key.starts_with(&prefix) && !entry.path.starts_with(&prefix));
    let removed = before - store.entries.len();
    save_store(&store);
    removed
}

pub(crate) fn stats() -> (u64, u64, usize) {
    let store = load_store();
    (store.total_hits, store.total_reads, store.entries.len())
}

fn evict_stale(store: &mut CliCacheStore, now: u64) {
    store
        .entries
        .retain(|_, e| (now - e.timestamp) < CACHE_TTL_SECS);

    if store.entries.len() > MAX_ENTRIES {
        let mut entries: Vec<(String, u64)> = store
            .entries
            .iter()
            .map(|(k, e)| (k.clone(), e.timestamp))
            .collect();
        entries.sort_by_key(|(_, ts)| *ts);
        let to_remove = store.entries.len() - MAX_ENTRIES;
        for (key, _) in entries.into_iter().take(to_remove) {
            store.entries.remove(&key);
        }
    }
}

pub(crate) fn format_hit(entry: &CliCacheEntry, file_ref: &str, short_path: &str) -> String {
    if crate::core::protocol::savings_footer_visible() {
        format!(
            "{file_ref} cached {short_path} [{}L {}t] (read #{})",
            entry.line_count, entry.original_tokens, entry.read_count
        )
    } else {
        format!("cached {short_path} [{}L]", entry.line_count)
    }
}

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

    #[test]
    fn compute_md5_deterministic() {
        let h1 = compute_md5("test content");
        let h2 = compute_md5("test content");
        assert_eq!(h1, h2);
        assert_ne!(h1, compute_md5("different"));
    }

    #[test]
    fn evict_stale_removes_old_entries() {
        let mut store = CliCacheStore::default();
        store.entries.insert(
            "/old.rs".to_string(),
            CliCacheEntry {
                path: "/old.rs".to_string(),
                hash: "h1".into(),
                line_count: 10,
                original_tokens: 50,
                timestamp: 1000,
                read_count: 1,
                nonce: "n1".into(),
            },
        );
        store.entries.insert(
            "/new.rs".to_string(),
            CliCacheEntry {
                path: "/new.rs".to_string(),
                hash: "h2".into(),
                line_count: 20,
                original_tokens: 100,
                timestamp: now_secs(),
                read_count: 1,
                nonce: "n2".into(),
            },
        );

        evict_stale(&mut store, now_secs());
        assert!(!store.entries.contains_key("/old.rs"));
        assert!(store.entries.contains_key("/new.rs"));
    }

    #[test]
    fn evict_respects_max_entries() {
        let mut store = CliCacheStore::default();
        let now = now_secs();
        for i in 0..MAX_ENTRIES + 10 {
            store.entries.insert(
                format!("/file_{i}.rs"),
                CliCacheEntry {
                    path: format!("/file_{i}.rs"),
                    hash: format!("h{i}"),
                    line_count: 1,
                    original_tokens: 10,
                    timestamp: now - i as u64,
                    read_count: 1,
                    nonce: format!("n{i}"),
                },
            );
        }
        evict_stale(&mut store, now);
        assert!(store.entries.len() <= MAX_ENTRIES);
    }

    #[test]
    fn format_hit_output() {
        let _lock = crate::core::data_dir::test_env_lock();
        let entry = CliCacheEntry {
            path: "/test.rs".into(),
            hash: "abc".into(),
            line_count: 42,
            original_tokens: 500,
            timestamp: now_secs(),
            read_count: 3,
            nonce: "n".into(),
        };
        crate::test_env::set_var("LEAN_CTX_SAVINGS_FOOTER", "never");
        let output = format_hit(&entry, "F1", "test.rs");
        assert!(output.contains("cached test.rs"));
        assert!(output.contains("42L"));
        assert!(!output.contains("F1"));
        assert!(!output.contains("500t"));
        assert!(!output.contains("read #3"));
        crate::test_env::remove_var("LEAN_CTX_SAVINGS_FOOTER");
    }

    #[test]
    fn stats_returns_defaults_on_empty() {
        let s = CliCacheStore::default();
        assert_eq!(s.total_hits, 0);
        assert_eq!(s.total_reads, 0);
        assert!(s.entries.is_empty());
    }

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

        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let test_data_dir = std::env::temp_dir().join(format!("lean_ctx_cache_iso_{nanos}"));
        std::fs::create_dir_all(&test_data_dir).unwrap();
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", &test_data_dir);

        let tmp = test_data_dir.join("test_file.txt");
        std::fs::write(&tmp, "fn main() {}\n").unwrap();
        let path_str = tmp.to_str().unwrap();

        invalidate(path_str);

        let result = check_and_read(path_str);
        assert!(matches!(result, CacheResult::Miss { .. }));

        let result2 = check_and_read(path_str);
        assert!(matches!(result2, CacheResult::Hit { .. }));
        if let CacheResult::Hit { entry, .. } = result2 {
            assert_eq!(entry.line_count, 1);
            assert!(entry.read_count >= 2);
        }

        invalidate(path_str);
        let result3 = check_and_read(path_str);
        assert!(matches!(result3, CacheResult::Miss { .. }));

        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        let _ = std::fs::remove_dir_all(&test_data_dir);
    }

    #[test]
    fn cross_process_entry_is_not_served_as_hit() {
        // #1459: a persistent entry written by a *different* process (a foreign
        // nonce) must not be served as a `cached … [NL]` stub — the reader never
        // received the content, so it must miss and get the real bytes.
        let _lock = crate::core::data_dir::test_env_lock();

        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let test_data_dir = std::env::temp_dir().join(format!("lean_ctx_cache_xproc_{nanos}"));
        std::fs::create_dir_all(&test_data_dir).unwrap();
        crate::test_env::set_var("LEAN_CTX_DATA_DIR", &test_data_dir);

        let tmp = test_data_dir.join("test_file.txt");
        let content = "fn main() {}\n";
        std::fs::write(&tmp, content).unwrap();
        let path_str = tmp.to_str().unwrap();
        let key = normalize_key(path_str);

        // Simulate a prior process that cached this path under its own nonce.
        let mut store = load_store();
        store.entries.insert(
            key.clone(),
            CliCacheEntry {
                path: key,
                hash: compute_md5(content),
                line_count: 1,
                original_tokens: 4,
                timestamp: now_secs(),
                read_count: 1,
                nonce: "a-different-process".into(),
            },
        );
        save_store(&store);

        // A fresh process (different nonce) must miss and receive full content.
        let result = check_and_read(path_str);
        assert!(
            matches!(&result, CacheResult::Miss { content } if content == "fn main() {}\n"),
            "foreign-process cache entry must not be served as a hit"
        );

        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
        let _ = std::fs::remove_dir_all(&test_data_dir);
    }
}