1use super::ccr;
2use crate::core::tokens::count_tokens;
3use crate::core::web::distill;
4
5const RESEARCH_PROSE_CAP: usize = 20_000;
9const RESEARCH_PROSE_CAP_ENV: &str = "LEAN_CTX_RESEARCH_PROSE_CAP";
10
11fn research_prose_cap() -> usize {
12 std::env::var(RESEARCH_PROSE_CAP_ENV)
13 .ok()
14 .and_then(|v| v.trim().parse::<usize>().ok())
15 .filter(|cap| *cap > 0)
16 .unwrap_or(RESEARCH_PROSE_CAP)
17}
18
19pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
31 let compressed = compress_inner(content, tool_name);
32 attach_ccr(content, compressed, CcrAudience::Local)
33}
34
35pub fn compress_tool_result_gateway(content: &str, tool_name: Option<&str>) -> String {
45 let compressed = compress_inner(content, tool_name);
46 let clean = crate::core::protocol::strip_trailing_savings_footer(&compressed).to_string();
47 attach_ccr(content, clean, CcrAudience::Gateway)
48}
49
50#[derive(Clone, Copy, PartialEq)]
53enum CcrAudience {
54 Local,
55 Gateway,
56}
57
58fn attach_ccr(original: &str, result: String, audience: CcrAudience) -> String {
65 use super::sticky_tools;
66 if original.len() < ccr::MIN_TEE_BYTES
67 || original.len().saturating_sub(result.len()) < ccr::MIN_TEE_BYTES
68 {
69 return result;
70 }
71 match ccr::persist(original) {
72 Some(handle) if audience == CcrAudience::Gateway => {
80 sticky_tools::mark_ccr_active(0);
81 let hash = ccr::litellm_hash(original);
82 format!(
83 "{result}\n[lean-ctx CCR: full original elided to save tokens — call the \
84 retrieve tool with hash={hash}, or read {handle} locally]"
85 )
86 }
87 Some(handle) => {
88 sticky_tools::mark_ccr_active(0);
89 match ccr::inband_locator(&handle) {
90 Some(marker) => format!(
91 "{result}\n[lean-ctx: full original elided to save tokens — echo {marker} \
92 on your next turn to get the verbatim original spliced back inline]"
93 ),
94 None => format!(
95 "{result}\n[lean-ctx: full original at {handle} — read it directly (no MCP), or \
96 ctx_expand(id=\"{handle}\", head=N|search=\"…\"|json_path=\"…\") for a slice]"
97 ),
98 }
99 }
100 None => result,
101 }
102}
103
104fn compress_inner(content: &str, tool_name: Option<&str>) -> String {
105 if content.trim().is_empty() || content.len() < 200 {
106 return content.to_string();
107 }
108
109 if tool_name.is_some_and(is_lean_ctx_tool) {
116 return content.to_string();
117 }
118
119 if crate::core::protect::has_markers(content) {
123 return crate::core::protect::compress_preserving(content, |seg| {
124 compress_inner(seg, tool_name)
125 });
126 }
127
128 if is_cited_research_output(content) {
129 return content.to_string();
130 }
131
132 if extract_command_hint(content).is_none()
133 && looks_like_prose(content)
134 && let Some(out) = squeeze_research_prose(content)
135 {
136 return out;
137 }
138
139 let cmd = infer_command(content, tool_name);
140
141 let generic_command = cmd.is_empty() || cmd == "shell";
148 if generic_command
149 && (output_looks_like_test_run(content) || output_looks_like_build_failure(content))
150 {
151 return crate::shell::compress::engine::preserve_verbatim_pub(content);
152 }
153
154 crate::shell::compress::engine::compress_if_beneficial(&cmd, content)
155}
156
157fn output_looks_like_test_run(content: &str) -> bool {
161 const NEEDLES: &[&str] = &[
162 "test result:", "short test summary info", " passed in ", " failed in ", "=== RUN", "--- FAIL:", "--- PASS:", "Test Suites:", " examples, ", "FAILED", ];
173 NEEDLES.iter().any(|n| content.contains(n))
174}
175
176fn output_looks_like_build_failure(content: &str) -> bool {
180 const NEEDLES: &[&str] = &[
181 "error[", ": error:", "fatal error:", "undefined reference to", "panicked at", "could not compile", "Traceback (most recent call last)", "AssertionError", "make: ***", "Build FAILED",
191 "BUILD FAILED",
192 "Segmentation fault",
193 ];
194 NEEDLES.iter().any(|n| content.contains(n))
195}
196
197fn is_cited_research_output(content: &str) -> bool {
200 content.contains("· Retrieved: ") && content.contains("\nSource: ")
201}
202
203const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
205
206fn looks_like_prose(content: &str) -> bool {
209 let sample: String = content.chars().take(4000).collect();
210 let total = sample.chars().count();
211 if total < 600 {
212 return false;
213 }
214 let total_f = total as f32;
215 let alpha = sample.chars().filter(|c| c.is_alphabetic()).count() as f32;
216 let spaces = sample.chars().filter(|c| *c == ' ').count() as f32;
217 let symbols = sample.chars().filter(|c| CODE_SYMBOLS.contains(*c)).count() as f32;
218
219 if alpha / total_f < 0.6 || spaces / total_f < 0.12 || symbols / total_f > 0.06 {
220 return false;
221 }
222 if sample.matches(['.', '!', '?']).count() < 4 {
223 return false;
224 }
225
226 let non_empty: Vec<&str> = sample.lines().filter(|l| !l.trim().is_empty()).collect();
227 if non_empty.is_empty() {
228 return false;
229 }
230 let avg_len =
231 non_empty.iter().map(|l| l.chars().count()).sum::<usize>() as f32 / non_empty.len() as f32;
232 avg_len >= 40.0
233}
234
235fn squeeze_research_prose(content: &str) -> Option<String> {
238 let before = count_tokens(content);
239 let squeezed = squeeze_research_prose_body(content);
240 if squeezed.trim().is_empty() {
241 return None;
242 }
243 let after = count_tokens(&squeezed);
244 if after + 2 >= before {
245 return None;
246 }
247 Some(crate::core::protocol::append_savings_with_info(
248 &squeezed,
249 before,
250 after,
251 Some("research"),
252 None,
253 ))
254}
255
256fn squeeze_research_prose_body(content: &str) -> String {
264 let cap = research_prose_cap();
265 if content.len() > cap {
266 return super::prose_ranker::squeeze(content, cap);
267 }
268 distill::squeeze_prose(content, cap)
269}
270
271fn is_lean_ctx_tool(name: &str) -> bool {
280 let bare = name
281 .rsplit("__")
282 .next()
283 .unwrap_or(name)
284 .rsplit([':', '/', '.'])
285 .next()
286 .unwrap_or(name);
287 bare.starts_with("ctx_") || name.starts_with("ctx_")
288}
289
290fn infer_command(content: &str, tool_name: Option<&str>) -> String {
291 if let Some(cmd) = extract_command_hint(content) {
292 return cmd;
293 }
294
295 if let Some(name) = tool_name {
296 let nl = name.to_lowercase();
297 if nl.contains("bash") || nl.contains("shell") || nl.contains("terminal") {
298 return "shell".to_string();
299 }
300 if nl.contains("search") || nl.contains("grep") || nl.contains("find") {
301 return "grep".to_string();
302 }
303 }
304
305 String::new()
306}
307
308fn extract_command_hint(content: &str) -> Option<String> {
309 for line in content.lines().take(3) {
310 let trimmed = line.trim();
311 if let Some(cmd) = trimmed.strip_prefix("$ ") {
312 return Some(cmd.to_string());
313 }
314 if let Some(cmd) = trimmed.strip_prefix("% ") {
315 return Some(cmd.to_string());
316 }
317 }
318 None
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324 use serial_test::serial;
325
326 #[test]
327 fn short_content_unchanged() {
328 let short = "hello world";
329 assert_eq!(compress_tool_result(short, None), short);
330 }
331
332 #[test]
333 fn empty_content_unchanged() {
334 assert_eq!(compress_tool_result("", None), "");
335 assert_eq!(compress_tool_result(" ", None), " ");
336 }
337
338 #[test]
339 fn command_hint_extraction() {
340 assert_eq!(
341 extract_command_hint("$ cargo build\nCompiling foo"),
342 Some("cargo build".to_string())
343 );
344 assert_eq!(extract_command_hint("no prefix here"), None);
345 }
346
347 #[test]
348 fn tool_name_inference() {
349 assert_eq!(infer_command("some text", Some("bash_execute")), "shell");
350 assert_eq!(infer_command("some text", Some("search_files")), "grep");
351 assert_eq!(infer_command("some text", Some("unknown_tool")), "");
352 }
353
354 #[test]
355 fn lean_ctx_tool_results_pass_through_verbatim() {
356 let raw = (1..=120)
360 .map(|i| format!("Line {i:04}: the quick brown fox jumps over the lazy dog"))
361 .collect::<Vec<_>>()
362 .join("\n");
363 assert!(raw.len() > 200);
364 for tool in [
367 "ctx_shell",
368 "ctx_read",
369 "ctx_search",
370 "ctx_grep",
371 "mcp__lean-ctx__ctx_shell",
372 "lean-ctx:ctx_read",
373 ] {
374 assert_eq!(
375 compress_tool_result(&raw, Some(tool)),
376 raw,
377 "{tool} output must pass through the proxy verbatim"
378 );
379 }
380 assert_ne!(
383 compress_tool_result(&raw, Some("bash")),
384 raw,
385 "foreign-tool output should still be compressed by the proxy"
386 );
387 }
388
389 #[test]
390 fn cited_research_output_is_preserved_verbatim() {
391 let cited = format!(
392 "Rust is a language.\n\n---\nSource: Rust — https://x.com/a\n\
393 Site: x.com · Retrieved: 2026-06-06T00:00:00Z\n{}",
394 "Extra body line that would otherwise be touched. ".repeat(20)
395 );
396 assert_eq!(compress_tool_result(&cited, Some("ctx_url_read")), cited);
397 }
398
399 #[test]
400 fn prose_is_squeezed_and_deduped() {
401 let para = "Rust is a multi-paradigm systems programming language that \
402 emphasizes performance, type safety, and fearless concurrency, \
403 achieving memory safety without a garbage collector at runtime.";
404 let input = format!("{}\n", [para; 8].join("\n\n"));
406 assert!(input.len() > 600);
407 let out = compress_tool_result(&input, Some("web_fetch"));
408 assert_eq!(out.matches("fearless concurrency").count(), 1);
409 assert!(out.contains("performance, type safety"));
410 }
411
412 #[test]
413 #[serial]
414 fn research_prose_cap_env_overrides_default() {
415 let _lock = crate::core::data_dir::test_env_lock();
416 crate::test_env::set_var(RESEARCH_PROSE_CAP_ENV, "1234");
417 assert_eq!(research_prose_cap(), 1234);
418 crate::test_env::remove_var(RESEARCH_PROSE_CAP_ENV);
419 }
420
421 #[test]
422 #[serial]
423 fn research_prose_cap_env_invalid_falls_back() {
424 let _lock = crate::core::data_dir::test_env_lock();
425 for value in ["", "not_a_number", "0"] {
426 crate::test_env::set_var(RESEARCH_PROSE_CAP_ENV, value);
427 assert_eq!(research_prose_cap(), RESEARCH_PROSE_CAP);
428 }
429 crate::test_env::remove_var(RESEARCH_PROSE_CAP_ENV);
430 }
431
432 #[test]
433 fn code_output_is_not_treated_as_prose() {
434 let code = "fn main() {\n let x = vec![1, 2, 3];\n \
435 for i in &x { println!(\"{}\", i); }\n}\n"
436 .repeat(20);
437 assert!(!looks_like_prose(&code));
438 }
439
440 #[test]
441 fn shell_log_is_not_treated_as_prose() {
442 let log = "$ cargo build\n Compiling foo v0.1.0\n Finished dev\n".repeat(20);
443 assert!(!looks_like_prose(&log));
444 }
445
446 #[test]
447 fn foreign_shell_build_failure_preserved_verbatim() {
448 let mut log = String::from("gcc -O2 -c src/versioncmp.c -o versioncmp.o\n");
452 log.push_str("src/versioncmp.c: In function 'version_cmp':\n");
453 log.push_str(
454 "src/versioncmp.c:142:17: error: invalid operands to binary < (have 'char *' and 'int')\n",
455 );
456 for i in 0..40 {
457 log.push_str(&format!(" note: expansion context line {i}\n"));
458 }
459 log.push_str("make: *** [Makefile:23: versioncmp.o] Error 1\n");
460
461 let out = compress_tool_result(&log, Some("shell"));
462 assert!(
463 out.contains("versioncmp.c:142:17: error:"),
464 "compiler error must survive the proxy"
465 );
466 assert!(
467 out.contains("make: ***"),
468 "make failure summary must survive"
469 );
470 }
471
472 #[test]
473 fn foreign_shell_test_failure_preserved_verbatim() {
474 let mut log = String::from("running 3 tests\n");
475 log.push_str("test version::tests::sorts_numeric ... FAILED\n");
476 for i in 0..40 {
477 log.push_str(&format!("note line {i} with some filler content here\n"));
478 }
479 log.push_str("test result: FAILED. 2 passed; 1 failed; 0 ignored\n");
480
481 let out = compress_tool_result(&log, Some("bash"));
482 assert!(
483 out.contains("test result: FAILED"),
484 "test summary must survive the proxy"
485 );
486 assert!(out.contains("sorts_numeric ... FAILED"));
487 }
488
489 #[test]
490 fn plain_shell_log_not_forced_verbatim() {
491 let log = "Listening on port 8080\nRequest received from 10.0.0.2\n".repeat(20);
492 assert!(!output_looks_like_test_run(&log));
493 assert!(!output_looks_like_build_failure(&log));
494 }
495
496 fn big_compressible_log() -> String {
497 (1..=400)
498 .map(|i| format!("[info] processed item {i:04} ok"))
499 .collect::<Vec<_>>()
500 .join("\n")
501 }
502
503 #[test]
504 fn live_compression_is_recoverable_via_ccr_handle() {
505 let _lock = crate::core::data_dir::test_env_lock();
506 let log = big_compressible_log();
507 let out = compress_tool_result(&log, Some("bash"));
508 assert!(
509 out.len() < log.len(),
510 "a large foreign log must be compressed"
511 );
512
513 let handle = ccr::persist(&log).expect("same content -> same handle");
517 assert!(out.contains(&handle), "CCR handle must be embedded: {out}");
518 let recovered = std::fs::read_to_string(&handle).expect("tee file readable");
519 assert!(
520 recovered.contains("processed item 0007 ok")
521 && recovered.contains("processed item 0400 ok"),
522 "verbatim original must be fully recoverable"
523 );
524 }
525
526 #[test]
527 fn live_compression_output_is_byte_stable_across_turns() {
528 let _lock = crate::core::data_dir::test_env_lock();
529 let log = big_compressible_log();
530 let a = compress_tool_result(&log, Some("bash"));
531 let b = compress_tool_result(&log, Some("bash"));
532 assert_eq!(
533 a, b,
534 "the CCR handle is content-addressed, so the rewritten result must be \
535 byte-identical across turns (provider cache prefix stays valid, #448)"
536 );
537 }
538
539 #[test]
545 fn gateway_stub_matches_litellm_marker_regex_and_retrieves() {
546 let _lock = crate::core::data_dir::test_env_lock();
547 let log = big_compressible_log();
548 let out = compress_tool_result_gateway(&log, Some("bash"));
549 assert!(out.len() < log.len(), "gateway funnel must still compress");
550
551 let litellm_regex = regex::Regex::new(r"hash=([a-f0-9]{24})").unwrap();
553 let captured = litellm_regex
554 .captures(&out)
555 .unwrap_or_else(|| panic!("gateway stub must carry a hash= marker: {out}"))
556 .get(1)
557 .unwrap()
558 .as_str();
559 assert_eq!(captured, ccr::litellm_hash(&log));
560
561 let recovered = ccr::retrieve_litellm(captured).expect("captured hash must resolve");
564 assert!(
565 recovered.contains("processed item 0007 ok")
566 && recovered.contains("processed item 0400 ok"),
567 "retrieve must return the verbatim original"
568 );
569
570 assert_eq!(out, compress_tool_result_gateway(&log, Some("bash")));
572
573 assert_eq!(
576 crate::core::protocol::strip_trailing_savings_footer(&out),
577 out
578 );
579 }
580
581 #[test]
582 fn gateway_stub_absent_for_passthrough_and_ctx_output() {
583 let _lock = crate::core::data_dir::test_env_lock();
584 assert!(!compress_tool_result_gateway("short output", Some("bash")).contains("hash="));
586 let raw = (1..=120)
589 .map(|i| format!("Line {i:04}: lorem ipsum dolor sit amet consectetur"))
590 .collect::<Vec<_>>()
591 .join("\n");
592 let out = compress_tool_result_gateway(&raw, Some("ctx_shell"));
593 assert_eq!(out, raw);
594 }
595
596 #[test]
597 fn small_or_passthrough_output_gets_no_ccr_handle() {
598 let _lock = crate::core::data_dir::test_env_lock();
599 let tiny = "ok\n".repeat(10);
601 assert!(!compress_tool_result(&tiny, Some("bash")).contains("full original at"));
602 let raw = (1..=120)
604 .map(|i| format!("Line {i:04}: lorem ipsum dolor sit amet consectetur"))
605 .collect::<Vec<_>>()
606 .join("\n");
607 let out = compress_tool_result(&raw, Some("ctx_shell"));
608 assert_eq!(out, raw, "lean-ctx tool result must stay verbatim (no CCR)");
609 }
610}