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
6const 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
20pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
32 compress_tool_result_for(content, tool_name, COUNTING_FAMILY)
33}
34
35pub 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
50pub 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
87pub 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
106pub 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#[derive(Clone, Copy, PartialEq)]
132enum CcrAudience {
133 Local,
134 Gateway,
135}
136
137fn 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 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 if tool_name.is_some_and(is_lean_ctx_tool) {
195 return content.to_string();
196 }
197
198 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 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
242fn output_looks_like_test_run(content: &str) -> bool {
246 const NEEDLES: &[&str] = &[
247 "test result:", "short test summary info", " passed in ", " failed in ", "=== RUN", "--- FAIL:", "--- PASS:", "Test Suites:", " examples, ", "FAILED", ];
258 NEEDLES.iter().any(|n| content.contains(n))
259}
260
261fn output_looks_like_build_failure(content: &str) -> bool {
265 const NEEDLES: &[&str] = &[
266 "error[", ": error:", "fatal error:", "undefined reference to", "panicked at", "could not compile", "Traceback (most recent call last)", "AssertionError", "make: ***", "Build FAILED",
276 "BUILD FAILED",
277 "Segmentation fault",
278 ];
279 NEEDLES.iter().any(|n| content.contains(n))
280}
281
282fn is_cited_research_output(content: &str) -> bool {
285 content.contains("· Retrieved: ") && content.contains("\nSource: ")
286}
287
288const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
290
291fn 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
332fn 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
353fn 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
368fn 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 #[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 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 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 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 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 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 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 #[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 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 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 assert_eq!(out, compress_tool_result_gateway(&log, Some("bash")));
702
703 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 assert!(!compress_tool_result_gateway("short output", Some("bash")).contains("hash="));
716 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 let tiny = "ok\n".repeat(10);
731 assert!(!compress_tool_result(&tiny, Some("bash")).contains("full original at"));
732 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}