Skip to main content

lean_ctx/tools/
ctx_smart_read.rs

1use crate::core::cache::SessionCache;
2use crate::core::mode_predictor::{FileSignature, ModePredictor};
3use crate::core::tokens::count_tokens;
4use crate::tools::CrpMode;
5
6pub fn select_mode(cache: &SessionCache, path: &str) -> String {
7    select_mode_with_task(cache, path, None)
8}
9
10pub fn select_mode_with_task(cache: &SessionCache, path: &str, task: Option<&str>) -> String {
11    if crate::tools::ctx_read::is_instruction_file(path) {
12        return "full".to_string();
13    }
14
15    if crate::core::binary_detect::is_binary_file(path) {
16        return "full".to_string();
17    }
18
19    if let Ok(meta) = std::fs::metadata(path) {
20        let cap = crate::core::limits::max_read_bytes() as u64;
21        if meta.len() > cap {
22            return "full".to_string();
23        }
24    }
25
26    let Ok(content) = std::fs::read_to_string(path) else {
27        return "full".to_string();
28    };
29
30    let token_count = count_tokens(&content);
31    let ext = std::path::Path::new(path)
32        .extension()
33        .and_then(|e| e.to_str())
34        .unwrap_or("");
35
36    if let Some(cached) = cache.get(path) {
37        if cached.hash == compute_hash(&content) {
38            return "full".to_string();
39        }
40        return "diff".to_string();
41    }
42
43    if token_count <= 200 {
44        return "full".to_string();
45    }
46
47    if is_config_or_data(ext, path) {
48        return "full".to_string();
49    }
50
51    // task mode (IB-filter) is never auto-selected — it reorders lines and breaks edits.
52    // Users can still explicitly request mode: "task".
53
54    if let Some(recommended) = intent_recommended_mode(task) {
55        return recommended;
56    }
57
58    let sig = FileSignature::from_path(path, token_count);
59    let predictor = ModePredictor::new();
60    if let Some(predicted) = predictor.predict_best_mode(&sig) {
61        return predicted;
62    }
63
64    heuristic_mode(ext, token_count)
65}
66
67/// Queries the intent engine + router for a task-aware read mode recommendation.
68/// Returns `None` when there is no task, confidence is too low, or the router
69/// recommends "auto" (which would recurse).
70fn intent_recommended_mode(task: Option<&str>) -> Option<String> {
71    let task_desc = task?;
72    let classification = crate::core::intent_engine::classify(task_desc);
73    if classification.confidence < 0.4 {
74        return None;
75    }
76    let route = crate::core::intent_engine::route_intent(task_desc, &classification);
77    let mode =
78        crate::core::intent_router::read_mode_for_tier(route.model_tier, classification.task_type);
79    if mode == "auto" {
80        return None;
81    }
82    Some(mode)
83}
84
85fn heuristic_mode(ext: &str, token_count: usize) -> String {
86    if token_count > 8000 {
87        if is_code(ext) {
88            return "map".to_string();
89        }
90        return "aggressive".to_string();
91    }
92    if token_count > 3000 && is_code(ext) {
93        return "map".to_string();
94    }
95    "full".to_string()
96}
97
98pub fn handle(cache: &mut SessionCache, path: &str, crp_mode: CrpMode) -> String {
99    crate::tools::ctx_read::handle(cache, path, "auto", crp_mode)
100}
101
102fn compute_hash(content: &str) -> String {
103    use md5::{Digest, Md5};
104    let mut hasher = Md5::new();
105    hasher.update(content.as_bytes());
106    format!("{:x}", hasher.finalize())
107}
108
109pub fn is_code_ext(ext: &str) -> bool {
110    is_code(ext)
111}
112
113fn is_code(ext: &str) -> bool {
114    matches!(
115        ext,
116        "rs" | "ts"
117            | "tsx"
118            | "js"
119            | "jsx"
120            | "py"
121            | "go"
122            | "java"
123            | "c"
124            | "cpp"
125            | "cc"
126            | "h"
127            | "hpp"
128            | "rb"
129            | "cs"
130            | "kt"
131            | "swift"
132            | "php"
133            | "zig"
134            | "ex"
135            | "exs"
136            | "scala"
137            | "sc"
138            | "dart"
139            | "sh"
140            | "bash"
141            | "svelte"
142            | "vue"
143    )
144}
145
146fn is_config_or_data(ext: &str, path: &str) -> bool {
147    if matches!(
148        ext,
149        "json" | "yaml" | "yml" | "toml" | "xml" | "ini" | "cfg" | "env" | "lock"
150    ) {
151        return true;
152    }
153    let name = std::path::Path::new(path)
154        .file_name()
155        .and_then(|n| n.to_str())
156        .unwrap_or("");
157    matches!(
158        name,
159        "Cargo.toml"
160            | "package.json"
161            | "tsconfig.json"
162            | "Makefile"
163            | "Dockerfile"
164            | "docker-compose.yml"
165            | ".gitignore"
166            | ".env"
167            | "pyproject.toml"
168            | "go.mod"
169            | "build.gradle"
170            | "pom.xml"
171    )
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn test_config_detection() {
180        assert!(is_config_or_data("json", "package.json"));
181        assert!(is_config_or_data("toml", "Cargo.toml"));
182        assert!(!is_config_or_data("rs", "main.rs"));
183    }
184
185    #[test]
186    fn test_code_detection() {
187        assert!(is_code("rs"));
188        assert!(is_code("py"));
189        assert!(is_code("tsx"));
190        assert!(!is_code("json"));
191    }
192
193    #[test]
194    fn intent_mode_for_explore_task() {
195        let mode = intent_recommended_mode(Some("how does the session cache work?"));
196        assert_eq!(mode, Some("map".to_string()));
197    }
198
199    #[test]
200    fn intent_mode_for_fix_task() {
201        let mode = intent_recommended_mode(Some("fix the bug in auth.rs"));
202        assert_eq!(mode, Some("full".to_string()));
203    }
204
205    #[test]
206    fn intent_mode_none_without_task() {
207        assert_eq!(intent_recommended_mode(None), None);
208    }
209
210    #[test]
211    fn intent_mode_none_for_low_confidence() {
212        let mode = intent_recommended_mode(Some("xyz qqq"));
213        assert_eq!(mode, None);
214    }
215}