pub(crate) const NO_COMPRESSION_BANNER_MIN_TOKENS: usize = 400;
thread_local! {
static AUTO_REQUEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) struct AutoRequestGuard {
prev: bool,
}
impl AutoRequestGuard {
pub(crate) fn new() -> Self {
Self {
prev: AUTO_REQUEST.with(|a| a.replace(true)),
}
}
}
impl Drop for AutoRequestGuard {
fn drop(&mut self) {
AUTO_REQUEST.with(|a| a.set(self.prev));
}
}
pub(crate) fn no_compression_banner(requested_mode: &str, raw_tokens: usize) -> Option<String> {
if raw_tokens < NO_COMPRESSION_BANNER_MIN_TOKENS || AUTO_REQUEST.with(std::cell::Cell::get) {
return None;
}
let limit = lean_ctx::core::config::Config::load().turn_fresh_limit_effective();
let delivery = if limit > 0 && raw_tokens > limit {
format!(
"returning full content ({raw_tokens} tok), truncated to the {limit}-token turn \
budget — use lines= or raw=true for the rest"
)
} else {
format!("returning full content ({raw_tokens} tok)")
};
Some(format!(
"[lean-ctx] no compression applied (mode={requested_mode}): \
output was not smaller than the file — {delivery}"
))
}
#[cfg(test)]
mod tests {
#[test]
fn no_compression_banner_only_above_threshold() {
let _lock = lean_ctx::core::data_dir::test_env_lock();
assert!(super::no_compression_banner("signatures", 10).is_none());
let banner =
super::no_compression_banner("signatures", super::NO_COMPRESSION_BANNER_MIN_TOKENS)
.expect("a whole file handed back instead of a summary must be announced");
assert!(banner.contains("no compression applied"), "{banner}");
assert!(banner.contains("mode=signatures"), "{banner}");
}
#[test]
fn no_compression_banner_silent_for_auto_requests() {
let _lock = lean_ctx::core::data_dir::test_env_lock();
{
let _auto = super::AutoRequestGuard::new();
assert!(super::no_compression_banner("cognitive", 5_000).is_none());
{
let _nested = super::AutoRequestGuard::new();
}
assert!(
super::no_compression_banner("cognitive", 5_000).is_none(),
"a nested guard must restore, not clear, the outer state"
);
}
assert!(super::no_compression_banner("cognitive", 5_000).is_some());
}
#[test]
fn no_compression_banner_names_turn_budget_truncation() {
let _lock = lean_ctx::core::data_dir::test_env_lock();
lean_ctx::test_env::set_var("LEAN_CTX_TURN_FRESH_LIMIT", "4096");
let within = super::no_compression_banner("entropy", 4_000).expect("banner");
let over = super::no_compression_banner("entropy", 9_889).expect("banner");
lean_ctx::test_env::set_var("LEAN_CTX_TURN_FRESH_LIMIT", "0");
let unlimited = super::no_compression_banner("entropy", 9_889).expect("banner");
lean_ctx::test_env::remove_var("LEAN_CTX_TURN_FRESH_LIMIT");
assert!(
within.ends_with("returning full content (4000 tok)"),
"{within}"
);
assert!(!within.contains("truncated"), "{within}");
assert!(
over.contains("truncated to the 4096-token turn budget") && over.contains("raw=true"),
"{over}"
);
assert!(
!unlimited.contains("truncated"),
"0 = unlimited: {unlimited}"
);
}
}