Skip to main content

lean_ctx/proxy/
compress.rs

1use super::ccr;
2use super::prose_compress::compress_prose;
3use crate::core::tokens::{COUNTING_FAMILY, TokenizerFamily, count_tokens_for};
4use crate::core::web::distill;
5
6/// Byte-ish budget for the research-prose squeeze (~5k tokens on English prose).
7/// Only oversized prose is truncated; the squeeze's main job is dedup + blank-collapse,
8/// not cutting.
9const RESEARCH_PROSE_CAP: usize = 20_000;
10const RESEARCH_PROSE_CAP_ENV: &str = "LEAN_CTX_RESEARCH_PROSE_CAP";
11
12fn research_prose_cap() -> usize {
13    std::env::var(RESEARCH_PROSE_CAP_ENV)
14        .ok()
15        .and_then(|v| v.trim().parse::<usize>().ok())
16        .filter(|cap| *cap > 0)
17        .unwrap_or(RESEARCH_PROSE_CAP)
18}
19
20/// Proxy compression funnel: routes a tool result to the right compressor.
21///
22/// 1. Already-cited research output (from `ctx_url_read` / the web layer) is kept
23///    verbatim — it is distilled and citation-stamped, so the shell pipeline must
24///    not touch its footer or claim markers.
25/// 2. Prose results (web fetches, doc reads, research MCP bridges) are squeezed
26///    by the prose-aware research compressor instead of the log/code-tuned shell
27///    engine.
28/// 3. Everything else (shell/build/search output) flows through the unified
29///    `compress_if_beneficial` pipeline. A `$ ...` command hint is extracted so
30///    the pattern engine gets the same routing as the CLI and MCP paths.
31pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
32    compress_tool_result_for(content, tool_name, COUNTING_FAMILY)
33}
34
35/// Compresses a tool result under a task-aware policy.
36pub fn compress_tool_result_with_policy(
37    content: &str,
38    tool_name: Option<&str>,
39    policy: crate::proxy::adaptive_policy::CompressionPolicy,
40) -> String {
41    if !policy.compress_tool_output || policy.log_compression_level == 0 {
42        return content.to_owned();
43    }
44    if policy.code_preserve && looks_like_code(content) {
45        return content.to_owned();
46    }
47    compress_tool_result(content, tool_name)
48}
49
50/// Gateway variant of [`compress_tool_result_with_policy`].
51pub fn compress_tool_result_gateway_with_policy(
52    content: &str,
53    tool_name: Option<&str>,
54    family: TokenizerFamily,
55    policy: crate::proxy::adaptive_policy::CompressionPolicy,
56) -> String {
57    if !policy.compress_tool_output || policy.log_compression_level == 0 {
58        return content.to_owned();
59    }
60    if policy.code_preserve && looks_like_code(content) {
61        return content.to_owned();
62    }
63    compress_tool_result_gateway_for(content, tool_name, family)
64}
65
66fn looks_like_code(content: &str) -> bool {
67    content.lines().any(|line| {
68        let line = line.trim_start();
69        ["fn ", "struct ", "class ", "function ", "def ", "impl "]
70            .iter()
71            .any(|p| line.starts_with(p))
72            || line.contains('{')
73                && line.contains('}')
74                && (line.contains(';') || line.contains("=>"))
75    })
76}
77
78pub fn compress_tool_result_for(
79    content: &str,
80    tool_name: Option<&str>,
81    family: TokenizerFamily,
82) -> String {
83    let compressed = compress_inner(content, tool_name, family);
84    attach_ccr(content, compressed, CcrAudience::Local)
85}
86
87/// Shape the output of a host-native shell command whose exact command line is
88/// known (`ctx_shape`, fed by a host mod after the native tool ran). Unlike the
89/// wire funnel, the real command reaches the engine, so its command-gated
90/// policies (protected/verbatim commands, build/test guards, per-tool patterns)
91/// apply exactly as for `ctx_shell`. With a known `exit_code` the outcome-aware
92/// path runs (success compresses, failure keeps its diagnostics); without one
93/// the engine's unknown-outcome guard applies. Lossy results carry the same
94/// deterministic CCR recovery handle (#482, #498).
95pub fn shape_command_output(command: &str, output: &str, exit_code: Option<i32>) -> String {
96    if output.trim().is_empty() || output.len() < 200 {
97        return output.to_string();
98    }
99    let compressed = match exit_code {
100        Some(code) => crate::shell::compress::engine::compress_for_outcome(command, output, code),
101        None => crate::shell::compress::engine::compress_if_beneficial_pub(command, output),
102    };
103    attach_ccr(output, compressed, CcrAudience::Local)
104}
105
106/// [`compress_tool_result`] for the `/v1/compress` gateway contract (#702):
107/// identical compression, but a lossy result advertises its retrieval hash in
108/// LiteLLM's regex-locked `hash=<24hex>` form, so a gateway running the
109/// headroom-guardrail CCR loop (BerriAI/litellm#31681) can inject its retrieve
110/// tool and resolve the original via `GET /v1/retrieve/{hash}`.
111///
112/// Any ambient savings footer is stripped *before* the marker is attached:
113/// savings figures belong in the caller's structured `stats` (#498), while the
114/// marker is functional content that must survive as the last line.
115pub fn compress_tool_result_gateway(content: &str, tool_name: Option<&str>) -> String {
116    compress_tool_result_gateway_for(content, tool_name, COUNTING_FAMILY)
117}
118
119pub fn compress_tool_result_gateway_for(
120    content: &str,
121    tool_name: Option<&str>,
122    family: TokenizerFamily,
123) -> String {
124    let compressed = compress_inner(content, tool_name, family);
125    let clean = crate::core::protocol::strip_trailing_savings_footer(&compressed).to_string();
126    attach_ccr(content, clean, CcrAudience::Gateway)
127}
128
129/// Who reads a CCR stub: a local agent (path handle / in-band marker) or a
130/// remote gateway whose agentic loop scans for `hash=<24hex>` (#702).
131#[derive(Clone, Copy, PartialEq)]
132enum CcrAudience {
133    Local,
134    Gateway,
135}
136
137/// Make a live-compressed `tool_result` non-lossy (#482): when compression
138/// removed a meaningful amount, tee the verbatim original to the shared
139/// content-addressed store and append a deterministic recovery handle. The
140/// handle is a pure function of the content hash, so the rewritten result is
141/// byte-stable across turns and never invalidates the provider cache prefix
142/// (#448). Passthrough / verbatim results (no real shrink) keep their bytes.
143fn attach_ccr(original: &str, result: String, audience: CcrAudience) -> String {
144    use super::sticky_tools;
145    if original.len() < ccr::MIN_TEE_BYTES
146        || original.len().saturating_sub(result.len()) < ccr::MIN_TEE_BYTES
147    {
148        return result;
149    }
150    match ccr::persist(original) {
151        // Gateway (#702): the reader is a model behind a LiteLLM-style gateway.
152        // A local path is useless there; advertise the 24-hex retrieval hash in
153        // the exact shape the guardrail's marker regex captures. The hash is a
154        // pure function of the content, so the stub stays byte-stable (#498).
155        // The `[lean-ctx CCR:` prefix is deliberately NOT the savings-footer
156        // shape (`[lean-ctx: `): this line is functional content — a footer
157        // strip must never eat it.
158        Some(handle) if audience == CcrAudience::Gateway => {
159            sticky_tools::mark_ccr_active(0);
160            let hash = ccr::litellm_hash(original);
161            format!(
162                "{result}\n[lean-ctx CCR: full original elided to save tokens — call the \
163                 retrieve tool with hash={hash}, or read {handle} locally]"
164            )
165        }
166        Some(handle) => {
167            sticky_tools::mark_ccr_active(0);
168            match ccr::inband_locator(&handle) {
169                Some(marker) => format!(
170                    "{result}\n[lean-ctx: full original elided to save tokens — echo {marker} \
171                     on your next turn to get the verbatim original spliced back inline]"
172                ),
173                None => format!(
174                    "{result}\n[lean-ctx: full original at {handle} — read it directly (no MCP), or \
175                     ctx_expand(id=\"{handle}\", head=N|search=\"…\"|json_path=\"…\") for a slice]"
176                ),
177            }
178        }
179        None => result,
180    }
181}
182
183fn compress_inner(content: &str, tool_name: Option<&str>, family: TokenizerFamily) -> String {
184    if content.trim().is_empty() || content.len() < 200 {
185        return content.to_string();
186    }
187
188    // #479: lean-ctx's own MCP tools already applied their compression policy at
189    // the tool boundary — honouring `raw=true`/`bypass`, `<lc_safe>` spans and
190    // the configured aggressiveness. Their `raw` intent lives in the originating
191    // `tool_use` input, which is invisible here, so re-compressing on the wire
192    // would silently undo an explicit `raw=true` and double-compress everything
193    // else. Pass results from `ctx_*` tools through untouched.
194    if tool_name.is_some_and(is_lean_ctx_tool) {
195        return content.to_string();
196    }
197
198    // #709: honour explicit <lc_safe>…</lc_safe> spans on the proxy path too.
199    // Protected spans pass through verbatim; each unprotected segment flows back
200    // through the normal funnel (markers are stripped, so this never recurses).
201    if crate::core::protect::has_markers(content) {
202        return crate::core::protect::compress_preserving(content, |seg| {
203            compress_inner(seg, tool_name, family)
204        });
205    }
206
207    if is_cited_research_output(content) {
208        if looks_like_markdown(content) {
209            let prose = compress_prose(content, None);
210            if prose.compressed_tokens < prose.original_tokens {
211                return prose.compressed;
212            }
213        }
214        return content.to_string();
215    }
216
217    if extract_command_hint(content).is_none()
218        && looks_like_prose(content)
219        && let Some(out) = squeeze_research_prose(content, family)
220    {
221        return out;
222    }
223
224    let cmd = infer_command(content, tool_name);
225
226    // Proxy fidelity guard. A foreign shell tool gives us at most a generic
227    // command (`"shell"`) or none, so the engine's command-gated build/test
228    // verbatim guards never fire. When the *output* is unmistakably a build or
229    // test run, preserve it verbatim (bounded by safety-line-preserving
230    // truncation) so compiler errors, panics and test summaries reach the model
231    // intact — the exact signal a bug-fix task depends on.
232    let generic_command = cmd.is_empty() || cmd == "shell";
233    if generic_command
234        && (output_looks_like_test_run(content) || output_looks_like_build_failure(content))
235    {
236        return crate::shell::compress::engine::preserve_verbatim_pub_for(content, family);
237    }
238
239    crate::shell::compress::engine::compress_if_beneficial_for(&cmd, content, family)
240}
241
242/// Strong, ecosystem-spanning signals that an output is a *test run* (passing or
243/// failing). Conservative — matches the summary/result lines a bug-fix task must
244/// never lose. Only consulted on the proxy path when the real command is unknown.
245fn output_looks_like_test_run(content: &str) -> bool {
246    const NEEDLES: &[&str] = &[
247        "test result:",            // rust
248        "short test summary info", // pytest
249        " passed in ",             // pytest summary
250        " failed in ",             // pytest summary
251        "=== RUN",                 // go
252        "--- FAIL:",               // go
253        "--- PASS:",               // go
254        "Test Suites:",            // jest
255        " examples, ",             // rspec ("5 examples, 0 failures")
256        "FAILED",                  // generic test failure marker
257    ];
258    NEEDLES.iter().any(|n| content.contains(n))
259}
260
261/// Strong, specific signals of a build / compile / runtime failure across the
262/// major toolchains. Used only on the proxy path for generically-named tools so
263/// the failing diagnostics (paths, lines, messages) survive intact.
264fn output_looks_like_build_failure(content: &str) -> bool {
265    const NEEDLES: &[&str] = &[
266        "error[",                            // rustc (E0277 …)
267        ": error:",                          // gcc / clang "file.c:12:5: error:"
268        "fatal error:",                      // gcc / clang
269        "undefined reference to",            // linker
270        "panicked at",                       // rust runtime
271        "could not compile",                 // cargo
272        "Traceback (most recent call last)", // python
273        "AssertionError",                    // python / junit
274        "make: ***",                         // make
275        "Build FAILED",
276        "BUILD FAILED",
277        "Segmentation fault",
278    ];
279    NEEDLES.iter().any(|n| content.contains(n))
280}
281
282/// True when `content` is a lean-ctx web read: distilled body + citation footer
283/// (`Source: …\nSite: … · Retrieved: …`). Such output is re-compression-hostile.
284fn is_cited_research_output(content: &str) -> bool {
285    content.contains("· Retrieved: ") && content.contains("\nSource: ")
286}
287
288/// Code/shell symbols whose density cleanly separates source/logs from prose.
289const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
290
291/// Conservative prose detector: substantial, letter-dense, low code-symbol, with
292/// real sentences and long lines. Code, logs, tables and JSON all fail this.
293fn looks_like_prose(content: &str) -> bool {
294    let sample: String = content.chars().take(4000).collect();
295    let total = sample.chars().count();
296    if total < 600 {
297        return false;
298    }
299    let total_f = total as f32;
300    let alpha = sample.chars().filter(|c| c.is_alphabetic()).count() as f32;
301    let spaces = sample.chars().filter(|c| *c == ' ').count() as f32;
302    let symbols = sample.chars().filter(|c| CODE_SYMBOLS.contains(*c)).count() as f32;
303
304    if alpha / total_f < 0.6 || spaces / total_f < 0.12 || symbols / total_f > 0.06 {
305        return false;
306    }
307    if sample.matches(['.', '!', '?']).count() < 4 {
308        return false;
309    }
310
311    let non_empty: Vec<&str> = sample.lines().filter(|l| !l.trim().is_empty()).collect();
312    if non_empty.is_empty() {
313        return false;
314    }
315    let avg_len =
316        non_empty.iter().map(|l| l.chars().count()).sum::<usize>() as f32 / non_empty.len() as f32;
317    avg_len >= 40.0
318}
319
320fn looks_like_markdown(content: &str) -> bool {
321    content.lines().any(|line| {
322        let trimmed = line.trim_start();
323        trimmed.starts_with("# ")
324            || trimmed.starts_with("## ")
325            || trimmed.starts_with("```")
326            || trimmed.starts_with("~~~")
327            || matches!(trimmed.as_bytes(), [b'-' | b'*' | b'+', b' ', ..])
328            || trimmed.matches('|').count() >= 2
329    })
330}
331
332/// Apply the prose squeeze, returning a footer-stamped result only when it
333/// actually saves tokens; otherwise `None` so the normal pipeline can try.
334fn squeeze_research_prose(content: &str, family: TokenizerFamily) -> Option<String> {
335    let before = count_tokens_for(content, family);
336    let squeezed = squeeze_research_prose_body(content);
337    if squeezed.trim().is_empty() {
338        return None;
339    }
340    let after = count_tokens_for(&squeezed, family);
341    if after + 2 >= before {
342        return None;
343    }
344    Some(crate::core::protocol::append_savings_with_info(
345        &squeezed,
346        before,
347        after,
348        Some("research"),
349        None,
350    ))
351}
352
353/// Choose the prose-squeeze body. Only when the content would actually be
354/// TRUNCATED (over the cap) do we upgrade from FIFO prefix truncation to
355/// extractive centrality ranking — which keeps the most representative sentences
356/// instead of just the first ones — via the cache-safe, memoized wire squeeze
357/// ([`crate::proxy::prose_ranker`]), so the cold→warm engine transition never
358/// changes a frozen-region rewrite (#448/#498). Below the cap the squeeze is a
359/// lossless dedup pass, so the cheaper truncating squeeze is used.
360fn squeeze_research_prose_body(content: &str) -> String {
361    let cap = research_prose_cap();
362    if content.len() > cap {
363        return super::prose_ranker::squeeze(content, cap);
364    }
365    distill::squeeze_prose(content, cap)
366}
367
368/// True when `name` refers to one of lean-ctx's own `ctx_*` MCP tools, whose
369/// results are already compressed at the tool boundary and must not be touched
370/// again by the proxy (#479).
371///
372/// Clients namespace MCP tools differently, so a plain `starts_with("ctx_")`
373/// misses the real-world callers: Claude Code (the reporter's setup) sends
374/// `mcp__lean-ctx__ctx_shell`, others use `lean-ctx:ctx_read`. Strip the client
375/// prefix down to the bare tool segment before matching.
376fn is_lean_ctx_tool(name: &str) -> bool {
377    let bare = name
378        .rsplit("__")
379        .next()
380        .unwrap_or(name)
381        .rsplit([':', '/', '.'])
382        .next()
383        .unwrap_or(name);
384    bare.starts_with("ctx_") || name.starts_with("ctx_")
385}
386
387fn infer_command(content: &str, tool_name: Option<&str>) -> String {
388    if let Some(cmd) = extract_command_hint(content) {
389        return cmd;
390    }
391
392    if let Some(name) = tool_name {
393        let nl = name.to_lowercase();
394        if nl.contains("bash") || nl.contains("shell") || nl.contains("terminal") {
395            return "shell".to_string();
396        }
397        if nl.contains("search") || nl.contains("grep") || nl.contains("find") {
398            return "grep".to_string();
399        }
400    }
401
402    String::new()
403}
404
405fn extract_command_hint(content: &str) -> Option<String> {
406    for line in content.lines().take(3) {
407        let trimmed = line.trim();
408        if let Some(cmd) = trimmed.strip_prefix("$ ") {
409            return Some(cmd.to_string());
410        }
411        if let Some(cmd) = trimmed.strip_prefix("% ") {
412            return Some(cmd.to_string());
413        }
414    }
415    None
416}
417
418#[cfg(test)]
419mod tests {
420    use super::ccr;
421    use super::{
422        RESEARCH_PROSE_CAP, RESEARCH_PROSE_CAP_ENV, compress_tool_result,
423        compress_tool_result_gateway, extract_command_hint, infer_command, looks_like_prose,
424        output_looks_like_build_failure, output_looks_like_test_run, research_prose_cap,
425    };
426    use serial_test::serial;
427
428    /// #980/#985: search tool results must compress without corrupting source.
429    #[test]
430    fn search_tool_result_is_compressed_without_corrupting_source() {
431        let raw = (0..60)
432            .map(|i| {
433                format!(
434                    "src/h.go:{i}:func handler{i}(ctx context.Context) (api.Result, error) \
435                     {{ return doWork(ctx) }}"
436                )
437            })
438            .collect::<Vec<_>>()
439            .join("\n");
440        let out = compress_tool_result(&raw, Some("search_files"));
441
442        assert!(
443            out.len() < raw.len(),
444            "search results must still compress ({} -> {})",
445            raw.len(),
446            out.len()
447        );
448        for keyword in ["context.Context", "(api.Result, error)", "return"] {
449            assert!(
450                out.contains(keyword),
451                "the terse dictionary rewrote `{keyword}` out of a search result:\n{out}"
452            );
453        }
454    }
455
456    #[test]
457    fn short_content_unchanged() {
458        let short = "hello world";
459        assert_eq!(compress_tool_result(short, None), short);
460    }
461
462    #[test]
463    fn empty_content_unchanged() {
464        assert_eq!(compress_tool_result("", None), "");
465        assert_eq!(compress_tool_result("   ", None), "   ");
466    }
467
468    #[test]
469    fn command_hint_extraction() {
470        assert_eq!(
471            extract_command_hint("$ cargo build\nCompiling foo"),
472            Some("cargo build".to_string())
473        );
474        assert_eq!(extract_command_hint("no prefix here"), None);
475    }
476
477    #[test]
478    fn tool_name_inference() {
479        assert_eq!(infer_command("some text", Some("bash_execute")), "shell");
480        assert_eq!(infer_command("some text", Some("search_files")), "grep");
481        assert_eq!(infer_command("some text", Some("unknown_tool")), "");
482    }
483
484    #[test]
485    fn lean_ctx_tool_results_pass_through_verbatim() {
486        // A ctx_shell result the tool already produced (raw=true, or its own
487        // compression). The proxy must NOT re-compress / re-truncate it — that
488        // was the #479 defect where `raw=true` was silently undone on the wire.
489        let raw = (1..=120)
490            .map(|i| format!("Line {i:04}: the quick brown fox jumps over the lazy dog"))
491            .collect::<Vec<_>>()
492            .join("\n");
493        assert!(raw.len() > 200);
494        // Bare names AND the namespaced forms real MCP clients emit (Claude Code
495        // `mcp__lean-ctx__ctx_shell`, colon-style `lean-ctx:ctx_read`).
496        for tool in [
497            "ctx_shell",
498            "ctx_read",
499            "ctx_search",
500            "ctx_grep",
501            "mcp__lean-ctx__ctx_shell",
502            "lean-ctx:ctx_read",
503        ] {
504            assert_eq!(
505                compress_tool_result(&raw, Some(tool)),
506                raw,
507                "{tool} output must pass through the proxy verbatim"
508            );
509        }
510        // A foreign tool with identical output is still compressed: the proxy
511        // keeps adding value for non-lean-ctx tools.
512        assert_ne!(
513            compress_tool_result(&raw, Some("bash")),
514            raw,
515            "foreign-tool output should still be compressed by the proxy"
516        );
517    }
518
519    #[test]
520    fn cited_research_output_is_preserved_verbatim() {
521        let cited = format!(
522            "Rust is a language.\n\n---\nSource: Rust — https://x.com/a\n\
523             Site: x.com · Retrieved: 2026-06-06T00:00:00Z\n{}",
524            "Extra body line that would otherwise be touched. ".repeat(20)
525        );
526        assert_eq!(compress_tool_result(&cited, Some("ctx_url_read")), cited);
527    }
528
529    #[test]
530    fn prose_is_squeezed_and_deduped() {
531        let para = "Rust is a multi-paradigm systems programming language that \
532                    emphasizes performance, type safety, and fearless concurrency, \
533                    achieving memory safety without a garbage collector at runtime.";
534        // Repeated paragraph (well over the 600-char prose floor) → dedup keeps one.
535        let input = format!("{}\n", [para; 8].join("\n\n"));
536        assert!(input.len() > 600);
537        let out = compress_tool_result(&input, Some("web_fetch"));
538        assert_eq!(out.matches("fearless concurrency").count(), 1);
539        assert!(out.contains("performance, type safety"));
540    }
541
542    #[test]
543    #[serial]
544    fn research_prose_cap_env_overrides_default() {
545        let _lock = crate::core::data_dir::test_env_lock();
546        crate::test_env::set_var(RESEARCH_PROSE_CAP_ENV, "1234");
547        assert_eq!(research_prose_cap(), 1234);
548        crate::test_env::remove_var(RESEARCH_PROSE_CAP_ENV);
549    }
550
551    #[test]
552    #[serial]
553    fn research_prose_cap_env_invalid_falls_back() {
554        let _lock = crate::core::data_dir::test_env_lock();
555        for value in ["", "not_a_number", "0"] {
556            crate::test_env::set_var(RESEARCH_PROSE_CAP_ENV, value);
557            assert_eq!(research_prose_cap(), RESEARCH_PROSE_CAP);
558        }
559        crate::test_env::remove_var(RESEARCH_PROSE_CAP_ENV);
560    }
561
562    #[test]
563    fn code_output_is_not_treated_as_prose() {
564        let code = "fn main() {\n    let x = vec![1, 2, 3];\n    \
565                    for i in &x { println!(\"{}\", i); }\n}\n"
566            .repeat(20);
567        assert!(!looks_like_prose(&code));
568    }
569
570    #[test]
571    fn shell_log_is_not_treated_as_prose() {
572        let log = "$ cargo build\n   Compiling foo v0.1.0\n    Finished dev\n".repeat(20);
573        assert!(!looks_like_prose(&log));
574    }
575
576    #[test]
577    fn foreign_shell_build_failure_preserved_verbatim() {
578        // A forge/pi-style shell tool: the name says "shell" and the output has
579        // no `$ cmd` hint, so the engine's command-gated guards cannot fire. The
580        // compiler error must still reach the model intact for a bug-fix task.
581        let mut log = String::from("gcc -O2 -c src/versioncmp.c -o versioncmp.o\n");
582        log.push_str("src/versioncmp.c: In function 'version_cmp':\n");
583        log.push_str(
584            "src/versioncmp.c:142:17: error: invalid operands to binary < (have 'char *' and 'int')\n",
585        );
586        for i in 0..40 {
587            log.push_str(&format!("  note: expansion context line {i}\n"));
588        }
589        log.push_str("make: *** [Makefile:23: versioncmp.o] Error 1\n");
590
591        let out = compress_tool_result(&log, Some("shell"));
592        assert!(
593            out.contains("versioncmp.c:142:17: error:"),
594            "compiler error must survive the proxy"
595        );
596        assert!(
597            out.contains("make: ***"),
598            "make failure summary must survive"
599        );
600    }
601
602    #[test]
603    fn foreign_shell_test_failure_preserved_verbatim() {
604        let mut log = String::from("running 3 tests\n");
605        log.push_str("test version::tests::sorts_numeric ... FAILED\n");
606        for i in 0..40 {
607            log.push_str(&format!("note line {i} with some filler content here\n"));
608        }
609        log.push_str("test result: FAILED. 2 passed; 1 failed; 0 ignored\n");
610
611        let out = compress_tool_result(&log, Some("bash"));
612        assert!(
613            out.contains("test result: FAILED"),
614            "test summary must survive the proxy"
615        );
616        assert!(out.contains("sorts_numeric ... FAILED"));
617    }
618
619    #[test]
620    fn plain_shell_log_not_forced_verbatim() {
621        let log = "Listening on port 8080\nRequest received from 10.0.0.2\n".repeat(20);
622        assert!(!output_looks_like_test_run(&log));
623        assert!(!output_looks_like_build_failure(&log));
624    }
625
626    fn big_compressible_log() -> String {
627        (1..=400)
628            .map(|i| format!("[info] processed item {i:04} ok"))
629            .collect::<Vec<_>>()
630            .join("\n")
631    }
632
633    #[test]
634    fn live_compression_is_recoverable_via_ccr_handle() {
635        let _lock = crate::core::data_dir::test_env_lock();
636        let log = big_compressible_log();
637        let out = compress_tool_result(&log, Some("bash"));
638        assert!(
639            out.len() < log.len(),
640            "a large foreign log must be compressed"
641        );
642
643        // The compressed result carries the content-addressed handle, and the
644        // handle points at the *verbatim* original — live compression is now
645        // non-lossy (#482), recoverable with a plain native file read.
646        let handle = ccr::persist(&log).expect("same content -> same handle");
647        assert!(out.contains(&handle), "CCR handle must be embedded: {out}");
648        let recovered = std::fs::read_to_string(&handle).expect("tee file readable");
649        assert!(
650            recovered.contains("processed item 0007 ok")
651                && recovered.contains("processed item 0400 ok"),
652            "verbatim original must be fully recoverable"
653        );
654    }
655
656    #[test]
657    fn live_compression_output_is_byte_stable_across_turns() {
658        let _lock = crate::core::data_dir::test_env_lock();
659        let log = big_compressible_log();
660        let a = compress_tool_result(&log, Some("bash"));
661        let b = compress_tool_result(&log, Some("bash"));
662        assert_eq!(
663            a, b,
664            "the CCR handle is content-addressed, so the rewritten result must be \
665             byte-identical across turns (provider cache prefix stays valid, #448)"
666        );
667    }
668
669    /// Contract test for #702, pinned to LiteLLM's marker regex: the headroom
670    /// guardrail scans compressed text with `hash=([a-f0-9]{24})`
671    /// (BerriAI/litellm#31681). If our gateway stub ever drifts from that
672    /// shape, the CCR agentic loop silently stops firing — this test fails
673    /// first.
674    #[test]
675    fn gateway_stub_matches_litellm_marker_regex_and_retrieves() {
676        let _lock = crate::core::data_dir::test_env_lock();
677        let log = big_compressible_log();
678        let out = compress_tool_result_gateway(&log, Some("bash"));
679        assert!(out.len() < log.len(), "gateway funnel must still compress");
680
681        // Exactly the pattern LiteLLM compiles (`_HASH_PATTERN`).
682        let litellm_regex = regex::Regex::new(r"hash=([a-f0-9]{24})").unwrap();
683        let captured = litellm_regex
684            .captures(&out)
685            .unwrap_or_else(|| panic!("gateway stub must carry a hash= marker: {out}"))
686            .get(1)
687            .unwrap()
688            .as_str();
689        assert_eq!(captured, ccr::litellm_hash(&log));
690
691        // The captured hash resolves through the /v1/retrieve/{hash} resolver
692        // to the verbatim original — the full guardrail round-trip.
693        let recovered = ccr::retrieve_litellm(captured).expect("captured hash must resolve");
694        assert!(
695            recovered.contains("processed item 0007 ok")
696                && recovered.contains("processed item 0400 ok"),
697            "retrieve must return the verbatim original"
698        );
699
700        // Byte-stable across calls (#498): the marker is content-addressed.
701        assert_eq!(out, compress_tool_result_gateway(&log, Some("bash")));
702
703        // The functional CCR line must survive the savings-footer strip that
704        // /v1/compress applies to every payload.
705        assert_eq!(
706            crate::core::protocol::strip_trailing_savings_footer(&out),
707            out
708        );
709    }
710
711    #[test]
712    fn gateway_stub_absent_for_passthrough_and_ctx_output() {
713        let _lock = crate::core::data_dir::test_env_lock();
714        // Below the compress floor: no marker.
715        assert!(!compress_tool_result_gateway("short output", Some("bash")).contains("hash="));
716        // lean-ctx tool output passes through verbatim — a gateway must never
717        // see a retrieval marker for content that was not rewritten.
718        let raw = (1..=120)
719            .map(|i| format!("Line {i:04}: lorem ipsum dolor sit amet consectetur"))
720            .collect::<Vec<_>>()
721            .join("\n");
722        let out = compress_tool_result_gateway(&raw, Some("ctx_shell"));
723        assert_eq!(out, raw);
724    }
725
726    #[test]
727    fn small_or_passthrough_output_gets_no_ccr_handle() {
728        let _lock = crate::core::data_dir::test_env_lock();
729        // Below the 200-char compress floor: passes through, no handle.
730        let tiny = "ok\n".repeat(10);
731        assert!(!compress_tool_result(&tiny, Some("bash")).contains("full original at"));
732        // lean-ctx tool output passes through verbatim (no handle either).
733        let raw = (1..=120)
734            .map(|i| format!("Line {i:04}: lorem ipsum dolor sit amet consectetur"))
735            .collect::<Vec<_>>()
736            .join("\n");
737        let out = compress_tool_result(&raw, Some("ctx_shell"));
738        assert_eq!(out, raw, "lean-ctx tool result must stay verbatim (no CCR)");
739    }
740}