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