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 (
26 "py",
27 CompressionThresholds {
28 bpe_entropy: 1.2,
29 jaccard: 0.65,
30 auto_delta: 0.55,
31 },
32 ),
33 (
35 "rs",
36 CompressionThresholds {
37 bpe_entropy: 0.85,
38 jaccard: 0.72,
39 auto_delta: 0.6,
40 },
41 ),
42 (
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 (
77 "go",
78 CompressionThresholds {
79 bpe_entropy: 0.9,
80 jaccard: 0.72,
81 auto_delta: 0.55,
82 },
83 ),
84 (
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 (
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 (
136 "rb",
137 CompressionThresholds {
138 bpe_entropy: 1.15,
139 jaccard: 0.65,
140 auto_delta: 0.55,
141 },
142 ),
143 (
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 (
186 "md",
187 CompressionThresholds {
188 bpe_entropy: 1.3,
189 jaccard: 0.6,
190 auto_delta: 0.55,
191 },
192 ),
193 (
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 (
212 "sql",
213 CompressionThresholds {
214 bpe_entropy: 0.8,
215 jaccard: 0.65,
216 auto_delta: 0.5,
217 },
218 ),
219 (
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 (
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 (
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
285pub fn adaptive_thresholds(path: &str, content: &str) -> CompressionThresholds {
286 let mut base = thresholds_for_path(path);
287
288 let ext = std::path::Path::new(path)
289 .extension()
290 .and_then(|e| e.to_str())
291 .unwrap_or("");
292 let feedback = super::feedback::FeedbackStore::load();
293 if let Some(learned_entropy) = feedback.get_learned_entropy(ext) {
294 base.bpe_entropy = base.bpe_entropy * 0.6 + learned_entropy * 0.4;
295 }
296 if let Some(learned_jaccard) = feedback.get_learned_jaccard(ext) {
297 base.jaccard = base.jaccard * 0.6 + learned_jaccard * 0.4;
298 }
299
300 base.bpe_entropy =
304 (base.bpe_entropy + super::threshold_learning::learned_delta(ext)).clamp(0.4, 2.0);
305
306 apply_content_compressibility(&mut base, content);
307
308 if let Some(project_root) =
309 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
310 {
311 let bandit_key =
312 crate::core::bandit::bandit_key("threshold", ext, Some(token_bucket_label(content)));
313 let mut store = super::bandit::BanditStore::load(&project_root);
314 let bandit = store.get_or_create(&bandit_key);
315 let arm = bandit.choose_arm();
319 base.bpe_entropy = base.bpe_entropy * 0.5 + arm.entropy_threshold * 0.5;
320 base.jaccard = base.jaccard * 0.5 + arm.jaccard_threshold * 0.5;
321 let arm_name = arm.name.clone();
322 super::context_field::set_active_weights(super::context_field::FieldWeights::from_arm(arm));
323 record_selected_arm(path, project_root, bandit_key, arm_name);
324 }
325
326 base
327}
328
329fn apply_content_compressibility(base: &mut CompressionThresholds, content: &str) {
332 if content.len() > 500 {
333 let k = kolmogorov_proxy(content);
334 let k_adjustment = (k - 0.45) * 0.5;
335 base.bpe_entropy = (base.bpe_entropy + k_adjustment).clamp(0.4, 2.0);
336 base.jaccard = (base.jaccard - k_adjustment * 0.3).clamp(0.5, 0.85);
337 }
338}
339
340pub fn read_thresholds(path: &str, content: &str) -> CompressionThresholds {
351 let _learned = adaptive_thresholds(path, content);
352 let mut base = thresholds_for_path(path);
353 apply_content_compressibility(&mut base, content);
354 base
355}
356
357#[derive(Clone)]
361struct SelectedArm {
362 project_root: String,
363 bandit_key: String,
364 arm_name: String,
365}
366
367const ARM_REGISTRY_CAP: usize = 64;
370
371static SELECTED_ARMS: std::sync::Mutex<Option<SelectedArmRegistry>> = std::sync::Mutex::new(None);
372
373#[derive(Default)]
374struct SelectedArmRegistry {
375 order: std::collections::VecDeque<String>,
377 by_path: std::collections::HashMap<String, SelectedArm>,
378}
379
380fn record_selected_arm(path: &str, project_root: String, bandit_key: String, arm_name: String) {
381 let norm = crate::core::pathutil::normalize_tool_path(path);
382 let mut guard = SELECTED_ARMS
383 .lock()
384 .unwrap_or_else(std::sync::PoisonError::into_inner);
385 let reg = guard.get_or_insert_with(SelectedArmRegistry::default);
386 let arm = SelectedArm {
387 project_root,
388 bandit_key,
389 arm_name,
390 };
391 if reg.by_path.insert(norm.clone(), arm).is_none() {
392 reg.order.push_back(norm);
393 while reg.order.len() > ARM_REGISTRY_CAP {
394 if let Some(old) = reg.order.pop_front() {
395 reg.by_path.remove(&old);
396 }
397 }
398 }
399}
400
401pub fn record_quality_signal(path: &str, signal: crate::core::threshold_learning::QualitySignal) {
409 use crate::core::threshold_learning::QualitySignal;
410 crate::core::threshold_learning::record_signal(path, signal);
411 match signal {
412 QualitySignal::Bounce | QualitySignal::EditFail => {
413 report_bandit_outcome_for_path(path, false);
414 }
415 QualitySignal::CleanCompressed | QualitySignal::WastedFull => {}
416 }
417}
418
419pub fn report_bandit_outcome_for_path(path: &str, success: bool) {
423 let norm = crate::core::pathutil::normalize_tool_path(path);
424 let selected = {
425 let guard = SELECTED_ARMS
426 .lock()
427 .unwrap_or_else(std::sync::PoisonError::into_inner);
428 guard.as_ref().and_then(|r| r.by_path.get(&norm).cloned())
429 };
430 if let Some(sel) = selected {
431 let mut store = super::bandit::BanditStore::load(&sel.project_root);
432 store
433 .get_or_create(&sel.bandit_key)
434 .update(&sel.arm_name, success);
435 let _ = store.save(&sel.project_root);
436 }
437}
438
439fn token_bucket_label(content: &str) -> &'static str {
440 let len = content.len();
441 match len {
442 0..=2000 => "sm",
443 2001..=10000 => "md",
444 10001..=50000 => "lg",
445 _ => "xl",
446 }
447}
448
449#[cfg(test)]
450pub mod tests {
451 use super::*;
452
453 #[test]
454 fn rust_has_lower_threshold_than_python() {
455 let rs = thresholds_for_path("src/main.rs");
456 let py = thresholds_for_path("src/main.py");
457 assert!(rs.bpe_entropy < py.bpe_entropy);
458 }
459
460 #[test]
461 fn json_has_lowest_threshold() {
462 let json = thresholds_for_path("config.json");
463 let rs = thresholds_for_path("main.rs");
464 assert!(json.bpe_entropy < rs.bpe_entropy);
465 }
466
467 #[test]
468 fn unknown_ext_uses_default() {
469 let t = thresholds_for_path("file.xyz");
470 assert!((t.bpe_entropy - 1.0).abs() < f64::EPSILON);
471 }
472
473 #[test]
474 fn adaptive_adjusts_for_compressibility() {
475 let repetitive = "use std::io;\n".repeat(200);
476 let diverse = (0..200).fold(String::new(), |mut s, i| {
477 use std::fmt::Write;
478 let _ = writeln!(s, "let var_{i} = compute_{i}(arg_{i});");
479 s
480 });
481
482 let base_rep = thresholds_for_path("main.rs");
483 let base_div = thresholds_for_path("main.rs");
484 assert!(
485 (base_rep.bpe_entropy - base_div.bpe_entropy).abs() < f64::EPSILON,
486 "same path should get same base thresholds"
487 );
488
489 let k_rep = kolmogorov_proxy(&repetitive);
490 let k_div = kolmogorov_proxy(&diverse);
491 assert!(
492 k_rep < k_div,
493 "repetitive content should have lower Kolmogorov proxy: {k_rep} vs {k_div}"
494 );
495 }
496
497 use crate::core::threshold_learning::QualitySignal;
498
499 fn arm_mean(project_root: &str, key: &str, arm: &str) -> f64 {
500 let mut store = crate::core::bandit::BanditStore::load(project_root);
501 store
502 .get_or_create(key)
503 .arms
504 .iter()
505 .find(|a| a.name == arm)
506 .map_or(0.5, crate::core::bandit::BanditArm::mean)
507 }
508
509 #[test]
510 fn real_failure_signal_penalizes_selected_arm() {
511 let _data = crate::core::data_dir::isolated_data_dir();
512 let root = "/fix1/penalize";
513 record_selected_arm(
514 "src/foo.rs",
515 root.into(),
516 "threshold:rs:md".into(),
517 "aggressive".into(),
518 );
519
520 let before = arm_mean(root, "threshold:rs:md", "aggressive");
521 for _ in 0..15 {
522 record_quality_signal("src/foo.rs", QualitySignal::Bounce);
523 }
524 record_quality_signal("src/foo.rs", QualitySignal::EditFail);
525 let after = arm_mean(root, "threshold:rs:md", "aggressive");
526
527 assert!(
528 after < before,
529 "bounce/edit-fail must lower the selected arm mean: {before} -> {after}"
530 );
531 }
532
533 #[test]
534 fn clean_and_wasted_signals_leave_bandit_untouched() {
535 let _data = crate::core::data_dir::isolated_data_dir();
536 let root = "/fix1/untouched";
537 record_selected_arm(
538 "a.rs",
539 root.into(),
540 "threshold:rs:sm".into(),
541 "balanced".into(),
542 );
543
544 let before = arm_mean(root, "threshold:rs:sm", "balanced");
545 record_quality_signal("a.rs", QualitySignal::CleanCompressed);
546 record_quality_signal("a.rs", QualitySignal::WastedFull);
547 let after = arm_mean(root, "threshold:rs:sm", "balanced");
548
549 assert!(
550 (before - after).abs() < f64::EPSILON,
551 "clean/wasted are learner-only: bandit mean must not move ({before} -> {after})"
552 );
553 }
554
555 #[test]
556 fn outcome_without_registered_arm_does_not_register_path() {
557 let _data = crate::core::data_dir::isolated_data_dir();
558 report_bandit_outcome_for_path("fix1/never-seen-xyz.rs", false);
560 let norm = crate::core::pathutil::normalize_tool_path("fix1/never-seen-xyz.rs");
561 let guard = SELECTED_ARMS
562 .lock()
563 .unwrap_or_else(std::sync::PoisonError::into_inner);
564 let registered = guard
565 .as_ref()
566 .is_some_and(|r| r.by_path.contains_key(&norm));
567 assert!(!registered, "no-op report must not create a registry entry");
568 }
569
570 #[test]
571 fn registry_evicts_oldest_beyond_cap() {
572 let _data = crate::core::data_dir::isolated_data_dir();
573 for i in 0..(ARM_REGISTRY_CAP + 5) {
574 record_selected_arm(
575 &format!("evict/f{i}.rs"),
576 "/fix1/evict".into(),
577 "threshold:rs:md".into(),
578 "balanced".into(),
579 );
580 }
581 let guard = SELECTED_ARMS
582 .lock()
583 .unwrap_or_else(std::sync::PoisonError::into_inner);
584 let reg = guard.as_ref().expect("registry initialized");
585 assert!(reg.order.len() <= ARM_REGISTRY_CAP);
586 assert_eq!(reg.order.len(), reg.by_path.len());
587 }
588}