Skip to main content

lean_ctx_ext/core/
quality.rs

1// SPDX-License-Identifier: Apache-2.0
2use crate::core::preservation;
3use crate::core::tokens::count_tokens;
4
5macro_rules! static_regex {
6    ($pattern:expr_2021) => {{
7        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
8        RE.get_or_init(|| {
9            regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
10        })
11    }};
12}
13
14const QUALITY_THRESHOLD: f64 = 0.95;
15const MIN_DENSITY: f64 = 0.15;
16
17#[derive(Debug, Clone)]
18pub struct QualityScore {
19    pub ast_score: f64,
20    pub identifier_score: f64,
21    pub line_score: f64,
22    pub density: f64,
23    pub composite: f64,
24    pub passed: bool,
25}
26
27impl QualityScore {
28    pub fn format_compact(&self) -> String {
29        if self.passed {
30            format!(
31                "Q:{:.0}% (ast:{:.0} id:{:.0} ln:{:.0} ρ:{:.0}) ✓",
32                self.composite * 100.0,
33                self.ast_score * 100.0,
34                self.identifier_score * 100.0,
35                self.line_score * 100.0,
36                self.density * 100.0,
37            )
38        } else {
39            format!(
40                "Q:{:.0}% (ast:{:.0} id:{:.0} ln:{:.0} ρ:{:.0}) ✗ BELOW THRESHOLD",
41                self.composite * 100.0,
42                self.ast_score * 100.0,
43                self.identifier_score * 100.0,
44                self.line_score * 100.0,
45                self.density * 100.0,
46            )
47        }
48    }
49}
50
51pub fn score(original: &str, compressed: &str, ext: &str) -> QualityScore {
52    let pres = preservation::measure(original, compressed, ext);
53    let ast_score = pres.overall();
54
55    let identifier_score = measure_identifier_preservation(original, compressed);
56    let line_score = measure_line_preservation(original, compressed);
57    let density = information_density(original, compressed, ext);
58
59    let composite = ast_score * 0.5 + identifier_score * 0.3 + line_score * 0.2;
60
61    let compression_ratio = measure_line_preservation(original, compressed);
62    let adaptive_threshold = QUALITY_THRESHOLD - 0.05 * (1.0 - compression_ratio);
63    let passed = composite >= adaptive_threshold && density >= MIN_DENSITY;
64
65    QualityScore {
66        ast_score,
67        identifier_score,
68        line_score,
69        density,
70        composite,
71        passed,
72    }
73}
74
75/// Information density: ratio of semantic tokens to total output tokens.
76/// Measures how much "meaning" per output token is preserved.
77pub fn information_density(original: &str, compressed: &str, ext: &str) -> f64 {
78    let output_tokens = count_tokens(compressed);
79    if output_tokens == 0 {
80        return 1.0;
81    }
82
83    let pres = preservation::measure(original, compressed, ext);
84    let semantic_items = pres.functions_preserved + pres.exports_preserved + pres.imports_preserved;
85    let ident_re = static_regex!(r"\b[a-zA-Z_][a-zA-Z0-9_]{3,}\b");
86    let unique_idents: std::collections::HashSet<&str> =
87        ident_re.find_iter(compressed).map(|m| m.as_str()).collect();
88    let semantic_token_estimate = semantic_items + unique_idents.len();
89
90    (semantic_token_estimate as f64 / output_tokens as f64).min(1.0)
91}
92
93/// Guard: returns compressed if quality passes, original otherwise
94pub fn guard(original: &str, compressed: &str, ext: &str) -> (String, QualityScore) {
95    let q = score(original, compressed, ext);
96    if q.passed {
97        (compressed.to_string(), q)
98    } else {
99        (original.to_string(), q)
100    }
101}
102
103/// #940: density-specific guard that does NOT penalise line reduction.
104///
105/// The standard `score()` composite weights `line_score` at 20% and the
106/// adaptive threshold rises as `line_score` drops — so a density target of
107/// 0.4 (which *intentionally* discards ~60% of lines) always fails by
108/// construction. Density mode needs a structure-only gate: AST + identifiers.
109pub fn guard_density(
110    original: &str,
111    compressed: &str,
112    ext: &str,
113    target: f64,
114) -> (String, QualityScore) {
115    let pres = preservation::measure(original, compressed, ext);
116    let ast_score = pres.overall();
117    let identifier_score = measure_identifier_preservation(original, compressed);
118    let line_score = measure_line_preservation(original, compressed);
119    let density = information_density(original, compressed, ext);
120
121    // Structure-only composite: ignore line_score for density mode.
122    let structure_composite = ast_score * 0.6 + identifier_score * 0.4;
123
124    // Structure must survive intact: definitions, exports and imports. Losing
125    // fewer lines is the *point* of density mode, never a reason to reject.
126    let structure_threshold = 0.85;
127    // Identifiers are judged against the requested budget: a view holding 30%
128    // of the tokens cannot hold 62% of the identifiers (what a fixed composite
129    // bar demanded, so only targets ≥ 0.8 ever passed), but it must hold at
130    // least as large a share of them as of the tokens — no dilution.
131    let identifier_floor = target.clamp(0.05, structure_threshold);
132    // Information density likewise against the file itself: source code sits
133    // at ρ≈0.07–0.14 *uncompressed*, so the absolute floor rejected every
134    // density view of real code, including ones denser than the original.
135    let density_floor = MIN_DENSITY.min(information_density(original, original, ext));
136    let passed = ast_score >= structure_threshold
137        && identifier_score >= identifier_floor
138        && density >= density_floor;
139
140    let q = QualityScore {
141        ast_score,
142        identifier_score,
143        line_score,
144        density,
145        composite: structure_composite,
146        passed,
147    };
148
149    if passed {
150        (compressed.to_string(), q)
151    } else {
152        tracing::debug!(
153            target = target,
154            composite = structure_composite,
155            threshold = structure_threshold,
156            "density quality gate rejected → full fallback"
157        );
158        (original.to_string(), q)
159    }
160}
161
162fn measure_identifier_preservation(original: &str, compressed: &str) -> f64 {
163    let ident_re = static_regex!(r"\b[a-zA-Z_][a-zA-Z0-9_]{3,}\b");
164
165    let original_idents: std::collections::HashSet<&str> =
166        ident_re.find_iter(original).map(|m| m.as_str()).collect();
167
168    if original_idents.is_empty() {
169        return 1.0;
170    }
171
172    let preserved = original_idents
173        .iter()
174        .filter(|id| compressed.contains(*id))
175        .count();
176
177    preserved as f64 / original_idents.len() as f64
178}
179
180fn measure_line_preservation(original: &str, compressed: &str) -> f64 {
181    let original_lines: usize = original.lines().filter(|l| !l.trim().is_empty()).count();
182    if original_lines == 0 {
183        return 1.0;
184    }
185
186    let compressed_lines: usize = compressed.lines().filter(|l| !l.trim().is_empty()).count();
187    let ratio = compressed_lines as f64 / original_lines as f64;
188
189    ratio.min(1.0)
190}
191
192#[cfg(test)]
193pub mod tests {
194    use super::*;
195
196    #[test]
197    fn test_perfect_score_identity() {
198        let code = "fn main() {\n    println!(\"hello\");\n}\n";
199        let q = score(code, code, "rs");
200        assert!(q.composite >= 0.99);
201        assert!(q.passed);
202    }
203
204    #[test]
205    fn test_score_below_threshold_returns_original() {
206        let original = "fn validate_token() {\n    let result = check();\n    return result;\n}\n";
207        let bad_compressed = "removed everything";
208        let (output, q) = guard(original, bad_compressed, "rs");
209        assert!(!q.passed);
210        assert_eq!(output, original);
211    }
212
213    #[test]
214    fn test_good_compression_passes() {
215        let original = "fn validate_token() {\n    let result = check();\n    return result;\n}\n";
216        let compressed = "fn validate_token() { let result = check(); return result; }";
217        let q = score(original, compressed, "rs");
218        assert!(q.ast_score >= 0.9);
219        assert!(q.identifier_score >= 0.9);
220    }
221
222    #[test]
223    fn test_score_format_compact() {
224        let code = "fn main() {}\n";
225        let q = score(code, code, "rs");
226        let formatted = q.format_compact();
227        assert!(formatted.contains("Q:"));
228        assert!(formatted.contains("✓"));
229    }
230
231    #[test]
232    fn test_empty_content_scores_perfect() {
233        let q = score("", "", "rs");
234        assert!(q.passed);
235        assert!(q.composite >= 0.99);
236    }
237
238    #[test]
239    fn test_rust_file_with_structs() {
240        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";
241        let compressed = "pub struct Config { pub name: String, pub value: usize }\nimpl Config { pub fn new() -> Self { Self { name: String::new(), value: 0 } } }";
242        let q = score(original, compressed, "rs");
243        assert!(q.identifier_score >= 0.9);
244    }
245
246    #[test]
247    fn test_typescript_file() {
248        let original = "export function fetchData(url: string): Promise<Response> {\n  return fetch(url);\n}\n\nexport const API_URL = 'https://api.example.com';\n";
249        let compressed = "export function fetchData(url: string): Promise<Response> { return fetch(url); }\nexport const API_URL = 'https://api.example.com';";
250        let q = score(original, compressed, "ts");
251        assert!(q.identifier_score >= 0.9);
252    }
253
254    #[test]
255    fn test_python_file() {
256        let original = "def validate_credentials(username: str, password: str) -> bool:\n    user = find_user(username)\n    return verify_hash(user.password_hash, password)\n";
257        let compressed = "def validate_credentials(username, password): user = find_user(username); return verify_hash(user.password_hash, password)";
258        let q = score(original, compressed, "py");
259        assert!(q.identifier_score >= 0.8);
260    }
261
262    #[test]
263    fn test_density_high_for_meaningful_compression() {
264        let original = "pub fn calculate_total(items: Vec<Item>) -> f64 {\n    items.iter().map(|i| i.price * i.quantity as f64).sum()\n}\n";
265        let d = information_density(original, original, "rs");
266        assert!(d > 0.15, "identity should have high density: {d}");
267    }
268
269    #[test]
270    fn test_density_low_for_garbage() {
271        let original = "pub fn calculate_total(items: Vec<Item>) -> f64 {\n    items.iter().map(|i| i.price).sum()\n}\n";
272        let garbage = "xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx";
273        let d = information_density(original, garbage, "rs");
274        assert!(d < 0.5, "garbage output should have low density: {d}");
275    }
276
277    #[test]
278    fn test_density_in_quality_score() {
279        let code = "fn main() {\n    println!(\"hello\");\n}\n";
280        let q = score(code, code, "rs");
281        assert!(q.density > 0.0, "density should be computed");
282    }
283
284    #[test]
285    fn test_adaptive_threshold_looser_for_heavy_compression() {
286        let original = "fn validate_token() {\n    let result = check();\n    return result;\n}\nfn other() {\n    let x = 1;\n}\n";
287        let compressed = "fn validate_token() { let result = check(); return result; }";
288        let q = score(original, compressed, "rs");
289        assert!(
290            q.density >= MIN_DENSITY,
291            "compressed code should maintain minimum density"
292        );
293    }
294}