lean_ctx/server/
predictive_preload.rs1#![allow(clippy::case_sensitive_file_extension_comparisons)]
2use std::collections::{HashMap, HashSet};
8use std::fs::{self, OpenOptions};
9use std::io::{Read, Write};
10use std::path::{Component, Path, PathBuf};
11use std::sync::{Mutex, OnceLock};
12
13const MAX_RECENT_FILES: usize = 3;
14const MAX_WARM_BYTES: u64 = 256 * 1024;
15
16type PredictionKey = (String, Vec<String>);
17
18#[derive(Debug)]
19pub struct PredictivePreloader {
20 model: HashMap<PredictionKey, Vec<String>>,
22 pending: HashSet<String>,
23 last_key: Option<PredictionKey>,
24 predicted: u64,
25 used: u64,
26 history_path: PathBuf,
27}
28
29impl Default for PredictivePreloader {
30 fn default() -> Self {
31 Self::with_history_path(default_history_path())
32 }
33}
34
35impl PredictivePreloader {
36 #[must_use]
37 pub fn with_history_path(history_path: PathBuf) -> Self {
38 Self {
39 model: HashMap::new(),
40 pending: HashSet::new(),
41 last_key: None,
42 predicted: 0,
43 used: 0,
44 history_path,
45 }
46 }
47
48 #[must_use]
51 pub fn predict_next(&mut self, task_class: &str, recent_files: &[&str]) -> Vec<String> {
52 let recent = normalize_recent_files(recent_files);
53 if recent.is_empty() {
54 return Vec::new();
55 }
56
57 let key = (task_class.to_ascii_lowercase(), recent.clone());
58 let mut predictions = self.model.get(&key).cloned().unwrap_or_default();
59 for path in &recent {
60 predictions.extend(file_predictions(path));
61 }
62 if is_debugging_task(task_class) {
63 predictions.extend(debugging_predictions());
64 }
65
66 predictions = unique_predictions(predictions, &recent);
67 self.model.insert(key.clone(), predictions.clone());
68 self.last_key = Some(key);
69 for path in &predictions {
70 if self.pending.insert(path.clone()) {
71 self.predicted += 1;
72 }
73 }
74 self.append_history("predict", None, &predictions);
75 predictions
76 }
77
78 pub fn on_file_read(&mut self, path: &str) {
81 let path = normalize_path(path);
82 let hit = self.pending.remove(&path);
83 if hit {
84 self.used += 1;
85 }
86 if let Some(key) = self.last_key.take() {
87 let learned = self.model.entry(key).or_default();
88 if !learned.contains(&path) {
89 learned.push(path.clone());
90 }
91 }
92 self.append_history("read", Some(hit), &[path]);
93 }
94
95 #[must_use]
96 pub fn accuracy(&self) -> f32 {
97 if self.predicted == 0 {
98 0.0
99 } else {
100 self.used as f32 / self.predicted as f32
101 }
102 }
103
104 fn append_history(&self, event: &str, hit: Option<bool>, paths: &[String]) {
105 let Some(parent) = self.history_path.parent() else {
106 return;
107 };
108 if fs::create_dir_all(parent).is_err() {
109 return;
110 }
111 let Ok(mut file) = OpenOptions::new()
112 .create(true)
113 .append(true)
114 .open(&self.history_path)
115 else {
116 return;
117 };
118 let record = serde_json::json!({
119 "event": event,
120 "hit": hit,
121 "paths": paths,
122 });
123 let _ = writeln!(file, "{record}");
124 }
125}
126
127static PRELOADER: OnceLock<Mutex<PredictivePreloader>> = OnceLock::new();
128
129#[must_use]
131pub fn record_read_and_predict(task_class: &str, path: &str) -> Vec<String> {
132 let Ok(mut preloader) = global_preloader().lock() else {
133 tracing::debug!("predictive preload lock poisoned; skipping prediction");
134 return Vec::new();
135 };
136 preloader.on_file_read(path);
137 preloader.predict_next(task_class, &[path])
138}
139
140#[must_use]
142pub fn predict_next(task_class: &str, recent_files: &[&str]) -> Vec<String> {
143 let Ok(mut preloader) = global_preloader().lock() else {
144 tracing::debug!("predictive preload lock poisoned; skipping prediction");
145 return Vec::new();
146 };
147 preloader.predict_next(task_class, recent_files)
148}
149
150pub fn on_file_read(path: &str) {
152 if let Ok(mut preloader) = global_preloader().lock() {
153 preloader.on_file_read(path);
154 } else {
155 tracing::debug!("predictive preload lock poisoned; skipping read record");
156 }
157}
158
159#[must_use]
161pub fn accuracy() -> f32 {
162 global_preloader()
163 .lock()
164 .map_or(0.0, |preloader| preloader.accuracy())
165}
166
167pub fn warm_paths(project_root: Option<&Path>, paths: &[String]) {
170 for path in paths {
171 if !is_safe_relative_path(path) {
172 continue;
173 }
174 let full_path = project_root.map_or_else(|| PathBuf::from(path), |root| root.join(path));
175 let Ok(file) = fs::File::open(full_path) else {
176 continue;
177 };
178 let mut reader = file.take(MAX_WARM_BYTES);
179 let mut contents = Vec::new();
180 let _ = reader.read_to_end(&mut contents);
181 }
182}
183
184fn global_preloader() -> &'static Mutex<PredictivePreloader> {
185 PRELOADER.get_or_init(|| Mutex::new(PredictivePreloader::default()))
186}
187
188fn default_history_path() -> PathBuf {
189 dirs::home_dir().map_or_else(
190 || PathBuf::from(".local/share/lean-ctx/predictions.jsonl"),
191 |home| home.join(".local/share/lean-ctx/predictions.jsonl"),
192 )
193}
194
195fn normalize_recent_files(recent_files: &[&str]) -> Vec<String> {
196 recent_files
197 .iter()
198 .rev()
199 .take(MAX_RECENT_FILES)
200 .rev()
201 .map(|path| normalize_path(path))
202 .filter(|path| !path.is_empty())
203 .collect()
204}
205
206fn normalize_path(path: &str) -> String {
207 path.trim().replace('\\', "/")
208}
209
210fn unique_predictions(predictions: Vec<String>, recent: &[String]) -> Vec<String> {
211 let mut seen = HashSet::new();
212 predictions
213 .into_iter()
214 .map(|path| normalize_path(&path))
215 .filter(|path| is_safe_relative_path(path) && !recent.contains(path))
216 .filter(|path| seen.insert(path.clone()))
217 .collect()
218}
219
220fn file_predictions(path: &str) -> Vec<String> {
221 let mut predictions = Vec::new();
222 if path.ends_with(".md") {
223 predictions.extend(documented_rust_paths(path));
224 }
225 if is_test_file(path) {
226 predictions.extend(implementation_candidates(path));
227 } else if path.ends_with(".rs") {
228 predictions.extend(rust_source_predictions(path));
229 }
230 if path.starts_with("src/proxy/") {
231 predictions.extend([
232 "src/proxy/mod.rs".to_owned(),
233 "src/proxy/forward/mod.rs".to_owned(),
234 ]);
235 }
236 predictions
237}
238
239fn rust_source_predictions(path: &str) -> Vec<String> {
240 let source = Path::new(path);
241 let Some(stem) = source.file_stem().and_then(|stem| stem.to_str()) else {
242 return Vec::new();
243 };
244 let mut predictions = vec![format!("tests/{stem}.rs"), "Cargo.toml".to_owned()];
245 if let Some(parent) = source.parent() {
246 let module = parent.join("mod.rs");
247 if module != source {
248 predictions.push(module.to_string_lossy().replace('\\', "/"));
249 }
250 }
251 if path.starts_with("src/") && path != "src/lib.rs" {
252 predictions.push("src/lib.rs".to_owned());
253 }
254 predictions
255}
256
257fn implementation_candidates(path: &str) -> Vec<String> {
258 let normalized = normalize_path(path);
259 let file_name = Path::new(&normalized)
260 .file_name()
261 .and_then(|name| name.to_str())
262 .unwrap_or_default();
263 let stem = file_name.trim_end_matches(".rs");
264 let implementation = stem
265 .trim_end_matches("_tests")
266 .trim_end_matches("_test")
267 .replace(".test", "");
268
269 let mut predictions = Vec::new();
270 if normalized.starts_with("tests/") {
271 predictions.push(format!("src/{implementation}.rs"));
272 predictions.push(format!("src/{implementation}/mod.rs"));
273 } else if let Some(parent) = Path::new(&normalized).parent() {
274 predictions.push(
275 parent
276 .join(format!("{implementation}.rs"))
277 .to_string_lossy()
278 .replace('\\', "/"),
279 );
280 }
281 predictions
282}
283
284fn is_test_file(path: &str) -> bool {
285 let path = path.to_ascii_lowercase();
286 path.starts_with("tests/")
287 || path.contains("/tests/")
288 || path.contains(".test.")
289 || path.ends_with("_test.rs")
290 || path.ends_with("_tests.rs")
291}
292
293fn documented_rust_paths(path: &str) -> Vec<String> {
294 let Ok(contents) = fs::read_to_string(path) else {
295 return Vec::new();
296 };
297 contents
298 .split(|character: char| character.is_whitespace() || "`'\"()[]{}<>,:;".contains(character))
299 .map(|token| token.trim_end_matches(|character| matches!(character, '.' | ')' | ']')))
300 .filter(|token| token.ends_with(".rs") && is_safe_relative_path(token))
301 .map(str::to_owned)
302 .collect()
303}
304
305fn is_debugging_task(task_class: &str) -> bool {
306 let task = task_class.to_ascii_lowercase();
307 task.contains("debug")
308 || task.contains("diagnos")
309 || task.contains("trace")
310 || task.contains("fix")
311}
312
313fn debugging_predictions() -> Vec<String> {
314 vec![
315 "logs/error.log".to_owned(),
316 ".lean-ctx/config.toml".to_owned(),
317 "Cargo.toml".to_owned(),
318 ]
319}
320
321fn is_safe_relative_path(path: &str) -> bool {
322 let path = Path::new(path);
323 path.is_relative()
324 && path
325 .components()
326 .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
327}
328
329#[cfg(test)]
330mod tests {
331 use super::PredictivePreloader;
332 use std::path::PathBuf;
333
334 fn preloader() -> PredictivePreloader {
335 PredictivePreloader::with_history_path(PathBuf::from("/dev/null/predictions.jsonl"))
336 }
337
338 #[test]
339 fn predicts_test_file_from_implementation_file() {
340 let mut preloader = preloader();
341 let predictions = preloader.predict_next("coding_new", &["src/server/context_gate.rs"]);
342
343 assert!(predictions.contains(&"tests/context_gate.rs".to_owned()));
344 assert!(predictions.contains(&"Cargo.toml".to_owned()));
345 }
346
347 #[test]
348 fn predicts_parent_mod_from_child_module() {
349 let mut preloader = preloader();
350 let predictions = preloader.predict_next("coding_new", &["src/server/context_gate.rs"]);
351
352 assert!(predictions.contains(&"src/server/mod.rs".to_owned()));
353 }
354
355 #[test]
356 fn tracks_prediction_accuracy() {
357 let mut preloader = preloader();
358 let predictions = preloader.predict_next("coding_new", &["src/lib.rs"]);
359 let predicted = predictions.len() as f32;
360
361 preloader.on_file_read("Cargo.toml");
362
363 assert_eq!(preloader.accuracy(), 1.0 / predicted);
364 }
365
366 #[test]
367 fn debugging_task_predicts_logs_tests_and_configuration() {
368 let mut preloader = preloader();
369 let predictions = preloader.predict_next("coding_fix", &["src/proxy/pre_optimize.rs"]);
370
371 assert!(predictions.contains(&"logs/error.log".to_owned()));
372 assert!(predictions.contains(&".lean-ctx/config.toml".to_owned()));
373 assert!(predictions.contains(&"tests/pre_optimize.rs".to_owned()));
374 }
375
376 #[test]
377 fn test_file_predicts_implementation() {
378 let mut preloader = preloader();
379 let predictions = preloader.predict_next("coding_fix", &["tests/context_gate.rs"]);
380
381 assert!(predictions.contains(&"src/context_gate.rs".to_owned()));
382 }
383}