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
//! Domain-specific abbreviation dictionaries for terse compression.
//!
//! Each dictionary provides whole-word-matching abbreviations for a specific
//! domain (git, cargo, npm, general). Unlike the legacy ABBREVIATIONS list
//! (18 blind substring replacements), these use word-boundary-aware matching.

/// A single abbreviation rule: replaces `long` with `short` at word boundaries.
pub struct Abbreviation {
    pub long: &'static str,
    pub short: &'static str,
}

/// Empty — all 60 single-English-word rules tokenize identically to their
/// abbreviations under BPE (1 tok -> 1 tok), so they saved zero tokens while
/// corrupting source code, file paths, and search results (#973, #980, #981).
/// Phrase-level rules (multi-word) are the ones that yield real savings and
/// live in the domain dictionaries (GIT, CARGO, NPM).
pub const GENERAL: &[Abbreviation] = &[];

pub const GIT: &[Abbreviation] = &[
    Abbreviation {
        long: "modified",
        short: "M",
    },
    Abbreviation {
        long: "deleted",
        short: "D",
    },
    Abbreviation {
        long: "untracked",
        short: "?",
    },
    Abbreviation {
        long: "renamed",
        short: "R",
    },
    Abbreviation {
        long: "copied",
        short: "C",
    },
    Abbreviation {
        long: "insertion",
        short: "+",
    },
    Abbreviation {
        long: "deletion",
        short: "-",
    },
    Abbreviation {
        long: "detached",
        short: "det",
    },
    Abbreviation {
        long: "conflict",
        short: "!!",
    },
    Abbreviation {
        long: "changes not staged for commit",
        short: "unstaged",
    },
    Abbreviation {
        long: "Changes to be committed",
        short: "staged",
    },
    Abbreviation {
        long: "nothing to commit, working tree clean",
        short: "clean",
    },
];

pub const CARGO: &[Abbreviation] = &[
    Abbreviation {
        long: "Compiling",
        short: "CC",
    },
    Abbreviation {
        long: "Downloading",
        short: "DL",
    },
    Abbreviation {
        long: "Finished",
        short: "OK",
    },
    Abbreviation {
        long: "warning",
        short: "W",
    },
    Abbreviation {
        long: "test result: ok",
        short: "PASS",
    },
    Abbreviation {
        long: "test result: FAILED",
        short: "FAIL",
    },
    Abbreviation {
        long: "running",
        short: "run",
    },
    Abbreviation {
        long: "Blocking waiting for file lock on package cache",
        short: "LOCK",
    },
    Abbreviation {
        long: "Updating crates.io index",
        short: "IDX",
    },
    Abbreviation {
        long: "target/debug",
        short: "t/d",
    },
    Abbreviation {
        long: "target/release",
        short: "t/r",
    },
];

pub const NPM: &[Abbreviation] = &[
    Abbreviation {
        long: "added",
        short: "+",
    },
    Abbreviation {
        long: "removed",
        short: "-",
    },
    Abbreviation {
        long: "node_modules",
        short: "n_m",
    },
    Abbreviation {
        long: "devDependencies",
        short: "devDeps",
    },
    Abbreviation {
        long: "peerDependencies",
        short: "peerDeps",
    },
    Abbreviation {
        long: "optionalDependencies",
        short: "optDeps",
    },
    Abbreviation {
        long: "npm warn",
        short: "W",
    },
    Abbreviation {
        long: "npm error",
        short: "E",
    },
];

