lean-ctx 3.6.0

Context Runtime for AI Agents with CCP. 63 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing + diaries, 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
//! Tree-sitter AST-aware code chunking for semantic search.
//!
//! Replaces heuristic line-prefix matching with proper AST parsing.
//! Extracts function bodies, struct definitions, class declarations etc.
//! as complete, self-contained chunks with accurate boundaries.
//!
//! Falls back to heuristic chunking for unsupported languages.

#[cfg(feature = "tree-sitter")]
use tree_sitter::{Language, Node, Parser, Query, QueryCursor, StreamingIterator};

use super::bm25_index::{ChunkKind, CodeChunk};

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_RUST: &str = r"
(function_item name: (identifier) @name) @chunk
(struct_item name: (type_identifier) @name) @chunk
(enum_item name: (type_identifier) @name) @chunk
(trait_item name: (type_identifier) @name) @chunk
(impl_item type: (type_identifier) @name) @chunk
(const_item name: (identifier) @name) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_TYPESCRIPT: &str = r"
(function_declaration name: (identifier) @name) @chunk
(class_declaration name: (type_identifier) @name) @chunk
(abstract_class_declaration name: (type_identifier) @name) @chunk
(interface_declaration name: (type_identifier) @name) @chunk
(type_alias_declaration name: (type_identifier) @name) @chunk
(method_definition name: (property_identifier) @name) @chunk
(variable_declarator name: (identifier) @name value: (arrow_function)) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_JAVASCRIPT: &str = r"
(function_declaration name: (identifier) @name) @chunk
(class_declaration name: (identifier) @name) @chunk
(method_definition name: (property_identifier) @name) @chunk
(variable_declarator name: (identifier) @name value: (arrow_function)) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_PYTHON: &str = r"
(function_definition name: (identifier) @name) @chunk
(class_definition name: (identifier) @name) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_GO: &str = r"
(function_declaration name: (identifier) @name) @chunk
(method_declaration name: (field_identifier) @name) @chunk
(type_spec name: (type_identifier) @name) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_JAVA: &str = r"
(method_declaration name: (identifier) @name) @chunk
(class_declaration name: (identifier) @name) @chunk
(interface_declaration name: (identifier) @name) @chunk
(enum_declaration name: (identifier) @name) @chunk
(constructor_declaration name: (identifier) @name) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_C: &str = r"
(function_definition
  declarator: (function_declarator
    declarator: (identifier) @name)) @chunk
(struct_specifier name: (type_identifier) @name) @chunk
(enum_specifier name: (type_identifier) @name) @chunk
";

#[cfg(feature = "tree-sitter")]
const CHUNK_QUERY_CPP: &str = r"
(function_definition
  declarator: (function_declarator
    declarator: (_) @name)) @chunk
(struct_specifier name: (type_identifier) @name) @chunk
(class_specifier name: (type_identifier) @name) @chunk
(enum_specifier name: (type_identifier) @name) @chunk
(namespace_definition name: (identifier) @name) @chunk
";

/// Extract code chunks from a file using tree-sitter AST parsing.
///
/// Returns `None` if the language is unsupported, allowing callers to fall back
/// to heuristic-based chunking.
#[cfg(feature = "tree-sitter")]
fn get_cached_query(file_ext: &str) -> Option<&'static Query> {
    use std::collections::HashMap;
    use std::sync::OnceLock;

    static QUERY_CACHE: OnceLock<HashMap<&'static str, Query>> = OnceLock::new();

    let cache = QUERY_CACHE.get_or_init(|| {
        let mut map = HashMap::new();
        let exts: &[&str] = &[
            "rs", "ts", "tsx", "js", "jsx", "py", "go", "java", "c", "h", "cpp", "cc", "cxx", "hpp",
        ];
        for &ext in exts {
            if let (Some(lang), Some(src)) = (get_language(ext), get_chunk_query(ext)) {
                if let Ok(q) = Query::new(&lang, src) {
                    map.insert(ext, q);
                }
            }
        }
        map
    });

    cache.get(file_ext)
}

