lean_ctx/proxy/
prose_patterns.rs1use std::collections::HashSet;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct PatternCompression {
12 pub compressed: String,
13 pub units_removed: usize,
14}
15
16pub fn compress_prose_patterns(content: &str) -> PatternCompression {
18 if content.trim().is_empty() {
19 return PatternCompression {
20 compressed: content.to_owned(),
21 units_removed: 0,
22 };
23 }
24
25 let mut compressed = String::with_capacity(content.len());
26 let mut prose = Vec::new();
27 let mut in_fence = false;
28 let mut units_removed = 0usize;
29
30 for line in content.split_inclusive('\n') {
31 if is_fence(line) {
32 let result = compress_prose_segment(&prose.join(""));
33 compressed.push_str(&result.compressed);
34 units_removed += result.units_removed;
35 prose.clear();
36 compressed.push_str(line);
37 in_fence = !in_fence;
38 } else if in_fence {
39 compressed.push_str(line);
40 } else {
41 prose.push(line);
42 }
43 }
44
45 let result = compress_prose_segment(&prose.join(""));
46 compressed.push_str(&result.compressed);
47 units_removed += result.units_removed;
48
49 PatternCompression {
50 compressed,
51 units_removed,
52 }
53}
54
55pub fn remove_seen_instruction_lines(content: &mut String, seen: &mut HashSet<String>) -> usize {
61 let mut retained = String::with_capacity(content.len());
62 let mut units_removed = 0;
63
64 for line in content.split_inclusive('\n') {
65 if is_instruction_line(line) {
66 let key = canonical(line);
67 if !key.is_empty() && !seen.insert(key) {
68 units_removed += 1;
69 continue;
70 }
71 }
72 retained.push_str(line);
73 }
74
75 if units_removed > 0 {
76 *content = retained;
77 }
78 units_removed
79}
80
81fn compress_prose_segment(segment: &str) -> PatternCompression {
82 if segment.trim().is_empty() {
83 return PatternCompression {
84 compressed: segment.to_owned(),
85 units_removed: 0,
86 };
87 }
88
89 let mut seen_headings = HashSet::new();
90 let mut seen_paragraphs = HashSet::new();
91 let mut seen_instruction_lines = HashSet::new();
92 let mut retained = Vec::new();
93 let mut paragraph = Vec::new();
94 let mut units_removed = 0usize;
95
96 let flush_paragraph = |paragraph: &mut Vec<&str>,
97 retained: &mut Vec<String>,
98 seen_paragraphs: &mut HashSet<String>,
99 units_removed: &mut usize| {
100 if paragraph.is_empty() {
101 return;
102 }
103 let original = paragraph.join("");
104 paragraph.clear();
105 let result = compress_paragraph(&original);
106 let key = canonical(&result.compressed);
107 if !key.is_empty() && !seen_paragraphs.insert(key) {
108 *units_removed += 1;
109 return;
110 }
111 *units_removed += result.units_removed;
112 retained.push(result.compressed);
113 };
114
115 for line in segment.split_inclusive('\n') {
116 if line.trim().is_empty() {
117 flush_paragraph(
118 &mut paragraph,
119 &mut retained,
120 &mut seen_paragraphs,
121 &mut units_removed,
122 );
123 retained.push(line.to_owned());
124 continue;
125 }
126
127 if is_heading(line) {
128 flush_paragraph(
129 &mut paragraph,
130 &mut retained,
131 &mut seen_paragraphs,
132 &mut units_removed,
133 );
134 let key = canonical(line.trim_start_matches('#').trim());
135 if key.is_empty() || seen_headings.insert(key) {
136 retained.push(line.to_owned());
137 } else {
138 units_removed += 1;
139 }
140 continue;
141 }
142
143 if is_instruction_line(line) {
144 flush_paragraph(
145 &mut paragraph,
146 &mut retained,
147 &mut seen_paragraphs,
148 &mut units_removed,
149 );
150 let key = canonical(line);
151 if key.is_empty() || seen_instruction_lines.insert(key) {
152 retained.push(line.to_owned());
153 } else {
154 units_removed += 1;
155 }
156 continue;
157 }
158
159 paragraph.push(line);
160 }
161
162 flush_paragraph(
163 &mut paragraph,
164 &mut retained,
165 &mut seen_paragraphs,
166 &mut units_removed,
167 );
168
169 PatternCompression {
170 compressed: retained.concat(),
171 units_removed,
172 }
173}
174
175fn compress_paragraph(paragraph: &str) -> PatternCompression {
176 let sentences = sentences(paragraph);
177 if sentences.len() < 2 {
178 return PatternCompression {
179 compressed: paragraph.to_owned(),
180 units_removed: 0,
181 };
182 }
183
184 let error = paragraph_has_error(paragraph);
185 let mut retained = Vec::new();
186 let mut previous = Vec::<HashSet<String>>::new();
187 let mut units_removed = 0usize;
188
189 for (index, sentence) in sentences.iter().enumerate() {
190 let words = word_set(sentence);
191 let duplicate = words.len() >= 6
192 && previous
193 .iter()
194 .any(|candidate| overlap_ratio(&words, candidate) >= 0.82);
195 let verbose_error_detail = error
196 && index > 0
197 && index + 1 < sentences.len()
198 && words.len() >= 12
199 && !contains_remediation(sentence);
200
201 if duplicate || verbose_error_detail {
202 units_removed += 1;
203 continue;
204 }
205
206 previous.push(words);
207 retained.push(*sentence);
208 }
209
210 if retained.is_empty() {
211 return PatternCompression {
212 compressed: sentences[0].to_owned(),
213 units_removed: units_removed.saturating_sub(1),
214 };
215 }
216
217 PatternCompression {
218 compressed: retained.join(" "),
219 units_removed,
220 }
221}
222
223fn sentences(paragraph: &str) -> Vec<&str> {
224 let mut result = Vec::new();
225 let mut start = 0;
226 for (index, character) in paragraph.char_indices() {
227 if matches!(character, '.' | '!' | '?') {
228 let end = index + character.len_utf8();
229 if let Some(sentence) = paragraph.get(start..end) {
230 if !sentence.trim().is_empty() {
231 result.push(sentence.trim());
232 }
233 }
234 start = end;
235 }
236 }
237 if let Some(tail) = paragraph.get(start..) {
238 if !tail.trim().is_empty() {
239 result.push(tail.trim());
240 }
241 }
242 result
243}
244
245fn canonical(text: &str) -> String {
246 text.chars()
247 .flat_map(char::to_lowercase)
248 .map(|character| {
249 if character.is_alphanumeric() {
250 character
251 } else {
252 ' '
253 }
254 })
255 .collect::<String>()
256 .split_whitespace()
257 .collect::<Vec<_>>()
258 .join(" ")
259}
260
261fn word_set(text: &str) -> HashSet<String> {
262 canonical(text)
263 .split_whitespace()
264 .filter(|word| word.len() > 2)
265 .map(ToOwned::to_owned)
266 .collect()
267}
268
269fn overlap_ratio(left: &HashSet<String>, right: &HashSet<String>) -> f32 {
270 let union = left.union(right).count();
271 if union == 0 {
272 return 0.0;
273 }
274 left.intersection(right).count() as f32 / union as f32
275}
276
277fn is_fence(line: &str) -> bool {
278 let trimmed = line.trim_start();
279 trimmed.starts_with("```") || trimmed.starts_with("~~~")
280}
281
282fn is_heading(line: &str) -> bool {
283 let trimmed = line.trim_start();
284 trimmed.starts_with('#') && trimmed.trim_start_matches('#').starts_with(' ')
285}
286
287fn is_instruction_line(line: &str) -> bool {
288 let words = canonical(line);
289 let instruction_prefixes = [
290 "please ",
291 "always ",
292 "never ",
293 "must ",
294 "do not ",
295 "remember to ",
296 "make sure ",
297 "follow ",
298 ];
299 instruction_prefixes
300 .iter()
301 .any(|prefix| words.starts_with(prefix))
302}
303
304fn paragraph_has_error(paragraph: &str) -> bool {
305 sentence_has_error(paragraph)
306}
307
308fn sentence_has_error(sentence: &str) -> bool {
309 let lower = canonical(sentence);
310 [
311 "error",
312 "exception",
313 "failed",
314 "failure",
315 "panic",
316 "traceback",
317 ]
318 .iter()
319 .any(|marker| lower.split_whitespace().any(|word| word == *marker))
320}
321
322fn contains_remediation(sentence: &str) -> bool {
323 let lower = canonical(sentence);
324 [
325 "fix ", "retry ", "resolve ", "run ", "use ", "change ", "set ", "remove ",
326 ]
327 .iter()
328 .any(|prefix| lower.starts_with(prefix))
329}
330
331#[cfg(test)]
332mod tests {
333 use super::compress_prose_patterns;
334
335 #[test]
336 fn removes_repeated_explanations_but_keeps_the_first_one() {
337 let source = "The cache stores normalized keys before lookup. The cache stores normalized keys before lookup. Keep the key format stable.";
338 let result = compress_prose_patterns(source);
339 assert_eq!(
340 result.compressed,
341 "The cache stores normalized keys before lookup. Keep the key format stable."
342 );
343 assert_eq!(result.units_removed, 1);
344 }
345
346 #[test]
347 fn collapses_repeated_markdown_headings_and_instruction_lines() {
348 let source = "# Rules\nAlways run tests before merging.\n# Rules\nAlways run tests before merging.\n";
349 let result = compress_prose_patterns(source);
350 assert_eq!(
351 result.compressed,
352 "# Rules\nAlways run tests before merging.\n"
353 );
354 assert_eq!(result.units_removed, 2);
355 }
356
357 #[test]
358 fn keeps_the_error_and_remediation_while_dropping_verbose_detail() {
359 let source = "Error: cache write failed. The worker attempted every available fallback and recorded extensive retry diagnostics for each failed filesystem operation. Retry after freeing disk space.";
360 let result = compress_prose_patterns(source);
361 assert_eq!(
362 result.compressed,
363 "Error: cache write failed. Retry after freeing disk space."
364 );
365 assert_eq!(result.units_removed, 1);
366 }
367
368 #[test]
369 fn code_fences_are_byte_preserved() {
370 let source = "Repeat this explanation. Repeat this explanation.\n```rust\nlet value = \"Repeat this explanation.\";\n```\n";
371 let result = compress_prose_patterns(source);
372 assert!(
373 result
374 .compressed
375 .contains("let value = \"Repeat this explanation.\";")
376 );
377 }
378
379 #[test]
380 fn removes_boilerplate_instruction_lines_seen_in_earlier_turns() {
381 let mut seen = std::collections::HashSet::new();
382 let mut first = "Always run tests before merging.\nKeep the failure output.\n".to_owned();
383 let mut second = "Always run tests before merging.\nKeep the failure output.\n".to_owned();
384 assert_eq!(
385 super::remove_seen_instruction_lines(&mut first, &mut seen),
386 0
387 );
388 assert_eq!(
389 super::remove_seen_instruction_lines(&mut second, &mut seen),
390 1
391 );
392 assert_eq!(second, "Keep the failure output.\n");
393 }
394}