/// Applies whole-word abbreviations from the given dictionaries to the text.
/// Uses a single scan: first checks which patterns exist, then applies only matches.
pub fn apply_dictionaries(text: &str, level: DictLevel) -> String {
    let dicts: Vec<&[Abbreviation]> = match level {
        DictLevel::General => vec![GENERAL],
        DictLevel::Full => vec![GENERAL, GIT, CARGO, NPM],
    };

    let mut result = text.to_string();
    for dict in dicts {
        for abbr in dict {
            result = replace_whole_word(&result, abbr.long, abbr.short);
        }
    }
    result
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DictLevel {
    General,
    Full,
}

fn is_word_boundary(b: u8) -> bool {
    !b.is_ascii_alphanumeric() && b != b'-' && b != b'_' && b != b'\'' && b != b'"'
}

/// #973: true when `[match_start..match_end)` sits inside a file-path token —
/// the surrounding whitespace-delimited word contains `/` or `\`.  Dictionary
/// substitutions inside paths emit non-existent paths (`environment.rs` →
/// `env.rs`).
fn is_inside_path(text: &[u8], match_start: usize, match_end: usize) -> bool {
    let token_start = text[..match_start]
        .iter()
        .rposition(u8::is_ascii_whitespace)
        .map_or(0, |i| i + 1);
    let token_end = text[match_end..]
        .iter()
        .position(u8::is_ascii_whitespace)
        .map_or(text.len(), |i| match_end + i);
    let token = &text[token_start..token_end];
    token.contains(&b'/') || token.contains(&b'\\')
}

/// Whole-word replacement — **case-sensitive**, path-aware, non-ASCII safe.
///
/// #981 fix: matching was case-insensitive, collapsing `context.Context` into
/// `ctx.ctx`.  Now matches the exact case of the pattern only.  All byte
/// offsets come from a single string (the original text), eliminating the
/// lowercased-copy divergence that panicked on non-ASCII input (ß→ss changes
/// byte length).
///
/// #973 fix: matches inside file-path tokens (containing `/` or `\`) are
/// skipped so `src/environment.rs` is never rewritten to `src/env.rs`.
pub(crate) fn replace_whole_word(text: &str, pattern: &str, replacement: &str) -> String {
    if pattern.is_empty() || !text.contains(pattern) {
        return text.to_string();
    }

    let bytes = text.as_bytes();
    let pat_len = pattern.len();
    let mut result = String::with_capacity(text.len());
    let mut start = 0;

    while let Some(pos) = text[start..].find(pattern) {
        let abs_pos = start + pos;
        let end_pos = abs_pos + pat_len;

        let before_ok = abs_pos == 0 || is_word_boundary(bytes[abs_pos - 1]);
        let after_ok = end_pos >= bytes.len() || is_word_boundary(bytes[end_pos]);

        result.push_str(&text[start..abs_pos]);

        if before_ok && after_ok && !is_inside_path(bytes, abs_pos, end_pos) {
            result.push_str(replacement);
        } else {
            result.push_str(&text[abs_pos..end_pos]);
        }
        start = end_pos;
    }
    result.push_str(&text[start..]);
    result
}

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

    #[test]
    fn whole_word_replaces_standalone() {
        let r = replace_whole_word("the function works", "function", "fn");
        assert_eq!(r, "the fn works");
    }

    #[test]
    fn whole_word_skips_substring() {
        let r = replace_whole_word("dysfunction", "function", "fn");
        assert_eq!(r, "dysfunction");
    }

    #[test]
    fn whole_word_at_start() {
        let r = replace_whole_word("function call", "function", "fn");
        assert_eq!(r, "fn call");
    }

    #[test]
    fn whole_word_at_end() {
        let r = replace_whole_word("call function", "function", "fn");
        assert_eq!(r, "call fn");
    }

    #[test]
    fn whole_word_with_punctuation() {
        let r = replace_whole_word("function(arg)", "function", "fn");
        assert_eq!(r, "fn(arg)");
    }

    // #981: case-sensitive matching — `Context` ≠ `context`.
    #[test]
    fn case_sensitive_preserves_different_casing() {
        assert_eq!(
            replace_whole_word("context.Context", "context", "ctx"),
            "ctx.Context",
            "only lowercase `context` should be replaced (#981)"
        );
    }

    // #981: non-ASCII must not panic.
    #[test]
    fn non_ascii_input_does_not_panic() {
        let r = replace_whole_word("die Größe der function", "function", "fn");
        assert_eq!(r, "die Größe der fn");
    }

    #[test]
    fn non_ascii_with_no_match_returns_unchanged() {
        let r = replace_whole_word("Ströme und Flüsse", "function", "fn");
        assert_eq!(r, "Ströme und Flüsse");
    }

    // #973: file paths must never be rewritten.
    #[test]
    fn path_words_are_never_abbreviated() {
        assert_eq!(
            replace_whole_word("src/environment.rs changed", "environment", "env"),
            "src/environment.rs changed",
            "words inside paths must be preserved (#973)"
        );
    }

    #[test]
    fn path_with_backslash_protected() {
        assert_eq!(
            replace_whole_word("src\\configuration\\mod.rs", "configuration", "cfg"),
            "src\\configuration\\mod.rs"
        );
    }

    #[test]
    fn standalone_word_still_replaced_next_to_path() {
        assert_eq!(
            replace_whole_word(
                "the environment in src/environment.rs",
                "environment",
                "env"
            ),
            "the env in src/environment.rs",
            "standalone word replaced, path-embedded word preserved"
        );
    }

    #[test]
    fn general_dict_stays_empty() {
        assert!(
            GENERAL.is_empty(),
            "GENERAL must stay empty: all 60 single-word rules save 0 tokens              under BPE and corrupt source/paths (#973, #980, #981)"
        );
    }

    #[test]
    fn full_dict_includes_domain() {
        let r = apply_dictionaries("Compiling lean-ctx", DictLevel::Full);
        assert!(r.contains("CC"), "cargo abbreviation should apply: {r}");
    }

    #[test]
    fn no_abbreviation_inflates_tokens() {
        for (name, dict) in [("GIT", GIT), ("CARGO", CARGO), ("NPM", NPM)] {
            for abbr in dict {
                let long_tok = crate::core::tokens::count_tokens(abbr.long);
                let short_tok = crate::core::tokens::count_tokens(abbr.short);
                assert!(
                    short_tok <= long_tok,
                    "{name}: '{}'->'{}'  inflates ({long_tok} tok -> {short_tok} tok)",
                    abbr.long,
                    abbr.short,
                );
            }
        }
    }

    #[test]
    fn dict_count_git() {
        assert!(
            GIT.len() >= 9,
            "should have 9+ git abbreviations, got {}",
            GIT.len()
        );
    }

    #[test]
    fn git_dict_never_abbreviates_subcommands() {
        let git_subcommands = [
            "commit", "branch", "checkout", "merge", "stash", "rebase", "push", "pull", "fetch",
            "clone", "tag", "reset", "bisect", "log", "diff", "show", "status", "add",
        ];
        for abbr in GIT {
            assert!(
                !git_subcommands.contains(&abbr.long),
                "GIT dictionary must NOT abbreviate git subcommand '{}' (→ '{}'). \
                 Agents will misinterpret abbreviated output as valid commands.",
                abbr.long,
                abbr.short
            );
        }
    }

    #[test]
    fn commit_word_survives_full_dict() {
        let text = "commit abc1234 on branch main";
        let result = apply_dictionaries(text, DictLevel::Full);
        assert!(
            result.contains("commit"),
            "word 'commit' must not be abbreviated in output: {result}"
        );
    }

    #[test]
    fn branch_word_survives_full_dict() {
        let text = "Your branch is ahead of 'origin/main' by 2 commits";
        let result = apply_dictionaries(text, DictLevel::Full);
        assert!(
            result.contains("branch"),
            "word 'branch' must not be abbreviated in output: {result}"
        );
    }

    // #973: paths in realistic shell output survive dictionary application.
    #[test]
    fn dict_preserves_file_paths_in_shell_output() {
        let text = "warning: unused variable in src/configuration/environment.rs:42";
        let result = apply_dictionaries(text, DictLevel::Full);
        assert!(
            result.contains("src/configuration/environment.rs:42"),
            "file path must survive dictionary: {result}"
        );
    }

    #[test]
    fn dictionaries_leave_source_code_intact() {
        let go_src = "func handler(ctx context.Context) (api.Result, error) { return doWork(ctx) }";
        let result = apply_dictionaries(go_src, DictLevel::Full);
        for keyword in ["context.Context", "error", "return"] {
            assert!(
                result.contains(keyword),
                "source keyword '{keyword}' must survive dictionaries: {result}"
            );
        }
        let paths = "src/environment.rs src/configuration.rs src/repository.rs";
        let result = apply_dictionaries(paths, DictLevel::Full);
        assert_eq!(
            result, paths,
            "file paths must survive dictionaries verbatim"
        );
    }
}