/// Visit each structural chunk root (`@chunk` capture) once per tree-sitter query match.
///
/// `start_line` / `end_line` are **1-based** inclusive line numbers (matching [`CodeChunk`]).
/// Returns `None` if the extension is unsupported or parsing fails.
#[cfg(feature = "tree-sitter")]
pub(crate) fn for_each_chunk_node(
    content: &str,
    file_ext: &str,
    mut visitor: impl FnMut(Node, &str, ChunkKind, usize, usize),
) -> Option<()> {
    let language = get_language(file_ext)?;

    thread_local! {
        static PARSER: std::cell::RefCell<Parser> = std::cell::RefCell::new(Parser::new());
    }

    let tree = PARSER.with(|p| {
        let mut parser = p.borrow_mut();
        let _ = parser.set_language(&language);
        parser.parse(content, None)
    })?;

    let query = get_cached_query(file_ext)?;
    let chunk_idx = find_capture_index(query, "chunk")?;
    let name_idx = find_capture_index(query, "name")?;

    let source = content.as_bytes();
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, tree.root_node(), source);
    let mut seen_ranges = Vec::new();

    while let Some(m) = matches.next() {
        let mut chunk_node: Option<Node> = None;
        let mut name_text = String::new();

        for cap in m.captures {
            if cap.index == chunk_idx {
                chunk_node = Some(cap.node);
            } else if cap.index == name_idx {
                if let Ok(text) = cap.node.utf8_text(source) {
                    name_text = text.to_string();
                }
            }
        }

        if let Some(node) = chunk_node {
            if name_text.is_empty() {
                continue;
            }

            let start_row0 = node.start_position().row;
            let end_row0 = node.end_position().row;

            let range = (start_row0, end_row0);
            if seen_ranges
                .iter()
                .any(|&(s, e)| s <= start_row0 && end_row0 <= e && range != (s, e))
            {
                continue;
            }
            seen_ranges.push(range);

            let kind = node_kind_to_chunk_kind(node.kind());
            visitor(node, name_text.as_str(), kind, start_row0 + 1, end_row0 + 1);
        }
    }

    Some(())
}

#[cfg(feature = "tree-sitter")]
pub fn extract_chunks_ts(file_path: &str, content: &str, file_ext: &str) -> Option<Vec<CodeChunk>> {
    let lines: Vec<&str> = content.lines().collect();
    let mut chunks = Vec::new();

    for_each_chunk_node(
        content,
        file_ext,
        |node, name_text, kind, start_line, end_line| {
            let start_row0 = node.start_position().row;
            let end_row0 = node.end_position().row;
            let block: String = lines[start_row0..=end_row0.min(lines.len().saturating_sub(1))]
                .to_vec()
                .join("\n");
            let token_count = super::bm25_index::tokenize_for_index(&block).len();

            chunks.push(CodeChunk {
                file_path: file_path.to_string(),
                symbol_name: name_text.to_string(),
                kind,
                start_line,
                end_line,
                content: block,
                tokens: Vec::new(),
                token_count,
            });
        },
    )?;

    if chunks.is_empty() {
        return None;
    }

    chunks.sort_by_key(|c| c.start_line);
    Some(chunks)
}

#[cfg(not(feature = "tree-sitter"))]
pub fn extract_chunks_ts(
    _file_path: &str,
    _content: &str,
    _file_ext: &str,
) -> Option<Vec<CodeChunk>> {
    None
}

#[cfg(feature = "tree-sitter")]
fn get_language(ext: &str) -> Option<Language> {
    Some(match ext {
        "rs" => tree_sitter_rust::LANGUAGE.into(),
        "ts" => tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
        "tsx" => tree_sitter_typescript::LANGUAGE_TSX.into(),
        "js" | "jsx" => tree_sitter_javascript::LANGUAGE.into(),
        "py" => tree_sitter_python::LANGUAGE.into(),
        "go" => tree_sitter_go::LANGUAGE.into(),
        "java" => tree_sitter_java::LANGUAGE.into(),
        "c" | "h" => tree_sitter_c::LANGUAGE.into(),
        "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "hh" => tree_sitter_cpp::LANGUAGE.into(),
        _ => return None,
    })
}

#[cfg(feature = "tree-sitter")]
fn get_chunk_query(ext: &str) -> Option<&'static str> {
    Some(match ext {
        "rs" => CHUNK_QUERY_RUST,
        "ts" | "tsx" => CHUNK_QUERY_TYPESCRIPT,
        "js" | "jsx" => CHUNK_QUERY_JAVASCRIPT,
        "py" => CHUNK_QUERY_PYTHON,
        "go" => CHUNK_QUERY_GO,
        "java" => CHUNK_QUERY_JAVA,
        "c" | "h" => CHUNK_QUERY_C,
        "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "hh" => CHUNK_QUERY_CPP,
        _ => return None,
    })
}

#[cfg(feature = "tree-sitter")]
fn find_capture_index(query: &Query, name: &str) -> Option<u32> {
    query
        .capture_names()
        .iter()
        .position(|n| *n == name)
        .map(|i| i as u32)
}

