Skip to main content

lean_ctx/core/
adaptive_thresholds.rs

1use std::collections::HashMap;
2use std::path::Path;
3
4use super::entropy::kolmogorov_proxy;
5
6#[derive(Debug, Clone)]
7pub struct CompressionThresholds {
8    pub bpe_entropy: f64,
9    pub jaccard: f64,
10    pub auto_delta: f64,
11}
12
13impl Default for CompressionThresholds {
14    fn default() -> Self {
15        Self {
16            bpe_entropy: 1.0,
17            jaccard: 0.7,
18            auto_delta: 0.6,
19        }
20    }
21}
22
23static LANGUAGE_THRESHOLDS: &[(&str, CompressionThresholds)] = &[
24    // Python: English-like syntax, significant whitespace → higher entropy baseline
25    (
26        "py",
27        CompressionThresholds {
28            bpe_entropy: 1.2,
29            jaccard: 0.65,
30            auto_delta: 0.55,
31        },
32    ),
33    // Rust: Repetitive keywords (fn, pub, impl, let, mut) → lower threshold catches more
34    (
35        "rs",
36        CompressionThresholds {
37            bpe_entropy: 0.85,
38            jaccard: 0.72,
39            auto_delta: 0.6,
40        },
41    ),
42    // TypeScript/JavaScript: Type annotations are predictable
43    (
44        "ts",
45        CompressionThresholds {
46            bpe_entropy: 0.95,
47            jaccard: 0.68,
48            auto_delta: 0.58,
49        },
50    ),
51    (
52        "tsx",
53        CompressionThresholds {
54            bpe_entropy: 0.95,
55            jaccard: 0.68,
56            auto_delta: 0.58,
57        },
58    ),
59    (
60        "js",
61        CompressionThresholds {
62            bpe_entropy: 1.0,
63            jaccard: 0.68,
64            auto_delta: 0.58,
65        },
66    ),
67    (
68        "jsx",
69        CompressionThresholds {
70            bpe_entropy: 1.0,
71            jaccard: 0.68,
72            auto_delta: 0.58,
73        },
74    ),
75    // Go: Verbose but highly structured → aggressive threshold
76    (
77        "go",
78        CompressionThresholds {
79            bpe_entropy: 0.9,
80            jaccard: 0.72,
81            auto_delta: 0.55,
82        },
83    ),
84    // Java/Kotlin: Very verbose, lots of boilerplate
85    (
86        "java",
87        CompressionThresholds {
88            bpe_entropy: 0.8,
89            jaccard: 0.65,
90            auto_delta: 0.5,
91        },
92    ),
93    (
94        "kt",
95        CompressionThresholds {
96            bpe_entropy: 0.85,
97            jaccard: 0.68,
98            auto_delta: 0.55,
99        },
100    ),
101    // C/C++: Headers are highly repetitive
102    (
103        "c",
104        CompressionThresholds {
105            bpe_entropy: 0.9,
106            jaccard: 0.7,
107            auto_delta: 0.6,
108        },
109    ),
110    (
111        "h",
112        CompressionThresholds {
113            bpe_entropy: 0.75,
114            jaccard: 0.65,
115            auto_delta: 0.5,
116        },
117    ),
118    (
119        "cpp",
120        CompressionThresholds {
121            bpe_entropy: 0.9,
122            jaccard: 0.7,
123            auto_delta: 0.6,
124        },
125    ),
126    (
127        "hpp",
128        CompressionThresholds {
129            bpe_entropy: 0.75,
130            jaccard: 0.65,
131            auto_delta: 0.5,
132        },
133    ),
134    // Ruby: English-like, high entropy
135    (
136        "rb",
137        CompressionThresholds {
138            bpe_entropy: 1.15,
139            jaccard: 0.65,
140            auto_delta: 0.55,
141        },
142    ),
143    // Config/data files: highly repetitive
144    (
145        "json",
146        CompressionThresholds {
147            bpe_entropy: 0.6,
148            jaccard: 0.6,
149            auto_delta: 0.4,
150        },
151    ),
152    (
153        "yaml",
154        CompressionThresholds {
155            bpe_entropy: 0.7,
156            jaccard: 0.62,
157            auto_delta: 0.45,
158        },
159    ),
160    (
161        "yml",
162        CompressionThresholds {
163            bpe_entropy: 0.7,
164            jaccard: 0.62,
165            auto_delta: 0.45,
166        },
167    ),
168    (
169        "toml",
170        CompressionThresholds {
171            bpe_entropy: 0.7,
172            jaccard: 0.62,
173            auto_delta: 0.45,
174        },
175    ),
176    (
177        "xml",
178        CompressionThresholds {
179            bpe_entropy: 0.6,
180            jaccard: 0.6,
181            auto_delta: 0.4,
182        },
183    ),
184    // Markdown/docs: natural language, high entropy
185    (
186        "md",
187        CompressionThresholds {
188            bpe_entropy: 1.3,
189            jaccard: 0.6,
190            auto_delta: 0.55,
191        },
192    ),
193    // CSS: very repetitive selectors/properties
194    (
195        "css",
196        CompressionThresholds {
197            bpe_entropy: 0.7,
198            jaccard: 0.6,
199            auto_delta: 0.45,
200        },
201    ),
202    (
203        "scss",
204        CompressionThresholds {
205            bpe_entropy: 0.75,
206            jaccard: 0.62,
207            auto_delta: 0.48,
208        },
209    ),
210    // SQL: repetitive keywords
211    (
212        "sql",
213        CompressionThresholds {
214            bpe_entropy: 0.8,
215            jaccard: 0.65,
216            auto_delta: 0.5,
217        },
218    ),
219    // Shell scripts
220    (
221        "sh",
222        CompressionThresholds {
223            bpe_entropy: 1.0,
224            jaccard: 0.68,
225            auto_delta: 0.55,
226        },
227    ),
228    (
229        "bash",
230        CompressionThresholds {
231            bpe_entropy: 1.0,
232            jaccard: 0.68,
233            auto_delta: 0.55,
234        },
235    ),
236    // Swift/C#
237    (
238        "swift",
239        CompressionThresholds {
240            bpe_entropy: 0.9,
241            jaccard: 0.68,
242            auto_delta: 0.55,
243        },
244    ),
245    (
246        "cs",
247        CompressionThresholds {
248            bpe_entropy: 0.85,
249            jaccard: 0.65,
250            auto_delta: 0.52,
251        },
252    ),
253    // PHP
254    (
255        "php",
256        CompressionThresholds {
257            bpe_entropy: 0.95,
258            jaccard: 0.68,
259            auto_delta: 0.55,
260        },
261    ),
262];
263
264fn language_map() -> HashMap<&'static str, &'static CompressionThresholds> {
265    LANGUAGE_THRESHOLDS
266        .iter()
267        .map(|(ext, t)| (*ext, t))
268        .collect()
269}
270
271pub fn thresholds_for_path(path: &str) -> CompressionThresholds {
272    let ext = Path::new(path)
273        .extension()
274        .and_then(|e| e.to_str())
275        .unwrap_or("");
276
277    let map = language_map();
278    if let Some(t) = map.get(ext) {
279        return (*t).clone();
280    }
281
282    CompressionThresholds::default()
283}
284
285/// Selects the bandit arm for a read of `path`: its FieldWeights feed the
286/// adaptive context planner (`context_kernel::autopilot`), and a later bounce
287/// or edit failure penalizes it. The rendered text never depends on it (#498).
288fn select_threshold_arm(path: &str, content: &str) {
289    let Some(project_root) =
290        crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
291    else {
292        return;
293    };
294    let ext = Path::new(path)
295        .extension()
296        .and_then(|e| e.to_str())
297        .unwrap_or("");
298    let bandit_key =
299        crate::core::bandit::bandit_key("threshold", ext, Some(token_bucket_label(content)));
300    let mut store = super::bandit::BanditStore::load(&project_root);
301    let bandit = store.get_or_create(&bandit_key);
302    // #4: deterministic argmax-of-mean by default (Thompson only under the
303    // stochastic flag).
304    let arm = bandit.choose_arm();
305    let arm_name = arm.name.clone();
306    super::context_field::set_active_weights(super::context_field::FieldWeights::from_arm(arm));
307    record_selected_arm(path, project_root, bandit_key, arm_name);
308}
309
310/// Shift the thresholds by the content's own compressibility (Kolmogorov
311/// proxy): a pure function of the text.
312fn apply_content_compressibility(base: &mut CompressionThresholds, content: &str) {
313    if content.len() > 500 {
314        let k = kolmogorov_proxy(content);
315        let k_adjustment = (k - 0.45) * 0.5;
316        base.bpe_entropy = (base.bpe_entropy + k_adjustment).clamp(0.4, 2.0);
317        base.jaccard = (base.jaccard - k_adjustment * 0.3).clamp(0.5, 0.85);
318    }
319}
320
321/// Thresholds for rendering a read: the per-language base adjusted by the
322/// content's compressibility, so the rendered text is a pure function of
323/// `(path, content)` (#498). Learned threshold shifts were retired on
324/// 2026-10-16: since #1910 the text ignored them, so they only cost a store
325/// load per read. The bandit arm is still selected for the planner weights.
326pub fn read_thresholds(path: &str, content: &str) -> CompressionThresholds {
327    select_threshold_arm(path, content);
328    let mut base = thresholds_for_path(path);
329    apply_content_compressibility(&mut base, content);
330    base
331}
332
333/// The bandit arm selected for a file's most recent threshold-driven read, kept
334/// so a *deferred* real outcome (bounce, edit-fail) can penalize the arm that
335/// actually produced the compression — instead of a hardcoded success (#593).
336#[derive(Clone)]
337struct SelectedArm {
338    project_root: String,
339    bandit_key: String,
340    arm_name: String,
341}
342
343/// Bounded far above the bounce (5) and edit-force (10) detection windows, so
344/// evicting the oldest entry can never drop an arm a still-pending signal needs.
345const ARM_REGISTRY_CAP: usize = 64;
346
347static SELECTED_ARMS: std::sync::Mutex<Option<SelectedArmRegistry>> = std::sync::Mutex::new(None);
348
349#[derive(Default)]
350struct SelectedArmRegistry {
351    /// Insertion order of distinct paths, for O(1) oldest-first eviction.
352    order: std::collections::VecDeque<String>,
353    by_path: std::collections::HashMap<String, SelectedArm>,
354}
355
356fn record_selected_arm(path: &str, project_root: String, bandit_key: String, arm_name: String) {
357    let norm = crate::core::pathutil::normalize_tool_path(path);
358    let mut guard = SELECTED_ARMS
359        .lock()
360        .unwrap_or_else(std::sync::PoisonError::into_inner);
361    let reg = guard.get_or_insert_with(SelectedArmRegistry::default);
362    let arm = SelectedArm {
363        project_root,
364        bandit_key,
365        arm_name,
366    };
367    if reg.by_path.insert(norm.clone(), arm).is_none() {
368        reg.order.push_back(norm);
369        while reg.order.len() > ARM_REGISTRY_CAP {
370            if let Some(old) = reg.order.pop_front() {
371                reg.by_path.remove(&old);
372            }
373        }
374    }
375}
376
377/// A bounce or edit failure after a read of `path` (#593): penalize the bandit
378/// arm that produced the read. The positive signal comes from realized savings
379/// (`report_bandit_outcome_for_path` in entropy mode).
380pub fn penalize_read_arm(path: &str) {
381    report_bandit_outcome_for_path(path, false);
382}
383
384/// Reward (`success=true`) or penalize (`false`) the bandit arm recorded for
385/// `path`. No-op when no arm was registered (e.g. the file was never read in a
386/// threshold-driven mode), so attribution is never guessed.
387pub fn report_bandit_outcome_for_path(path: &str, success: bool) {
388    let norm = crate::core::pathutil::normalize_tool_path(path);
389    let selected = {
390        let guard = SELECTED_ARMS
391            .lock()
392            .unwrap_or_else(std::sync::PoisonError::into_inner);
393        guard.as_ref().and_then(|r| r.by_path.get(&norm).cloned())
394    };
395    if let Some(sel) = selected {
396        let mut store = super::bandit::BanditStore::load(&sel.project_root);
397        store
398            .get_or_create(&sel.bandit_key)
399            .update(&sel.arm_name, success);
400        let _ = store.save(&sel.project_root);
401    }
402}
403
404fn token_bucket_label(content: &str) -> &'static str {
405    let len = content.len();
406    match len {
407        0..=2000 => "sm",
408        2001..=10000 => "md",
409        10001..=50000 => "lg",
410        _ => "xl",
411    }
412}
413
414#[cfg(test)]
415pub mod tests {
416    use super::*;
417
418    #[test]
419    fn rust_has_lower_threshold_than_python() {
420        let rs = thresholds_for_path("src/main.rs");
421        let py = thresholds_for_path("src/main.py");
422        assert!(rs.bpe_entropy < py.bpe_entropy);
423    }
424
425    #[test]
426    fn json_has_lowest_threshold() {
427        let json = thresholds_for_path("config.json");
428        let rs = thresholds_for_path("main.rs");
429        assert!(json.bpe_entropy < rs.bpe_entropy);
430    }
431
432    #[test]
433    fn unknown_ext_uses_default() {
434        let t = thresholds_for_path("file.xyz");
435        assert!((t.bpe_entropy - 1.0).abs() < f64::EPSILON);
436    }
437
438    #[test]
439    fn adaptive_adjusts_for_compressibility() {
440        let repetitive = "use std::io;\n".repeat(200);
441        let diverse = (0..200).fold(String::new(), |mut s, i| {
442            use std::fmt::Write;
443            let _ = writeln!(s, "let var_{i} = compute_{i}(arg_{i});");
444            s
445        });
446
447        let base_rep = thresholds_for_path("main.rs");
448        let base_div = thresholds_for_path("main.rs");
449        assert!(
450            (base_rep.bpe_entropy - base_div.bpe_entropy).abs() < f64::EPSILON,
451            "same path should get same base thresholds"
452        );
453
454        let k_rep = kolmogorov_proxy(&repetitive);
455        let k_div = kolmogorov_proxy(&diverse);
456        assert!(
457            k_rep < k_div,
458            "repetitive content should have lower Kolmogorov proxy: {k_rep} vs {k_div}"
459        );
460    }
461
462    fn arm_mean(project_root: &str, key: &str, arm: &str) -> f64 {
463        let mut store = crate::core::bandit::BanditStore::load(project_root);
464        store
465            .get_or_create(key)
466            .arms
467            .iter()
468            .find(|a| a.name == arm)
469            .map_or(0.5, crate::core::bandit::BanditArm::mean)
470    }
471
472    #[test]
473    fn real_failure_signal_penalizes_selected_arm() {
474        let _data = crate::core::data_dir::isolated_data_dir();
475        let root = "/fix1/penalize";
476        record_selected_arm(
477            "src/foo.rs",
478            root.into(),
479            "threshold:rs:md".into(),
480            "aggressive".into(),
481        );
482
483        let before = arm_mean(root, "threshold:rs:md", "aggressive");
484        for _ in 0..16 {
485            penalize_read_arm("src/foo.rs");
486        }
487        let after = arm_mean(root, "threshold:rs:md", "aggressive");
488
489        assert!(
490            after < before,
491            "bounce/edit-fail must lower the selected arm mean: {before} -> {after}"
492        );
493    }
494
495    #[test]
496    fn outcome_without_registered_arm_does_not_register_path() {
497        let _data = crate::core::data_dir::isolated_data_dir();
498        // Attribution must never be guessed for a path we never selected an arm for.
499        report_bandit_outcome_for_path("fix1/never-seen-xyz.rs", false);
500        let norm = crate::core::pathutil::normalize_tool_path("fix1/never-seen-xyz.rs");
501        let guard = SELECTED_ARMS
502            .lock()
503            .unwrap_or_else(std::sync::PoisonError::into_inner);
504        let registered = guard
505            .as_ref()
506            .is_some_and(|r| r.by_path.contains_key(&norm));
507        assert!(!registered, "no-op report must not create a registry entry");
508    }
509
510    #[test]
511    fn registry_evicts_oldest_beyond_cap() {
512        let _data = crate::core::data_dir::isolated_data_dir();
513        for i in 0..(ARM_REGISTRY_CAP + 5) {
514            record_selected_arm(
515                &format!("evict/f{i}.rs"),
516                "/fix1/evict".into(),
517                "threshold:rs:md".into(),
518                "balanced".into(),
519            );
520        }
521        let guard = SELECTED_ARMS
522            .lock()
523            .unwrap_or_else(std::sync::PoisonError::into_inner);
524        let reg = guard.as_ref().expect("registry initialized");
525        assert!(reg.order.len() <= ARM_REGISTRY_CAP);
526        assert_eq!(reg.order.len(), reg.by_path.len());
527    }
528}