Skip to main content

lean_ctx/core/terse/
engine.rs

1//! Layer 1: Deterministic output compression.
2//!
3//! Replaces the legacy `compress_terse`/`compress_ultra` with a scoring-based
4//! approach that preserves information-dense lines and removes low-value content.
5
6use super::counter;
7use super::dictionaries::{self, DictLevel};
8use super::quality::{self, QualityConfig, QualityReport};
9use super::scoring;
10use crate::core::config::CompressionLevel;
11
12/// Threshold below which a line is considered low-information and may be removed.
13const LOW_SCORE_THRESHOLD: f32 = 2.5;
14
15const STANDARD_SCORE_THRESHOLD: f32 = 3.0;
16const MAX_SCORE_THRESHOLD: f32 = 3.5;
17
18/// Result of Layer 1 compression.
19#[derive(Debug)]
20pub struct EngineResult {
21    pub output: String,
22    pub tokens_before: u32,
23    pub tokens_after: u32,
24    pub quality: QualityReport,
25    pub lines_removed: usize,
26    pub lines_total: usize,
27}
28
29const MIN_LINES_FOR_COMPRESSION: usize = 5;
30
31/// Runs Layer 1 deterministic compression on the input text.
32pub fn compress(text: &str, level: &CompressionLevel) -> EngineResult {
33    let tokens_before = counter::count(text);
34    let lines_total = text.lines().count();
35
36    if !level.is_active() || text.is_empty() || lines_total < MIN_LINES_FOR_COMPRESSION {
37        return EngineResult {
38            output: text.to_string(),
39            tokens_before,
40            tokens_after: tokens_before,
41            quality: quality::check(
42                text,
43                text,
44                tokens_before,
45                tokens_before,
46                &QualityConfig::default(),
47            ),
48            lines_removed: 0,
49            lines_total,
50        };
51    }
52
53    let result = compress_at_level(text, tokens_before, level);
54
55    if result.quality.passed {
56        return result;
57    }
58
59    if matches!(level, CompressionLevel::Max | CompressionLevel::Raw) {
60        let fallback = compress_at_level(text, tokens_before, &CompressionLevel::Standard);
61        if fallback.quality.passed {
62            return fallback;
63        }
64    }
65
66    EngineResult {
67        output: text.to_string(),
68        tokens_before,
69        tokens_after: tokens_before,
70        quality: result.quality,
71        lines_removed: 0,
72        lines_total: text.lines().count(),
73    }
74}
75
76fn compress_at_level(text: &str, tokens_before: u32, level: &CompressionLevel) -> EngineResult {
77    let scores = scoring::score_lines(text);
78    let lines: Vec<&str> = text.lines().collect();
79    let lines_total = lines.len();
80
81    let threshold = match level {
82        CompressionLevel::Max | CompressionLevel::Raw => MAX_SCORE_THRESHOLD,
83        CompressionLevel::Standard => STANDARD_SCORE_THRESHOLD,
84        CompressionLevel::Lite | CompressionLevel::Off => LOW_SCORE_THRESHOLD,
85    };
86
87    let mut kept_lines = Vec::new();
88    let mut lines_removed = 0;
89
90    for (score, line) in scores.iter().zip(lines.iter()) {
91        let trimmed = line.trim();
92
93        if trimmed.is_empty() {
94            lines_removed += 1;
95            continue;
96        }
97
98        // Section delimiters are semantic record boundaries. Dropping one then
99        // joining the surviving lines can attach a later record to an earlier
100        // heading, so they must remain hard breaks regardless of score.
101        if is_section_boundary(trimmed) {
102            kept_lines.push(*line);
103            continue;
104        }
105
106        if is_pure_decoration(trimmed) {
107            lines_removed += 1;
108            continue;
109        }
110
111        if is_filler_line(trimmed) && !score.has_structural_marker {
112            lines_removed += 1;
113            continue;
114        }
115
116        if score.combined < threshold && !score.has_structural_marker {
117            lines_removed += 1;
118            continue;
119        }
120
121        kept_lines.push(*line);
122    }
123
124    let filtered = kept_lines.join("\n");
125
126    let quality_config = match level {
127        CompressionLevel::Max | CompressionLevel::Raw => QualityConfig {
128            min_identifier_preservation: 0.80,
129            ..QualityConfig::default()
130        },
131        _ => QualityConfig::default(),
132    };
133
134    let filtered_tokens = counter::count(&filtered);
135    let quality_report = quality::check(
136        text,
137        &filtered,
138        tokens_before,
139        filtered_tokens,
140        &quality_config,
141    );
142
143    if !quality_report.passed {
144        return EngineResult {
145            output: text.to_string(),
146            tokens_before,
147            tokens_after: tokens_before,
148            quality: quality_report,
149            lines_removed: 0,
150            lines_total,
151        };
152    }
153
154    let dict_level = match level {
155        CompressionLevel::Max | CompressionLevel::Raw | CompressionLevel::Standard => {
156            DictLevel::Full
157        }
158        CompressionLevel::Lite | CompressionLevel::Off => DictLevel::General,
159    };
160    let compressed = dictionaries::apply_dictionaries(&filtered, dict_level);
161    let compressed = match dict_level {
162        DictLevel::Full => super::auto_dict::apply(&compressed).unwrap_or(compressed),
163        DictLevel::General => compressed,
164    };
165    let tokens_after = counter::count(&compressed);
166
167    EngineResult {
168        output: compressed,
169        tokens_before,
170        tokens_after,
171        quality: quality_report,
172        lines_removed,
173        lines_total,
174    }
175}
176
177fn is_filler_line(line: &str) -> bool {
178    let trimmed = line.trim();
179
180    if trimmed == "|" || trimmed == "| " {
181        return true;
182    }
183
184    let lower = line.to_lowercase();
185    const FILLER_PATTERNS: &[&str] = &[
186        "use \"git add",
187        "use \"git restore",
188        "(use \"git",
189        "run with `rust_backtrace",
190        "for more information about this error",
191        "try `rustc --explain",
192        "run `npm fund`",
193        "run `npm audit`",
194        "to address all issues",
195        "sending build context",
196        "using cache",
197        "packages are looking for funding",
198        "no changes added to commit",
199        "help: ",
200        "= note: ",
201        "---> running in",
202    ];
203    FILLER_PATTERNS.iter().any(|p| lower.contains(p))
204}
205
206fn is_pure_decoration(line: &str) -> bool {
207    let trimmed = line.trim();
208
209    if trimmed.is_empty() {
210        return true;
211    }
212
213    if trimmed.chars().all(|c| c == '|' || c.is_whitespace()) {
214        return true;
215    }
216
217    if line.len() < 3 {
218        return false;
219    }
220
221    if line.starts_with("//") || line.starts_with('#') || line.starts_with("--") {
222        let content = line
223            .trim_start_matches('/')
224            .trim_start_matches('#')
225            .trim_start_matches('-')
226            .trim();
227        return content.is_empty() || is_banner_chars(content);
228    }
229
230    is_banner_chars(line)
231}
232
233/// True when a line uses a common section-header delimiter. These delimiters
234/// separate records in shell output and must never be removed during filtering.
235fn is_section_boundary(line: &str) -> bool {
236    let trimmed = line.trim_start();
237    ["===", "---", "###", "***", "___", ":::"]
238        .iter()
239        .any(|prefix| trimmed.starts_with(prefix))
240}
241
242fn is_banner_chars(line: &str) -> bool {
243    let chars: Vec<char> = line.chars().collect();
244    if chars.len() < 4 {
245        return false;
246    }
247    let first = chars[0];
248    if matches!(
249        first,
250        '=' | '-' | '*' | '─' | '━' | '▀' | '▄' | '╔' | '╚' | '║' | '░' | '█' | '═'
251    ) {
252        let same_count = chars.iter().filter(|c| **c == first).count();
253        return same_count as f64 / chars.len() as f64 > 0.6;
254    }
255    false
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn compress_off_returns_original() {
264        let text = "hello world\n\nsome blank lines\n\n";
265        let result = compress(text, &CompressionLevel::Off);
266        assert_eq!(result.output, text);
267        assert_eq!(result.lines_removed, 0);
268    }
269
270    #[test]
271    fn compress_lite_removes_blank_lines() {
272        let text = "line one\n\n\nline two\n\n";
273        let result = compress(text, &CompressionLevel::Lite);
274        assert!(
275            !result.output.contains("\n\n"),
276            "blank lines should be removed"
277        );
278    }
279
280    #[test]
281    fn compress_preserves_paths() {
282        let text = "error in src/main.rs at line 42\n\nsome blank\n\n";
283        let result = compress(text, &CompressionLevel::Standard);
284        assert!(
285            result.output.contains("src/main.rs"),
286            "path must be preserved"
287        );
288    }
289
290    #[test]
291    fn decoration_detection() {
292        assert!(is_pure_decoration("════════════════════"));
293        assert!(is_pure_decoration("--------------------"));
294        assert!(is_pure_decoration("// ================"));
295        assert!(!is_pure_decoration("error: mismatched types"));
296    }
297
298    #[test]
299    fn compress_preserves_multi_section_record_boundaries() {
300        let text = "record alpha payload remains associated with alpha\n\
301                    additional alpha detail for the first record\n\
302                    ===\n\
303                    record beta payload remains associated with beta\n\
304                    additional beta detail for the second record\n\
305                    ---\n\
306                    record gamma payload remains associated with gamma\n\
307                    ###\n\
308                    record delta payload remains associated with delta";
309
310        let result = compress(text, &CompressionLevel::Standard);
311
312        assert!(
313            result.output.contains("==="),
314            "first boundary missing: {}",
315            result.output
316        );
317        assert!(
318            result.output.contains("---"),
319            "second boundary missing: {}",
320            result.output
321        );
322        assert!(
323            result.output.contains("###"),
324            "third boundary missing: {}",
325            result.output
326        );
327        let alpha = result.output.find("record alpha").unwrap();
328        let first_boundary = result.output.find("===").unwrap();
329        let beta = result.output.find("record beta").unwrap();
330        let second_boundary = result.output.find("---").unwrap();
331        let gamma = result.output.find("record gamma").unwrap();
332        let third_boundary = result.output.find("###").unwrap();
333        let delta = result.output.find("record delta").unwrap();
334        assert!(alpha < first_boundary && first_boundary < beta);
335        assert!(beta < second_boundary && second_boundary < gamma);
336        assert!(gamma < third_boundary && third_boundary < delta);
337    }
338
339    #[test]
340    fn compress_returns_token_counts() {
341        let text = "Hello world from the compression engine test";
342        let result = compress(text, &CompressionLevel::Lite);
343        assert!(result.tokens_before > 0);
344    }
345}