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() && 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    // Proxy fidelity guard. A foreign shell tool gives us at most a generic
37    // command (`"shell"`) or none, so the engine's command-gated build/test
38    // verbatim guards never fire. When the *output* is unmistakably a build or
39    // test run, preserve it verbatim (bounded by safety-line-preserving
40    // truncation) so compiler errors, panics and test summaries reach the model
41    // intact — the exact signal a bug-fix task depends on.
42    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
52/// Strong, ecosystem-spanning signals that an output is a *test run* (passing or
53/// failing). Conservative — matches the summary/result lines a bug-fix task must
54/// never lose. Only consulted on the proxy path when the real command is unknown.
55fn output_looks_like_test_run(content: &str) -> bool {
56    const NEEDLES: &[&str] = &[
57        "test result:",            // rust
58        "short test summary info", // pytest
59        " passed in ",             // pytest summary
60        " failed in ",             // pytest summary
61        "=== RUN",                 // go
62        "--- FAIL:",               // go
63        "--- PASS:",               // go
64        "Test Suites:",            // jest
65        " examples, ",             // rspec ("5 examples, 0 failures")
66        "FAILED",                  // generic test failure marker
67    ];
68    NEEDLES.iter().any(|n| content.contains(n))
69}
70
71/// Strong, specific signals of a build / compile / runtime failure across the
72/// major toolchains. Used only on the proxy path for generically-named tools so
73/// the failing diagnostics (paths, lines, messages) survive intact.
74fn output_looks_like_build_failure(content: &str) -> bool {
75    const NEEDLES: &[&str] = &[
76        "error[",                            // rustc (E0277 …)
77        ": error:",                          // gcc / clang "file.c:12:5: error:"
78        "fatal error:",                      // gcc / clang
79        "undefined reference to",            // linker
80        "panicked at",                       // rust runtime
81        "could not compile",                 // cargo
82        "Traceback (most recent call last)", // python
83        "AssertionError",                    // python / junit
84        "make: ***",                         // make
85        "Build FAILED",
86        "BUILD FAILED",
87        "Segmentation fault",
88    ];
89    NEEDLES.iter().any(|n| content.contains(n))
90}
91
92/// True when `content` is a lean-ctx web read: distilled body + citation footer
93/// (`Source: …\nSite: … · Retrieved: …`). Such output is re-compression-hostile.
94fn is_cited_research_output(content: &str) -> bool {
95    content.contains("· Retrieved: ") && content.contains("\nSource: ")
96}
97
98/// Code/shell symbols whose density cleanly separates source/logs from prose.
99const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
100
101/// Conservative prose detector: substantial, letter-dense, low code-symbol, with
102/// real sentences and long lines. Code, logs, tables and JSON all fail this.
103fn 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
130/// Apply the prose squeeze, returning a footer-stamped result only when it
131/// actually saves tokens; otherwise `None` so the normal pipeline can try.
132fn 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        // Repeated paragraph (well over the 600-char prose floor) → dedup keeps one.
230        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        // A forge/pi-style shell tool: the name says "shell" and the output has
254        // no `$ cmd` hint, so the engine's command-gated guards cannot fire. The
255        // compiler error must still reach the model intact for a bug-fix task.
256        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}