lean_ctx/core/
compressor.rs1use similar::{ChangeTag, TextDiff};
2
3pub fn strip_ansi(s: &str) -> String {
4 if !s.contains('\x1b') {
5 return s.to_string();
6 }
7 let mut result = String::with_capacity(s.len());
8 let mut in_escape = false;
9 for c in s.chars() {
10 if c == '\x1b' {
11 in_escape = true;
12 continue;
13 }
14 if in_escape {
15 if c.is_ascii_alphabetic() {
16 in_escape = false;
17 }
18 continue;
19 }
20 result.push(c);
21 }
22 result
23}
24
25pub fn ansi_density(s: &str) -> f64 {
26 if s.is_empty() {
27 return 0.0;
28 }
29 let escape_bytes = s.chars().filter(|&c| c == '\x1b').count();
30 escape_bytes as f64 / s.len() as f64
31}
32
33pub fn aggressive_compress(content: &str, ext: Option<&str>) -> String {
34 let mut result: Vec<String> = Vec::new();
35 let is_python = matches!(ext, Some("py"));
36 let is_html = matches!(ext, Some("html" | "htm" | "xml" | "svg"));
37 let is_sql = matches!(ext, Some("sql"));
38 let is_shell = matches!(ext, Some("sh" | "bash" | "zsh" | "fish"));
39
40 let mut in_block_comment = false;
41
42 for line in content.lines() {
43 let trimmed = line.trim();
44
45 if trimmed.is_empty() {
46 continue;
47 }
48
49 if in_block_comment {
50 if trimmed.contains("*/") || (is_html && trimmed.contains("-->")) {
51 in_block_comment = false;
52 }
53 continue;
54 }
55
56 if trimmed.starts_with("/*") || (is_html && trimmed.starts_with("<!--")) {
57 if !(trimmed.contains("*/") || trimmed.contains("-->")) {
58 in_block_comment = true;
59 }
60 continue;
61 }
62
63 if trimmed.starts_with("//") && !trimmed.starts_with("///") {
64 continue;
65 }
66 if trimmed.starts_with('*') || trimmed.starts_with("*/") {
67 continue;
68 }
69 if is_python && trimmed.starts_with('#') {
70 continue;
71 }
72 if is_sql && trimmed.starts_with("--") {
73 continue;
74 }
75 if is_shell && trimmed.starts_with('#') && !trimmed.starts_with("#!") {
76 continue;
77 }
78 if !is_python && trimmed.starts_with('#') && trimmed.contains('[') {
79 continue;
80 }
81
82 if trimmed == "}" || trimmed == "};" || trimmed == ");" || trimmed == "});" {
83 if let Some(last) = result.last() {
84 let last_trimmed = last.trim();
85 if matches!(last_trimmed, "}" | "};" | ");" | "});") {
86 if let Some(last_mut) = result.last_mut() {
87 last_mut.push_str(trimmed);
88 }
89 continue;
90 }
91 }
92 result.push(trimmed.to_string());
93 continue;
94 }
95
96 let normalized = normalize_indentation(line);
97 result.push(normalized);
98 }
99
100 result.join("\n")
101}
102
103pub fn lightweight_cleanup(content: &str) -> String {
106 let mut result: Vec<String> = Vec::new();
107 let mut blank_count = 0u32;
108 let mut close_brace_count = 0u32;
109
110 for line in content.lines() {
111 let trimmed = line.trim();
112
113 if trimmed.is_empty() {
114 close_brace_count = 0;
115 blank_count += 1;
116 if blank_count <= 1 {
117 result.push(String::new());
118 }
119 continue;
120 }
121 blank_count = 0;
122
123 if matches!(trimmed, "}" | "};" | ");" | "});" | ")") {
124 close_brace_count += 1;
125 if close_brace_count <= 2 {
126 result.push(trimmed.to_string());
127 }
128 continue;
129 }
130 close_brace_count = 0;
131
132 result.push(line.to_string());
133 }
134
135 result.join("\n")
136}
137
138pub fn safeguard_ratio(original: &str, compressed: &str) -> String {
141 let orig_tokens = super::tokens::count_tokens(original);
142 let comp_tokens = super::tokens::count_tokens(compressed);
143
144 if orig_tokens == 0 {
145 return compressed.to_string();
146 }
147
148 let ratio = comp_tokens as f64 / orig_tokens as f64;
149 if ratio < 0.15 || comp_tokens > orig_tokens {
150 original.to_string()
151 } else {
152 compressed.to_string()
153 }
154}
155
156fn normalize_indentation(line: &str) -> String {
157 let content = line.trim_start();
158 let leading = line.len() - content.len();
159 let has_tabs = line.starts_with('\t');
160 let reduced = if has_tabs { leading } else { leading / 2 };
161 format!("{}{}", " ".repeat(reduced), content)
162}
163
164pub fn diff_content(old_content: &str, new_content: &str) -> String {
165 if old_content == new_content {
166 return "(no changes)".to_string();
167 }
168
169 let diff = TextDiff::from_lines(old_content, new_content);
170 let mut changes = Vec::new();
171 let mut additions = 0usize;
172 let mut deletions = 0usize;
173
174 for change in diff.iter_all_changes() {
175 let line_no = change.new_index().or(change.old_index()).map(|i| i + 1);
176 let text = change.value().trim_end_matches('\n');
177 match change.tag() {
178 ChangeTag::Insert => {
179 additions += 1;
180 if let Some(n) = line_no {
181 changes.push(format!("+{n}: {text}"));
182 }
183 }
184 ChangeTag::Delete => {
185 deletions += 1;
186 if let Some(n) = line_no {
187 changes.push(format!("-{n}: {text}"));
188 }
189 }
190 ChangeTag::Equal => {}
191 }
192 }
193
194 if changes.is_empty() {
195 return "(no changes)".to_string();
196 }
197
198 changes.push(format!("\ndiff +{additions}/-{deletions} lines"));
199 changes.join("\n")
200}
201
202pub fn verbatim_compact(text: &str) -> String {
203 let mut lines: Vec<String> = Vec::new();
204 let mut blank_count = 0u32;
205 let mut prev_line: Option<String> = None;
206 let mut repeat_count = 0u32;
207
208 for line in text.lines() {
209 let trimmed = line.trim();
210
211 if trimmed.is_empty() {
212 blank_count += 1;
213 if blank_count <= 1 {
214 flush_repeats(&mut lines, &mut prev_line, &mut repeat_count);
215 lines.push(String::new());
216 }
217 continue;
218 }
219 blank_count = 0;
220
221 if is_boilerplate_line(trimmed) {
222 continue;
223 }
224
225 let normalized = normalize_whitespace(trimmed);
226 let stripped = strip_timestamps_hashes(&normalized);
227
228 if let Some(ref prev) = prev_line {
229 if *prev == stripped {
230 repeat_count += 1;
231 continue;
232 }
233 }
234
235 flush_repeats(&mut lines, &mut prev_line, &mut repeat_count);
236 prev_line = Some(stripped.clone());
237 repeat_count = 1;
238 lines.push(stripped);
239 }
240
241 flush_repeats(&mut lines, &mut prev_line, &mut repeat_count);
242 lines.join("\n")
243}
244
245pub fn task_aware_compress(
246 content: &str,
247 ext: Option<&str>,
248 intent: &super::intent_engine::StructuredIntent,
249) -> String {
250 use super::intent_engine::{IntentScope, TaskType};
251
252 let budget_ratio = match intent.scope {
253 IntentScope::SingleFile => 0.7,
254 IntentScope::MultiFile => 0.5,
255 IntentScope::CrossModule => 0.35,
256 IntentScope::ProjectWide => 0.25,
257 };
258
259 match intent.task_type {
260 TaskType::FixBug | TaskType::Debug => {
261 let filtered = super::task_relevance::information_bottleneck_filter_typed(
262 content,
263 &intent.keywords,
264 budget_ratio,
265 Some(intent.task_type),
266 );
267 safeguard_ratio(content, &filtered)
268 }
269 TaskType::Refactor | TaskType::Review => {
270 let cleaned = lightweight_cleanup(content);
271 let filtered = super::task_relevance::information_bottleneck_filter_typed(
272 &cleaned,
273 &intent.keywords,
274 budget_ratio.max(0.5),
275 Some(intent.task_type),
276 );
277 safeguard_ratio(content, &filtered)
278 }
279 TaskType::Generate | TaskType::Test => {
280 let compressed = aggressive_compress(content, ext);
281 safeguard_ratio(content, &compressed)
282 }
283 TaskType::Explore => {
284 let cleaned = lightweight_cleanup(content);
285 safeguard_ratio(content, &cleaned)
286 }
287 TaskType::Config | TaskType::Deploy => {
288 let cleaned = lightweight_cleanup(content);
289 safeguard_ratio(content, &cleaned)
290 }
291 }
292}
293
294fn flush_repeats(lines: &mut [String], prev_line: &mut Option<String>, count: &mut u32) {
295 if *count > 1 {
296 if let Some(ref prev) = prev_line {
297 let last_idx = lines.len().saturating_sub(1);
298 if last_idx < lines.len() {
299 lines[last_idx] = format!("[{}x] {}", count, prev);
300 }
301 }
302 }
303 *count = 0;
304 *prev_line = None;
305}
306
307fn normalize_whitespace(line: &str) -> String {
308 let mut result = String::with_capacity(line.len());
309 let mut prev_space = false;
310 for ch in line.chars() {
311 if ch == ' ' || ch == '\t' {
312 if !prev_space {
313 result.push(' ');
314 prev_space = true;
315 }
316 } else {
317 result.push(ch);
318 prev_space = false;
319 }
320 }
321 result
322}
323
324fn strip_timestamps_hashes(line: &str) -> String {
325 use regex::Regex;
326 use std::sync::OnceLock;
327
328 static TS_RE: OnceLock<Regex> = OnceLock::new();
329 static HASH_RE: OnceLock<Regex> = OnceLock::new();
330
331 let ts_re = TS_RE.get_or_init(|| {
332 Regex::new(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?")
333 .unwrap()
334 });
335 let hash_re = HASH_RE.get_or_init(|| Regex::new(r"\b[0-9a-f]{32,64}\b").unwrap());
336
337 let s = ts_re.replace_all(line, "[TS]");
338 let s = hash_re.replace_all(&s, "[HASH]");
339 s.into_owned()
340}
341
342fn is_boilerplate_line(trimmed: &str) -> bool {
343 let lower = trimmed.to_lowercase();
344 if lower.starts_with("copyright")
345 || lower.starts_with("licensed under")
346 || lower.starts_with("license:")
347 || lower.starts_with("all rights reserved")
348 {
349 return true;
350 }
351 if lower.starts_with("generated by") || lower.starts_with("auto-generated") {
352 return true;
353 }
354 if trimmed.len() >= 4 {
355 let chars: Vec<char> = trimmed.chars().collect();
356 let first = chars[0];
357 if matches!(first, '=' | '-' | '*' | '─' | '━') {
358 let same = chars.iter().filter(|c| **c == first).count();
359 if same as f64 / chars.len() as f64 > 0.8 {
360 return true;
361 }
362 }
363 }
364 false
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[test]
372 fn test_diff_insertion() {
373 let old = "line1\nline2\nline3";
374 let new = "line1\nline2\nnew_line\nline3";
375 let result = diff_content(old, new);
376 assert!(result.contains("+"), "should show additions");
377 assert!(result.contains("new_line"));
378 }
379
380 #[test]
381 fn test_diff_deletion() {
382 let old = "line1\nline2\nline3";
383 let new = "line1\nline3";
384 let result = diff_content(old, new);
385 assert!(result.contains("-"), "should show deletions");
386 assert!(result.contains("line2"));
387 }
388
389 #[test]
390 fn test_diff_no_changes() {
391 let content = "same\ncontent";
392 assert_eq!(diff_content(content, content), "(no changes)");
393 }
394
395 #[test]
396 fn test_lightweight_cleanup_collapses_braces() {
397 let input = "fn main() {\n inner()\n}\n}\n}\n}\n}\nfn next() {}";
398 let result = lightweight_cleanup(input);
399 assert!(
400 result.matches('}').count() <= 3,
401 "should collapse consecutive closing braces"
402 );
403 assert!(result.contains("fn next()"));
404 }
405
406 #[test]
407 fn test_lightweight_cleanup_blank_lines() {
408 let input = "line1\n\n\n\n\nline2";
409 let result = lightweight_cleanup(input);
410 let blank_runs = result.split("line1").nth(1).unwrap();
411 let blanks = blank_runs.matches('\n').count();
412 assert!(blanks <= 2, "should collapse multiple blank lines");
413 }
414
415 #[test]
416 fn test_safeguard_ratio_prevents_over_compression() {
417 let original = "a ".repeat(100);
418 let too_compressed = "a";
419 let result = safeguard_ratio(&original, too_compressed);
420 assert_eq!(result, original, "should return original when ratio < 0.15");
421 }
422
423 #[test]
424 fn test_aggressive_strips_comments() {
425 let code = "fn main() {\n // a comment\n let x = 1;\n}";
426 let result = aggressive_compress(code, Some("rs"));
427 assert!(!result.contains("// a comment"));
428 assert!(result.contains("let x = 1"));
429 }
430
431 #[test]
432 fn test_aggressive_python_comments() {
433 let code = "def main():\n # comment\n x = 1";
434 let result = aggressive_compress(code, Some("py"));
435 assert!(!result.contains("# comment"));
436 assert!(result.contains("x = 1"));
437 }
438
439 #[test]
440 fn test_aggressive_preserves_doc_comments() {
441 let code = "/// Doc comment\nfn main() {}";
442 let result = aggressive_compress(code, Some("rs"));
443 assert!(result.contains("/// Doc comment"));
444 }
445
446 #[test]
447 fn test_aggressive_block_comment() {
448 let code = "/* start\n * middle\n */ end\nfn main() {}";
449 let result = aggressive_compress(code, Some("rs"));
450 assert!(!result.contains("start"));
451 assert!(!result.contains("middle"));
452 assert!(result.contains("fn main()"));
453 }
454
455 #[test]
456 fn test_strip_ansi_removes_escape_codes() {
457 let input = "\x1b[31mERROR\x1b[0m: something failed";
458 let result = strip_ansi(input);
459 assert_eq!(result, "ERROR: something failed");
460 assert!(!result.contains('\x1b'));
461 }
462
463 #[test]
464 fn test_strip_ansi_passthrough_clean_text() {
465 let input = "clean text without escapes";
466 let result = strip_ansi(input);
467 assert_eq!(result, input);
468 }
469
470 #[test]
471 fn test_ansi_density_zero_for_clean() {
472 assert_eq!(ansi_density("hello world"), 0.0);
473 }
474
475 #[test]
476 fn test_ansi_density_nonzero_for_colored() {
477 let input = "\x1b[31mred\x1b[0m";
478 assert!(ansi_density(input) > 0.0);
479 }
480}