Skip to main content

lean_ctx/proxy/
compress.rs

1use crate::core::tokens::count_tokens;
2use crate::core::web::distill;
3
4/// Char budget for the research-prose squeeze (~6k tokens). Only oversized prose
5/// is truncated; the squeeze's main job is dedup + blank-collapse, not cutting.
6const RESEARCH_PROSE_CAP: usize = 24_000;
7
8/// Proxy compression funnel: routes a tool result to the right compressor.
9///
10/// 1. Already-cited research output (from `ctx_url_read` / the web layer) is kept
11///    verbatim — it is distilled and citation-stamped, so the shell pipeline must
12///    not touch its footer or claim markers.
13/// 2. Prose results (web fetches, doc reads, research MCP bridges) are squeezed
14///    by the prose-aware research compressor instead of the log/code-tuned shell
15///    engine.
16/// 3. Everything else (shell/build/search output) flows through the unified
17///    `compress_if_beneficial` pipeline. A `$ ...` command hint is extracted so
18///    the pattern engine gets the same routing as the CLI and MCP paths.
19pub 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    // Proxy fidelity guard. A foreign shell tool gives us at most a generic
38    // command (`"shell"`) or none, so the engine's command-gated build/test
39    // verbatim guards never fire. When the *output* is unmistakably a build or
40    // test run, preserve it verbatim (bounded by safety-line-preserving
41    // truncation) so compiler errors, panics and test summaries reach the model
42    // intact — the exact signal a bug-fix task depends on.
43    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
53/// Strong, ecosystem-spanning signals that an output is a *test run* (passing or
54/// failing). Conservative — matches the summary/result lines a bug-fix task must
55/// never lose. Only consulted on the proxy path when the real command is unknown.
56fn output_looks_like_test_run(content: &str) -> bool {
57    const NEEDLES: &[&str] = &[
58        "test result:",            // rust
59        "short test summary info", // pytest
60        " passed in ",             // pytest summary
61        " failed in ",             // pytest summary
62        "=== RUN",                 // go
63        "--- FAIL:",               // go
64        "--- PASS:",               // go
65        "Test Suites:",            // jest
66        " examples, ",             // rspec ("5 examples, 0 failures")
67        "FAILED",                  // generic test failure marker
68    ];
69    NEEDLES.iter().any(|n| content.contains(n))
70}
71
72/// Strong, specific signals of a build / compile / runtime failure across the
73/// major toolchains. Used only on the proxy path for generically-named tools so
74/// the failing diagnostics (paths, lines, messages) survive intact.
75fn output_looks_like_build_failure(content: &str) -> bool {
76    const NEEDLES: &[&str] = &[
77        "error[",                            // rustc (E0277 …)
78        ": error:",                          // gcc / clang "file.c:12:5: error:"
79        "fatal error:",                      // gcc / clang
80        "undefined reference to",            // linker
81        "panicked at",                       // rust runtime
82        "could not compile",                 // cargo
83        "Traceback (most recent call last)", // python
84        "AssertionError",                    // python / junit
85        "make: ***",                         // make
86        "Build FAILED",
87        "BUILD FAILED",
88        "Segmentation fault",
89    ];
90    NEEDLES.iter().any(|n| content.contains(n))
91}
92
93/// True when `content` is a lean-ctx web read: distilled body + citation footer
94/// (`Source: …\nSite: … · Retrieved: …`). Such output is re-compression-hostile.
95fn is_cited_research_output(content: &str) -> bool {
96    content.contains("· Retrieved: ") && content.contains("\nSource: ")
97}
98
99/// Code/shell symbols whose density cleanly separates source/logs from prose.
100const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
101
102/// Conservative prose detector: substantial, letter-dense, low code-symbol, with
103/// real sentences and long lines. Code, logs, tables and JSON all fail this.
104fn 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
131/// Apply the prose squeeze, returning a footer-stamped result only when it
132/// actually saves tokens; otherwise `None` so the normal pipeline can try.
133fn 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        // Repeated paragraph (well over the 600-char prose floor) → dedup keeps one.
231        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        // A forge/pi-style shell tool: the name says "shell" and the output has
255        // no `$ cmd` hint, so the engine's command-gated guards cannot fire. The
256        // compiler error must still reach the model intact for a bug-fix task.
257        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}