lean_ctx/proxy/
compress.rs1use crate::core::tokens::count_tokens;
2use crate::core::web::distill;
3
4const RESEARCH_PROSE_CAP: usize = 24_000;
7
8pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
20 if content.trim().is_empty() || content.len() < 200 {
21 return content.to_string();
22 }
23
24 if is_cited_research_output(content) {
25 return content.to_string();
26 }
27
28 if extract_command_hint(content).is_none()
29 && looks_like_prose(content)
30 && let Some(out) = squeeze_research_prose(content)
31 {
32 return out;
33 }
34
35 let cmd = infer_command(content, tool_name);
36
37 let generic_command = cmd.is_empty() || cmd == "shell";
44 if generic_command
45 && (output_looks_like_test_run(content) || output_looks_like_build_failure(content))
46 {
47 return crate::shell::compress::engine::preserve_verbatim_pub(content);
48 }
49
50 crate::shell::compress::engine::compress_if_beneficial(&cmd, content)
51}
52
53fn output_looks_like_test_run(content: &str) -> bool {
57 const NEEDLES: &[&str] = &[
58 "test result:", "short test summary info", " passed in ", " failed in ", "=== RUN", "--- FAIL:", "--- PASS:", "Test Suites:", " examples, ", "FAILED", ];
69 NEEDLES.iter().any(|n| content.contains(n))
70}
71
72fn output_looks_like_build_failure(content: &str) -> bool {
76 const NEEDLES: &[&str] = &[
77 "error[", ": error:", "fatal error:", "undefined reference to", "panicked at", "could not compile", "Traceback (most recent call last)", "AssertionError", "make: ***", "Build FAILED",
87 "BUILD FAILED",
88 "Segmentation fault",
89 ];
90 NEEDLES.iter().any(|n| content.contains(n))
91}
92
93fn is_cited_research_output(content: &str) -> bool {
96 content.contains("· Retrieved: ") && content.contains("\nSource: ")
97}
98
99const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
101
102fn looks_like_prose(content: &str) -> bool {
105 let sample: String = content.chars().take(4000).collect();
106 let total = sample.chars().count();
107 if total < 600 {
108 return false;
109 }
110 let total_f = total as f32;
111 let alpha = sample.chars().filter(|c| c.is_alphabetic()).count() as f32;
112 let spaces = sample.chars().filter(|c| *c == ' ').count() as f32;
113 let symbols = sample.chars().filter(|c| CODE_SYMBOLS.contains(*c)).count() as f32;
114
115 if alpha / total_f < 0.6 || spaces / total_f < 0.12 || symbols / total_f > 0.06 {
116 return false;
117 }
118 if sample.matches(['.', '!', '?']).count() < 4 {
119 return false;
120 }
121
122 let non_empty: Vec<&str> = sample.lines().filter(|l| !l.trim().is_empty()).collect();
123 if non_empty.is_empty() {
124 return false;
125 }
126 let avg_len =
127 non_empty.iter().map(|l| l.chars().count()).sum::<usize>() as f32 / non_empty.len() as f32;
128 avg_len >= 40.0
129}
130
131fn squeeze_research_prose(content: &str) -> Option<String> {
134 let before = count_tokens(content);
135 let squeezed = distill::squeeze_prose(content, RESEARCH_PROSE_CAP);
136 if squeezed.trim().is_empty() {
137 return None;
138 }
139 let after = count_tokens(&squeezed);
140 if after + 2 >= before {
141 return None;
142 }
143 Some(crate::core::protocol::append_savings_with_info(
144 &squeezed,
145 before,
146 after,
147 Some("research"),
148 None,
149 ))
150}
151
152fn infer_command(content: &str, tool_name: Option<&str>) -> String {
153 if let Some(cmd) = extract_command_hint(content) {
154 return cmd;
155 }
156
157 if let Some(name) = tool_name {
158 let nl = name.to_lowercase();
159 if nl.contains("bash") || nl.contains("shell") || nl.contains("terminal") {
160 return "shell".to_string();
161 }
162 if nl.contains("search") || nl.contains("grep") || nl.contains("find") {
163 return "grep".to_string();
164 }
165 }
166
167 String::new()
168}
169
170fn extract_command_hint(content: &str) -> Option<String> {
171 for line in content.lines().take(3) {
172 let trimmed = line.trim();
173 if let Some(cmd) = trimmed.strip_prefix("$ ") {
174 return Some(cmd.to_string());
175 }
176 if let Some(cmd) = trimmed.strip_prefix("% ") {
177 return Some(cmd.to_string());
178 }
179 }
180 None
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn short_content_unchanged() {
189 let short = "hello world";
190 assert_eq!(compress_tool_result(short, None), short);
191 }
192
193 #[test]
194 fn empty_content_unchanged() {
195 assert_eq!(compress_tool_result("", None), "");
196 assert_eq!(compress_tool_result(" ", None), " ");
197 }
198
199 #[test]
200 fn command_hint_extraction() {
201 assert_eq!(
202 extract_command_hint("$ cargo build\nCompiling foo"),
203 Some("cargo build".to_string())
204 );
205 assert_eq!(extract_command_hint("no prefix here"), None);
206 }
207
208 #[test]
209 fn tool_name_inference() {
210 assert_eq!(infer_command("some text", Some("bash_execute")), "shell");
211 assert_eq!(infer_command("some text", Some("search_files")), "grep");
212 assert_eq!(infer_command("some text", Some("unknown_tool")), "");
213 }
214
215 #[test]
216 fn cited_research_output_is_preserved_verbatim() {
217 let cited = format!(
218 "Rust is a language.\n\n---\nSource: Rust — https://x.com/a\n\
219 Site: x.com · Retrieved: 2026-06-06T00:00:00Z\n{}",
220 "Extra body line that would otherwise be touched. ".repeat(20)
221 );
222 assert_eq!(compress_tool_result(&cited, Some("ctx_url_read")), cited);
223 }
224
225 #[test]
226 fn prose_is_squeezed_and_deduped() {
227 let para = "Rust is a multi-paradigm systems programming language that \
228 emphasizes performance, type safety, and fearless concurrency, \
229 achieving memory safety without a garbage collector at runtime.";
230 let input = format!("{}\n", [para; 8].join("\n\n"));
232 assert!(input.len() > 600);
233 let out = compress_tool_result(&input, Some("web_fetch"));
234 assert_eq!(out.matches("fearless concurrency").count(), 1);
235 assert!(out.contains("performance, type safety"));
236 }
237
238 #[test]
239 fn code_output_is_not_treated_as_prose() {
240 let code = "fn main() {\n let x = vec![1, 2, 3];\n \
241 for i in &x { println!(\"{}\", i); }\n}\n"
242 .repeat(20);
243 assert!(!looks_like_prose(&code));
244 }
245
246 #[test]
247 fn shell_log_is_not_treated_as_prose() {
248 let log = "$ cargo build\n Compiling foo v0.1.0\n Finished dev\n".repeat(20);
249 assert!(!looks_like_prose(&log));
250 }
251
252 #[test]
253 fn foreign_shell_build_failure_preserved_verbatim() {
254 let mut log = String::from("gcc -O2 -c src/versioncmp.c -o versioncmp.o\n");
258 log.push_str("src/versioncmp.c: In function 'version_cmp':\n");
259 log.push_str(
260 "src/versioncmp.c:142:17: error: invalid operands to binary < (have 'char *' and 'int')\n",
261 );
262 for i in 0..40 {
263 log.push_str(&format!(" note: expansion context line {i}\n"));
264 }
265 log.push_str("make: *** [Makefile:23: versioncmp.o] Error 1\n");
266
267 let out = compress_tool_result(&log, Some("shell"));
268 assert!(
269 out.contains("versioncmp.c:142:17: error:"),
270 "compiler error must survive the proxy"
271 );
272 assert!(
273 out.contains("make: ***"),
274 "make failure summary must survive"
275 );
276 }
277
278 #[test]
279 fn foreign_shell_test_failure_preserved_verbatim() {
280 let mut log = String::from("running 3 tests\n");
281 log.push_str("test version::tests::sorts_numeric ... FAILED\n");
282 for i in 0..40 {
283 log.push_str(&format!("note line {i} with some filler content here\n"));
284 }
285 log.push_str("test result: FAILED. 2 passed; 1 failed; 0 ignored\n");
286
287 let out = compress_tool_result(&log, Some("bash"));
288 assert!(
289 out.contains("test result: FAILED"),
290 "test summary must survive the proxy"
291 );
292 assert!(out.contains("sorts_numeric ... FAILED"));
293 }
294
295 #[test]
296 fn plain_shell_log_not_forced_verbatim() {
297 let log = "Listening on port 8080\nRequest received from 10.0.0.2\n".repeat(20);
298 assert!(!output_looks_like_test_run(&log));
299 assert!(!output_looks_like_build_failure(&log));
300 }
301}