Skip to main content

lean_ctx/core/
quality.rs

1use crate::core::preservation;
2use crate::core::tokens::count_tokens;
3
4macro_rules! static_regex {
5    ($pattern:expr) => {{
6        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
7        RE.get_or_init(|| {
8            regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
9        })
10    }};
11}
12
13const QUALITY_THRESHOLD: f64 = 0.95;
14const MIN_DENSITY: f64 = 0.15;
15
16#[derive(Debug, Clone)]
17pub struct QualityScore {
18    pub ast_score: f64,
19    pub identifier_score: f64,
20    pub line_score: f64,
21    pub density: f64,
22    pub composite: f64,
23    pub passed: bool,
24}
25
26impl QualityScore {
27    pub fn format_compact(&self) -> String {
28        if self.passed {
29            format!(
30                "Q:{:.0}% (ast:{:.0} id:{:.0} ln:{:.0} ρ:{:.0}) ✓",
31                self.composite * 100.0,
32                self.ast_score * 100.0,
33                self.identifier_score * 100.0,
34                self.line_score * 100.0,
35                self.density * 100.0,
36            )
37        } else {
38            format!(
39                "Q:{:.0}% (ast:{:.0} id:{:.0} ln:{:.0} ρ:{:.0}) ✗ BELOW THRESHOLD",
40                self.composite * 100.0,
41                self.ast_score * 100.0,
42                self.identifier_score * 100.0,
43                self.line_score * 100.0,
44                self.density * 100.0,
45            )
46        }
47    }
48}
49
50pub fn score(original: &str, compressed: &str, ext: &str) -> QualityScore {
51    let pres = preservation::measure(original, compressed, ext);
52    let ast_score = pres.overall();
53
54    let identifier_score = measure_identifier_preservation(original, compressed);
55    let line_score = measure_line_preservation(original, compressed);
56    let density = information_density(original, compressed, ext);
57
58    let composite = ast_score * 0.5 + identifier_score * 0.3 + line_score * 0.2;
59
60    let compression_ratio = measure_line_preservation(original, compressed);
61    let adaptive_threshold = QUALITY_THRESHOLD - 0.05 * (1.0 - compression_ratio);
62    let passed = composite >= adaptive_threshold && density >= MIN_DENSITY;
63
64    QualityScore {
65        ast_score,
66        identifier_score,
67        line_score,
68        density,
69        composite,
70        passed,
71    }
72}
73
74/// Information density: ratio of semantic tokens to total output tokens.
75/// Measures how much "meaning" per output token is preserved.
76pub fn information_density(original: &str, compressed: &str, ext: &str) -> f64 {
77    let output_tokens = count_tokens(compressed);
78    if output_tokens == 0 {
79        return 1.0;
80    }
81
82    let pres = preservation::measure(original, compressed, ext);
83    let semantic_items = pres.functions_preserved + pres.exports_preserved + pres.imports_preserved;
84    let ident_re = static_regex!(r"\b[a-zA-Z_][a-zA-Z0-9_]{3,}\b");
85    let unique_idents: std::collections::HashSet<&str> =
86        ident_re.find_iter(compressed).map(|m| m.as_str()).collect();
87    let semantic_token_estimate = semantic_items + unique_idents.len();
88
89    (semantic_token_estimate as f64 / output_tokens as f64).min(1.0)
90}
91
92/// Guard: returns compressed if quality passes, original otherwise
93pub fn guard(original: &str, compressed: &str, ext: &str) -> (String, QualityScore) {
94    let q = score(original, compressed, ext);
95    if q.passed {
96        (compressed.to_string(), q)
97    } else {
98        (original.to_string(), q)
99    }
100}
101
102fn measure_identifier_preservation(original: &str, compressed: &str) -> f64 {
103    let ident_re = static_regex!(r"\b[a-zA-Z_][a-zA-Z0-9_]{3,}\b");
104
105    let original_idents: std::collections::HashSet<&str> =
106        ident_re.find_iter(original).map(|m| m.as_str()).collect();
107
108    if original_idents.is_empty() {
109        return 1.0;
110    }
111
112    let preserved = original_idents
113        .iter()
114        .filter(|id| compressed.contains(*id))
115        .count();
116
117    preserved as f64 / original_idents.len() as f64
118}
119
120fn measure_line_preservation(original: &str, compressed: &str) -> f64 {
121    let original_lines: usize = original.lines().filter(|l| !l.trim().is_empty()).count();
122    if original_lines == 0 {
123        return 1.0;
124    }
125
126    let compressed_lines: usize = compressed.lines().filter(|l| !l.trim().is_empty()).count();
127    let ratio = compressed_lines as f64 / original_lines as f64;
128
129    ratio.min(1.0)
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn test_perfect_score_identity() {
138        let code = "fn main() {\n    println!(\"hello\");\n}\n";
139        let q = score(code, code, "rs");
140        assert!(q.composite >= 0.99);
141        assert!(q.passed);
142    }
143
144    #[test]
145    fn test_score_below_threshold_returns_original() {
146        let original = "fn validate_token() {\n    let result = check();\n    return result;\n}\n";
147        let bad_compressed = "removed everything";
148        let (output, q) = guard(original, bad_compressed, "rs");
149        assert!(!q.passed);
150        assert_eq!(output, original);
151    }
152
153    #[test]
154    fn test_good_compression_passes() {
155        let original = "fn validate_token() {\n    let result = check();\n    return result;\n}\n";
156        let compressed = "fn validate_token() { let result = check(); return result; }";
157        let q = score(original, compressed, "rs");
158        assert!(q.ast_score >= 0.9);
159        assert!(q.identifier_score >= 0.9);
160    }
161
162    #[test]
163    fn test_score_format_compact() {
164        let code = "fn main() {}\n";
165        let q = score(code, code, "rs");
166        let formatted = q.format_compact();
167        assert!(formatted.contains("Q:"));
168        assert!(formatted.contains("✓"));
169    }
170
171    #[test]
172    fn test_empty_content_scores_perfect() {
173        let q = score("", "", "rs");
174        assert!(q.passed);
175        assert!(q.composite >= 0.99);
176    }
177
178    #[test]
179    fn test_rust_file_with_structs() {
180        let original = "pub struct Config {\n    pub name: String,\n    pub value: usize,\n}\n\nimpl Config {\n    pub fn new() -> Self {\n        Self { name: String::new(), value: 0 }\n    }\n}\n";
181        let compressed = "pub struct Config { pub name: String, pub value: usize }\nimpl Config { pub fn new() -> Self { Self { name: String::new(), value: 0 } } }";
182        let q = score(original, compressed, "rs");
183        assert!(q.identifier_score >= 0.9);
184    }
185
186    #[test]
187    fn test_typescript_file() {
188        let original = "export function fetchData(url: string): Promise<Response> {\n  return fetch(url);\n}\n\nexport const API_URL = 'https://api.example.com';\n";
189        let compressed = "export function fetchData(url: string): Promise<Response> { return fetch(url); }\nexport const API_URL = 'https://api.example.com';";
190        let q = score(original, compressed, "ts");
191        assert!(q.identifier_score >= 0.9);
192    }
193
194    #[test]
195    fn test_python_file() {
196        let original = "def validate_credentials(username: str, password: str) -> bool:\n    user = find_user(username)\n    return verify_hash(user.password_hash, password)\n";
197        let compressed = "def validate_credentials(username, password): user = find_user(username); return verify_hash(user.password_hash, password)";
198        let q = score(original, compressed, "py");
199        assert!(q.identifier_score >= 0.8);
200    }
201
202    #[test]
203    fn test_density_high_for_meaningful_compression() {
204        let original = "pub fn calculate_total(items: Vec<Item>) -> f64 {\n    items.iter().map(|i| i.price * i.quantity as f64).sum()\n}\n";
205        let d = information_density(original, original, "rs");
206        assert!(d > 0.15, "identity should have high density: {d}");
207    }
208
209    #[test]
210    fn test_density_low_for_garbage() {
211        let original = "pub fn calculate_total(items: Vec<Item>) -> f64 {\n    items.iter().map(|i| i.price).sum()\n}\n";
212        let garbage = "xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx";
213        let d = information_density(original, garbage, "rs");
214        assert!(d < 0.5, "garbage output should have low density: {d}");
215    }
216
217    #[test]
218    fn test_density_in_quality_score() {
219        let code = "fn main() {\n    println!(\"hello\");\n}\n";
220        let q = score(code, code, "rs");
221        assert!(q.density > 0.0, "density should be computed");
222    }
223
224    #[test]
225    fn test_adaptive_threshold_looser_for_heavy_compression() {
226        let original = "fn validate_token() {\n    let result = check();\n    return result;\n}\nfn other() {\n    let x = 1;\n}\n";
227        let compressed = "fn validate_token() { let result = check(); return result; }";
228        let q = score(original, compressed, "rs");
229        assert!(
230            q.density >= MIN_DENSITY,
231            "compressed code should maintain minimum density"
232        );
233    }
234}