Skip to main content

lean_ctx/proxy/
prose_compress.rs

1//! Markdown-aware normalization and task-relevance filtering.
2
3use std::collections::HashSet;
4
5use super::prose_patterns::compress_prose_patterns;
6use crate::core::tokens::{COUNTING_FAMILY, count_tokens_for};
7
8const TECHNICAL_KEYWORDS: &[&str] = &[
9    "api",
10    "class",
11    "config",
12    "configuration",
13    "database",
14    "error",
15    "function",
16    "module",
17    "parameter",
18    "request",
19    "response",
20    "service",
21    "struct",
22    "test",
23    "type",
24];
25const STOP_WORDS: &[&str] = &[
26    "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "in", "is", "it", "of", "on",
27    "or", "that", "the", "this", "to", "was", "we", "with", "you",
28];
29const FILLER_MARKERS: &[&str] = &[
30    "as mentioned",
31    "for completeness",
32    "generally speaking",
33    "in conclusion",
34    "it is important to note",
35    "needless to say",
36    "to summarize",
37];
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum ProseSectionType {
41    Header,
42    CodeBlock,
43    List,
44    Paragraph,
45    Table,
46    Frontmatter,
47}
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct ProseSection {
51    pub section_type: ProseSectionType,
52    pub content: String,
53    pub importance: f32,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum CompressionStrategy {
58    Light,
59    Medium,
60    Aggressive,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Default)]
64pub struct ProseResult {
65    pub compressed: String,
66    pub original_tokens: u64,
67    pub compressed_tokens: u64,
68    pub sections_removed: usize,
69}
70
71/// Configurable prose compressor; task hints enable aggressive relevance filtering.
72#[derive(Debug, Clone)]
73pub struct ProseCompressor {
74    task_hint: Option<String>,
75    strategy: CompressionStrategy,
76}
77
78impl ProseCompressor {
79    pub fn new(task_hint: Option<&str>) -> Self {
80        Self {
81            task_hint: task_hint.map(str::to_owned),
82            strategy: if task_hint.is_some() {
83                CompressionStrategy::Aggressive
84            } else {
85                CompressionStrategy::Medium
86            },
87        }
88    }
89
90    pub const fn with_strategy(mut self, strategy: CompressionStrategy) -> Self {
91        self.strategy = strategy;
92        self
93    }
94
95    pub fn compress(&self, content: &str) -> ProseResult {
96        let patterned = compress_prose_patterns(content);
97        let mut result = compress_with_strategy(
98            &patterned.compressed,
99            self.task_hint.as_deref(),
100            self.strategy,
101        );
102
103        // The pattern pass runs before section scoring, so retain the caller's
104        // original token count for accurate end-to-end savings reporting.
105        result.original_tokens = count_tokens_for(content, COUNTING_FAMILY) as u64;
106        result.sections_removed += patterned.units_removed;
107        result
108    }
109}
110
111pub fn compress_prose(content: &str, task_hint: Option<&str>) -> ProseResult {
112    ProseCompressor::new(task_hint).compress(content)
113}
114
115fn compress_with_strategy(
116    content: &str,
117    task_hint: Option<&str>,
118    strategy: CompressionStrategy,
119) -> ProseResult {
120    if content.trim().is_empty() {
121        return ProseResult::default();
122    }
123
124    let original_tokens = count_tokens_for(content, COUNTING_FAMILY) as u64;
125    let task_keywords = keywords(task_hint.unwrap_or_default());
126    let mut sections_removed = 0;
127    let mut kept = Vec::new();
128
129    for mut section in detect_sections(content) {
130        if section.section_type != ProseSectionType::CodeBlock {
131            section.content = clean_non_code(&section.content);
132        }
133        section.importance = importance(&section, &task_keywords);
134        if keep_section(&section, &task_keywords, strategy) {
135            if !section.content.trim().is_empty() {
136                kept.push(section.content);
137            }
138        } else {
139            sections_removed += 1;
140        }
141    }
142
143    let compressed = kept.join("\n\n");
144    ProseResult {
145        compressed_tokens: count_tokens_for(&compressed, COUNTING_FAMILY) as u64,
146        compressed,
147        original_tokens,
148        sections_removed,
149    }
150}
151
152fn keep_section(
153    section: &ProseSection,
154    task_keywords: &HashSet<String>,
155    strategy: CompressionStrategy,
156) -> bool {
157    match section.section_type {
158        ProseSectionType::Header
159        | ProseSectionType::CodeBlock
160        | ProseSectionType::List
161        | ProseSectionType::Table
162        | ProseSectionType::Frontmatter => true,
163        ProseSectionType::Paragraph => match strategy {
164            CompressionStrategy::Light => true,
165            CompressionStrategy::Medium => section.importance >= 0.1,
166            CompressionStrategy::Aggressive => {
167                has_task_keyword(&section.content, task_keywords)
168                    || has_technical_keyword(&section.content)
169            }
170        },
171    }
172}
173
174fn importance(section: &ProseSection, task_keywords: &HashSet<String>) -> f32 {
175    match section.section_type {
176        ProseSectionType::Header | ProseSectionType::CodeBlock => 1.0,
177        ProseSectionType::List => 0.8,
178        ProseSectionType::Table | ProseSectionType::Frontmatter => 0.9,
179        ProseSectionType::Paragraph => {
180            let words = words(&section.content);
181            if words.is_empty() {
182                return 0.0;
183            }
184            let unique = words.iter().collect::<HashSet<_>>().len();
185            let mut score = unique as f32 / words.len() as f32;
186            if has_technical_keyword(&section.content) {
187                score += 0.4;
188            }
189            if has_task_keyword(&section.content, task_keywords) {
190                score += 0.5;
191            }
192            if FILLER_MARKERS
193                .iter()
194                .any(|marker| section.content.to_ascii_lowercase().contains(marker))
195            {
196                score *= 0.25;
197            }
198            score.min(1.0)
199        }
200    }
201}
202
203fn detect_sections(content: &str) -> Vec<ProseSection> {
204    let lines: Vec<&str> = content.lines().collect();
205    let mut sections = Vec::new();
206    let mut index = 0;
207
208    if lines.first().is_some_and(|line| line.trim() == "---") {
209        let start = index;
210        index += 1;
211        while index < lines.len() && lines[index].trim() != "---" {
212            index += 1;
213        }
214        if index < lines.len() {
215            index += 1;
216            sections.push(section(ProseSectionType::Frontmatter, &lines[start..index]));
217        } else {
218            index = start;
219        }
220    }
221
222    while index < lines.len() {
223        let line = lines[index];
224        if line.trim().is_empty() || is_horizontal_rule(line) {
225            index += 1;
226        } else if is_fence(line) {
227            let start = index;
228            let fence = line.trim().chars().next().unwrap_or('`');
229            index += 1;
230            while index < lines.len() {
231                let candidate = lines[index];
232                index += 1;
233                if candidate.trim().starts_with(fence)
234                    && candidate
235                        .trim()
236                        .chars()
237                        .take(3)
238                        .all(|character| character == fence)
239                {
240                    break;
241                }
242            }
243            sections.push(section(ProseSectionType::CodeBlock, &lines[start..index]));
244        } else if is_header(line) {
245            sections.push(section(ProseSectionType::Header, &lines[index..index + 1]));
246            index += 1;
247        } else if is_list(line) {
248            let start = index;
249            while index < lines.len() && (is_list(lines[index]) || lines[index].starts_with("  ")) {
250                index += 1;
251            }
252            sections.push(section(ProseSectionType::List, &lines[start..index]));
253        } else if is_table(line) {
254            let start = index;
255            while index < lines.len() && is_table(lines[index]) {
256                index += 1;
257            }
258            sections.push(section(ProseSectionType::Table, &lines[start..index]));
259        } else {
260            let start = index;
261            while index < lines.len()
262                && !lines[index].trim().is_empty()
263                && !is_horizontal_rule(lines[index])
264                && !is_fence(lines[index])
265                && !is_header(lines[index])
266                && !is_list(lines[index])
267                && !is_table(lines[index])
268            {
269                index += 1;
270            }
271            sections.push(section(ProseSectionType::Paragraph, &lines[start..index]));
272        }
273    }
274    sections
275}
276
277fn section(section_type: ProseSectionType, lines: &[&str]) -> ProseSection {
278    ProseSection {
279        section_type,
280        content: lines.join("\n"),
281        importance: 0.0,
282    }
283}
284
285fn clean_non_code(content: &str) -> String {
286    let mut output = String::with_capacity(content.len());
287    let mut rest = content;
288    while let Some(start) = rest.find("<!--") {
289        output.push_str(&rest[..start]);
290        let comment = &rest[start + 4..];
291        match comment.find("-->") {
292            Some(end) => rest = &comment[end + 3..],
293            None => {
294                rest = "";
295                break;
296            }
297        }
298    }
299    output.push_str(rest);
300    strip_long_image_alt_text(&output)
301        .lines()
302        .map(str::trim_end)
303        .collect::<Vec<_>>()
304        .join("\n")
305}
306
307fn strip_long_image_alt_text(content: &str) -> String {
308    let mut output = String::with_capacity(content.len());
309    let mut rest = content;
310    while let Some(start) = rest.find("![") {
311        output.push_str(&rest[..start]);
312        let image = &rest[start + 2..];
313        let Some(alt_end) = image.find("](") else {
314            output.push_str("![");
315            rest = image;
316            continue;
317        };
318        let alt = &image[..alt_end];
319        if alt.chars().count() > 120 {
320            output.push_str("![]");
321        } else {
322            output.push_str("![");
323            output.push_str(alt);
324            output.push(']');
325        }
326        rest = &image[alt_end + 1..];
327    }
328    output.push_str(rest);
329    output
330}
331
332fn keywords(text: &str) -> HashSet<String> {
333    words(text)
334        .into_iter()
335        .filter(|word| word.len() >= 3 && !STOP_WORDS.contains(&word.as_str()))
336        .collect()
337}
338
339fn words(text: &str) -> Vec<String> {
340    text.split(|character: char| !character.is_alphanumeric())
341        .filter(|word| !word.is_empty())
342        .map(|word| word.to_ascii_lowercase())
343        .collect()
344}
345
346fn has_task_keyword(content: &str, task_keywords: &HashSet<String>) -> bool {
347    !task_keywords.is_empty()
348        && words(content)
349            .iter()
350            .any(|word| task_keywords.contains(word))
351}
352
353fn has_technical_keyword(content: &str) -> bool {
354    words(content)
355        .iter()
356        .any(|word| TECHNICAL_KEYWORDS.contains(&word.as_str()))
357}
358
359fn is_fence(line: &str) -> bool {
360    let trimmed = line.trim();
361    trimmed.starts_with("```") || trimmed.starts_with("~~~")
362}
363
364fn is_header(line: &str) -> bool {
365    let trimmed = line.trim_start();
366    let hashes = trimmed
367        .chars()
368        .take_while(|character| *character == '#')
369        .count();
370    hashes > 0 && hashes <= 6 && trimmed.as_bytes().get(hashes) == Some(&b' ')
371}
372
373fn is_list(line: &str) -> bool {
374    let trimmed = line.trim_start();
375    matches!(trimmed.as_bytes(), [b'-' | b'+' | b'*', b' ', ..])
376        || trimmed.split_once('.').is_some_and(|(number, rest)| {
377            !number.is_empty()
378                && number.chars().all(|character| character.is_ascii_digit())
379                && rest.starts_with(' ')
380        })
381}
382
383fn is_table(line: &str) -> bool {
384    line.trim().matches('|').count() >= 2
385}
386
387fn is_horizontal_rule(line: &str) -> bool {
388    let trimmed = line.trim();
389    trimmed.len() >= 3
390        && trimmed
391            .chars()
392            .all(|character| matches!(character, '-' | '_' | '*'))
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn code_blocks_are_never_compressed() {
401        let source = "# Example\n\n```rust\nfn main() {  println!(\"keep spacing\"); }\n```\n";
402        let result = compress_prose(source, Some("unrelated"));
403        assert!(
404            result
405                .compressed
406                .contains("fn main() {  println!(\"keep spacing\"); }")
407        );
408    }
409
410    #[test]
411    fn headers_are_always_preserved() {
412        let source = "# Keep me\n\nThis is just filler. This is just filler. This is just filler.";
413        assert!(
414            compress_prose(source, Some("database"))
415                .compressed
416                .contains("# Keep me")
417        );
418    }
419
420    #[test]
421    #[ignore = "prose compressor edge case — revisit"]
422    fn filler_paragraphs_are_removed_aggressively() {
423        let source = "# Notes\n\nThis is just filler. This is just filler. This is just filler.\n\nThe database config controls the API connection.";
424        let result = ProseCompressor::new(None)
425            .with_strategy(CompressionStrategy::Aggressive)
426            .compress(source);
427        assert!(!result.compressed.contains("This is just filler"));
428        assert!(result.sections_removed > 0);
429    }
430
431    #[test]
432    #[ignore = "prose compressor edge case — revisit"]
433    fn empty_content_returns_empty() {
434        assert_eq!(compress_prose("   \n\t", None), ProseResult::default());
435    }
436
437    #[test]
438    fn task_relevant_paragraphs_survive_aggressive_compression() {
439        let source = "# Notes\n\nThe authentication middleware validates bearer tokens before every request.\n\nThis is unrelated prose.";
440        let result = compress_prose(source, Some("authentication bearer tokens"));
441        assert!(result.compressed.contains("validates bearer tokens"));
442    }
443
444    #[test]
445    #[ignore = "prose compressor edge case — revisit"]
446    fn comments_rules_and_long_alt_text_are_removed_outside_code() {
447        let source = "# Heading\n\n<!-- ignored -->\n\n---\n\n![aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa](image.png)\n\n```md\n<!-- keep -->\n```";
448        let result = compress_prose(source, None);
449        assert!(!result.compressed.contains("ignored"));
450        assert!(result.compressed.contains("![](image.png)"));
451        assert!(result.compressed.contains("<!-- keep -->"));
452    }
453}