1use 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#[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 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(§ion.content);
132 }
133 section.importance = importance(§ion, &task_keywords);
134 if keep_section(§ion, &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 if compressed.trim().is_empty() && !content.trim().is_empty() {
151 return ProseResult {
152 compressed: content.to_string(),
153 original_tokens,
154 compressed_tokens: original_tokens,
155 sections_removed: 0,
156 };
157 }
158 ProseResult {
159 compressed_tokens: count_tokens_for(&compressed, COUNTING_FAMILY) as u64,
160 compressed,
161 original_tokens,
162 sections_removed,
163 }
164}
165
166fn keep_section(
167 section: &ProseSection,
168 task_keywords: &HashSet<String>,
169 strategy: CompressionStrategy,
170) -> bool {
171 match section.section_type {
172 ProseSectionType::Header
173 | ProseSectionType::CodeBlock
174 | ProseSectionType::List
175 | ProseSectionType::Table
176 | ProseSectionType::Frontmatter => true,
177 ProseSectionType::Paragraph => match strategy {
178 CompressionStrategy::Light => true,
179 CompressionStrategy::Medium => section.importance >= 0.1,
180 CompressionStrategy::Aggressive => {
181 has_task_keyword(§ion.content, task_keywords)
182 || has_technical_keyword(§ion.content)
183 }
184 },
185 }
186}
187
188fn importance(section: &ProseSection, task_keywords: &HashSet<String>) -> f32 {
189 match section.section_type {
190 ProseSectionType::Header | ProseSectionType::CodeBlock => 1.0,
191 ProseSectionType::List => 0.8,
192 ProseSectionType::Table | ProseSectionType::Frontmatter => 0.9,
193 ProseSectionType::Paragraph => {
194 let words = words(§ion.content);
195 if words.is_empty() {
196 return 0.0;
197 }
198 let unique = words.iter().collect::<HashSet<_>>().len();
199 let mut score = unique as f32 / words.len() as f32;
200 if has_technical_keyword(§ion.content) {
201 score += 0.4;
202 }
203 if has_task_keyword(§ion.content, task_keywords) {
204 score += 0.5;
205 }
206 if FILLER_MARKERS
207 .iter()
208 .any(|marker| section.content.to_ascii_lowercase().contains(marker))
209 {
210 score *= 0.25;
211 }
212 score.min(1.0)
213 }
214 }
215}
216
217fn detect_sections(content: &str) -> Vec<ProseSection> {
218 let lines: Vec<&str> = content.lines().collect();
219 let mut sections = Vec::new();
220 let mut index = 0;
221
222 if lines.first().is_some_and(|line| line.trim() == "---") {
223 let start = index;
224 index += 1;
225 while index < lines.len() && lines[index].trim() != "---" {
226 index += 1;
227 }
228 if index < lines.len() {
229 index += 1;
230 sections.push(section(ProseSectionType::Frontmatter, &lines[start..index]));
231 } else {
232 index = start;
233 }
234 }
235
236 while index < lines.len() {
237 let line = lines[index];
238 if line.trim().is_empty() || is_horizontal_rule(line) {
239 index += 1;
240 } else if is_fence(line) {
241 let start = index;
242 let fence = line.trim().chars().next().unwrap_or('`');
243 index += 1;
244 while index < lines.len() {
245 let candidate = lines[index];
246 index += 1;
247 if candidate.trim().starts_with(fence)
248 && candidate
249 .trim()
250 .chars()
251 .take(3)
252 .all(|character| character == fence)
253 {
254 break;
255 }
256 }
257 sections.push(section(ProseSectionType::CodeBlock, &lines[start..index]));
258 } else if is_header(line) {
259 sections.push(section(ProseSectionType::Header, &lines[index..index + 1]));
260 index += 1;
261 } else if is_list(line) {
262 let start = index;
263 while index < lines.len() && (is_list(lines[index]) || lines[index].starts_with(" ")) {
264 index += 1;
265 }
266 sections.push(section(ProseSectionType::List, &lines[start..index]));
267 } else if is_table(line) {
268 let start = index;
269 while index < lines.len() && is_table(lines[index]) {
270 index += 1;
271 }
272 sections.push(section(ProseSectionType::Table, &lines[start..index]));
273 } else {
274 let start = index;
275 while index < lines.len()
276 && !lines[index].trim().is_empty()
277 && !is_horizontal_rule(lines[index])
278 && !is_fence(lines[index])
279 && !is_header(lines[index])
280 && !is_list(lines[index])
281 && !is_table(lines[index])
282 {
283 index += 1;
284 }
285 sections.push(section(ProseSectionType::Paragraph, &lines[start..index]));
286 }
287 }
288 sections
289}
290
291fn section(section_type: ProseSectionType, lines: &[&str]) -> ProseSection {
292 ProseSection {
293 section_type,
294 content: lines.join("\n"),
295 importance: 0.0,
296 }
297}
298
299fn clean_non_code(content: &str) -> String {
300 let mut output = String::with_capacity(content.len());
301 let mut rest = content;
302 while let Some(start) = rest.find("<!--") {
303 output.push_str(&rest[..start]);
304 let comment = &rest[start + 4..];
305 match comment.find("-->") {
306 Some(end) => rest = &comment[end + 3..],
307 None => {
308 rest = "";
309 break;
310 }
311 }
312 }
313 output.push_str(rest);
314 strip_long_image_alt_text(&output)
315 .lines()
316 .map(str::trim_end)
317 .collect::<Vec<_>>()
318 .join("\n")
319}
320
321fn strip_long_image_alt_text(content: &str) -> String {
322 let mut output = String::with_capacity(content.len());
323 let mut rest = content;
324 while let Some(start) = rest.find("![") {
325 output.push_str(&rest[..start]);
326 let image = &rest[start + 2..];
327 let Some(alt_end) = image.find("](") else {
328 output.push_str("![");
329 rest = image;
330 continue;
331 };
332 let alt = &image[..alt_end];
333 if alt.chars().count() > 120 {
334 output.push_str("![]");
335 } else {
336 output.push_str("![");
337 output.push_str(alt);
338 output.push(']');
339 }
340 rest = &image[alt_end + 1..];
341 }
342 output.push_str(rest);
343 output
344}
345
346fn keywords(text: &str) -> HashSet<String> {
347 words(text)
348 .into_iter()
349 .filter(|word| word.len() >= 3 && !STOP_WORDS.contains(&word.as_str()))
350 .collect()
351}
352
353fn words(text: &str) -> Vec<String> {
354 text.split(|character: char| !character.is_alphanumeric())
355 .filter(|word| !word.is_empty())
356 .map(|word| word.to_ascii_lowercase())
357 .collect()
358}
359
360fn has_task_keyword(content: &str, task_keywords: &HashSet<String>) -> bool {
361 !task_keywords.is_empty()
362 && words(content)
363 .iter()
364 .any(|word| task_keywords.contains(word))
365}
366
367fn has_technical_keyword(content: &str) -> bool {
368 words(content)
369 .iter()
370 .any(|word| TECHNICAL_KEYWORDS.contains(&word.as_str()))
371}
372
373fn is_fence(line: &str) -> bool {
374 let trimmed = line.trim();
375 trimmed.starts_with("```") || trimmed.starts_with("~~~")
376}
377
378fn is_header(line: &str) -> bool {
379 let trimmed = line.trim_start();
380 let hashes = trimmed
381 .chars()
382 .take_while(|character| *character == '#')
383 .count();
384 hashes > 0 && hashes <= 6 && trimmed.as_bytes().get(hashes) == Some(&b' ')
385}
386
387fn is_list(line: &str) -> bool {
388 let trimmed = line.trim_start();
389 matches!(trimmed.as_bytes(), [b'-' | b'+' | b'*', b' ', ..])
390 || trimmed.split_once('.').is_some_and(|(number, rest)| {
391 !number.is_empty()
392 && number.chars().all(|character| character.is_ascii_digit())
393 && rest.starts_with(' ')
394 })
395}
396
397fn is_table(line: &str) -> bool {
398 line.trim().matches('|').count() >= 2
399}
400
401fn is_horizontal_rule(line: &str) -> bool {
402 let trimmed = line.trim();
403 trimmed.len() >= 3
404 && trimmed
405 .chars()
406 .all(|character| matches!(character, '-' | '_' | '*'))
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn code_blocks_are_never_compressed() {
415 let source = "# Example\n\n```rust\nfn main() { println!(\"keep spacing\"); }\n```\n";
416 let result = compress_prose(source, Some("unrelated"));
417 assert!(
418 result
419 .compressed
420 .contains("fn main() { println!(\"keep spacing\"); }")
421 );
422 }
423
424 #[test]
425 fn headers_are_always_preserved() {
426 let source = "# Keep me\n\nThis is just filler. This is just filler. This is just filler.";
427 assert!(
428 compress_prose(source, Some("database"))
429 .compressed
430 .contains("# Keep me")
431 );
432 }
433
434 #[test]
435 #[ignore = "prose compressor edge case — revisit"]
436 fn filler_paragraphs_are_removed_aggressively() {
437 let source = "# Notes\n\nThis is just filler. This is just filler. This is just filler.\n\nThe database config controls the API connection.";
438 let result = ProseCompressor::new(None)
439 .with_strategy(CompressionStrategy::Aggressive)
440 .compress(source);
441 assert!(!result.compressed.contains("This is just filler"));
442 assert!(result.sections_removed > 0);
443 }
444
445 #[test]
446 #[ignore = "prose compressor edge case — revisit"]
447 fn empty_content_returns_empty() {
448 assert_eq!(compress_prose(" \n\t", None), ProseResult::default());
449 }
450
451 #[test]
452 fn a_lone_non_technical_paragraph_is_never_deleted() {
453 for text in [
458 "Bonjour, quelle est la capitale de la France ?",
459 "La capitale de la France est Paris.",
460 "Et combien d habitants environ ?",
461 ] {
462 let result = ProseCompressor::new(Some("question"))
463 .with_strategy(CompressionStrategy::Aggressive)
464 .compress(text);
465 assert!(
466 !result.compressed.trim().is_empty(),
467 "compressing {text:?} returned an empty result"
468 );
469 }
470 }
471
472 #[test]
473 fn task_relevant_paragraphs_survive_aggressive_compression() {
474 let source = "# Notes\n\nThe authentication middleware validates bearer tokens before every request.\n\nThis is unrelated prose.";
475 let result = compress_prose(source, Some("authentication bearer tokens"));
476 assert!(result.compressed.contains("validates bearer tokens"));
477 }
478
479 #[test]
480 #[ignore = "prose compressor edge case — revisit"]
481 fn comments_rules_and_long_alt_text_are_removed_outside_code() {
482 let source = "# Heading\n\n<!-- ignored -->\n\n---\n\n\n\n```md\n<!-- keep -->\n```";
483 let result = compress_prose(source, None);
484 assert!(!result.compressed.contains("ignored"));
485 assert!(result.compressed.contains(""));
486 assert!(result.compressed.contains("<!-- keep -->"));
487 }
488}