fn node_kind_to_chunk_kind(kind: &str) -> ChunkKind {
    match kind {
        "function_item"
        | "function_declaration"
        | "function_definition"
        | "method_declaration"
        | "method_definition"
        | "constructor_declaration"
        | "variable_declarator" => ChunkKind::Function,

        "struct_item"
        | "struct_specifier"
        | "struct_declaration"
        | "enum_item"
        | "enum_specifier"
        | "enum_declaration"
        | "trait_item"
        | "interface_declaration"
        | "type_alias_declaration"
        | "type_spec" => ChunkKind::Struct,

        "impl_item" => ChunkKind::Impl,

        "class_declaration"
        | "abstract_class_declaration"
        | "class_specifier"
        | "class_definition" => ChunkKind::Class,

        "namespace_definition" | "namespace_declaration" => ChunkKind::Module,

        _ => ChunkKind::Other,
    }
}

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

    #[test]
    fn extract_rust_chunks() {
        let src = r#"use std::io;

pub fn process(input: &str) -> String {
    input.to_uppercase()
}

pub struct Config {
    pub name: String,
    pub port: u16,
}

impl Config {
    pub fn new() -> Self {
        Self { name: "default".into(), port: 8080 }
    }
}

fn helper() -> bool {
    true
}
"#;
        let chunks = extract_chunks_ts("main.rs", src, "rs").unwrap();
        assert!(
            chunks.len() >= 4,
            "expected >=4 chunks, got {}",
            chunks.len()
        );

        let names: Vec<&str> = chunks.iter().map(|c| c.symbol_name.as_str()).collect();
        assert!(names.contains(&"process"), "got {names:?}");
        assert!(names.contains(&"Config"), "got {names:?}");
        assert!(names.contains(&"helper"), "got {names:?}");

        let process = chunks.iter().find(|c| c.symbol_name == "process").unwrap();
        assert!(matches!(process.kind, ChunkKind::Function));
        assert!(process.content.contains("to_uppercase"));
    }

    #[test]
    fn extract_typescript_chunks() {
        let src = r"
export function greet(name: string): string {
    return `Hello ${name}`;
}

export class UserService {
    findUser(id: number): User {
        return db.find(id);
    }
}

const handler = async (req: Request): Promise<Response> => {
    return new Response();
};
";
        let chunks = extract_chunks_ts("app.ts", src, "ts").unwrap();
        assert!(
            chunks.len() >= 3,
            "expected >=3 chunks, got {}",
            chunks.len()
        );

        let names: Vec<&str> = chunks.iter().map(|c| c.symbol_name.as_str()).collect();
        assert!(names.contains(&"greet"), "got {names:?}");
        assert!(names.contains(&"UserService"), "got {names:?}");
    }

    #[test]
    fn extract_python_chunks() {
        let src = r"
class AuthService:
    def __init__(self, db):
        self.db = db

    def authenticate(self, email: str) -> bool:
        user = self.db.find(email)
        return user is not None

def create_app():
    return Flask(__name__)
";
        let chunks = extract_chunks_ts("app.py", src, "py").unwrap();
        assert!(
            chunks.len() >= 2,
            "expected >=2 chunks, got {}",
            chunks.len()
        );

        let names: Vec<&str> = chunks.iter().map(|c| c.symbol_name.as_str()).collect();
        assert!(names.contains(&"AuthService"), "got {names:?}");
        assert!(names.contains(&"create_app"), "got {names:?}");

        let auth = chunks
            .iter()
            .find(|c| c.symbol_name == "AuthService")
            .unwrap();
        assert!(auth.content.contains("authenticate"));
    }

    #[test]
    fn chunks_contain_full_body() {
        let src = r#"
pub fn complex(x: i32, y: i32) -> Result<String, Error> {
    let sum = x + y;
    let result = format!("Sum: {}", sum);
    if sum > 100 {
        return Err(Error::new("too large"));
    }
    Ok(result)
}
"#;
        let chunks = extract_chunks_ts("math.rs", src, "rs").unwrap();
        let complex = chunks.iter().find(|c| c.symbol_name == "complex").unwrap();
        assert!(complex.content.contains("sum > 100"));
        assert!(complex.content.contains("Ok(result)"));
    }

    #[test]
    fn unsupported_language_returns_none() {
        assert!(extract_chunks_ts("file.xyz", "content", "xyz").is_none());
    }

    #[test]
    fn empty_file_returns_none() {
        assert!(extract_chunks_ts("empty.rs", "", "rs").is_none());
    }

    #[test]
    fn chunks_sorted_by_line() {
        let src = r"
fn b_func() {}
fn a_func() {}
";
        let chunks = extract_chunks_ts("sort.rs", src, "rs").unwrap();
        assert!(chunks[0].start_line <= chunks[1].start_line);
    }
}