Skip to main content

lean_ctx_proxy/
compress.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::cell::RefCell;
3use std::collections::BTreeMap;
4
5use super::ccr;
6use super::prose_compress::compress_prose;
7use lean_ctx::core::archive::{RecoveryId, RecoveryRefusal, delivered};
8use lean_ctx::core::tokens::{COUNTING_FAMILY, TokenizerFamily, count_tokens_for};
9use lean_ctx::core::web::distill;
10
11#[path = "compress_gate.rs"]
12pub(crate) mod gate;
13
14/// Byte-ish budget for the research-prose squeeze (~5k tokens on English prose).
15/// Only oversized prose is truncated; the squeeze's main job is dedup + blank-collapse,
16/// not cutting.
17const RESEARCH_PROSE_CAP: usize = 20_000;
18const RESEARCH_PROSE_CAP_ENV: &str = "LEAN_CTX_RESEARCH_PROSE_CAP";
19
20fn research_prose_cap() -> usize {
21    std::env::var(RESEARCH_PROSE_CAP_ENV)
22        .ok()
23        .and_then(|v| v.trim().parse::<usize>().ok())
24        .filter(|cap| *cap > 0)
25        .unwrap_or(RESEARCH_PROSE_CAP)
26}
27
28/// A tool result up to this size reaches the model whole, from every tool.
29///
30/// Derived from the budgets of the compressors behind this funnel: the
31/// `log_dedup` pattern cuts any block above 30 unique lines to its first 5
32/// and last 10, and the shell engine shows at most 40 lines (`SHOWN`) of an
33/// output it cannot classify — so without a floor every result above ~35
34/// lines left as a fragment, whatever tool produced it. The fragment of a
35/// result the model asked for is followed by a re-read that carries the
36/// whole original again plus a turn of its own; below ~1k tokens (4 KiB,
37/// eight tee floors of [`ccr::MIN_TEE_BYTES`]) the pruning cannot save what
38/// that re-read costs.
39pub(crate) const VERBATIM_MAX_BYTES: usize = 4 * 1024;
40/// A result of at most this many lines also stays whole: one bounded view
41/// (`head -60`, `sed -n 'A,Bp'`, a page of a listing) is what the caller
42/// sized it to be, and twice log_dedup's 30-line block is room for it.
43pub(crate) const VERBATIM_MAX_LINES: usize = 60;
44/// Few long lines (minified JSON, a bundle) are no bounded view: past this
45/// size the line rule no longer holds and the result is compressed.
46const VERBATIM_LINES_MAX_BYTES: usize = 16 * 1024;
47/// The output of a filtering command stays whole up to this size: the
48/// engine's own verbatim budget for verbatim commands (`MAX_VERBATIM_TOKENS`
49/// = 4000 tokens, ~16 KiB). A larger filtered output is compressed and
50/// carries its re-read path like any other.
51const FILTERED_VERBATIM_MAX_BYTES: usize = 16 * 1024;
52
53fn fits_verbatim(content: &str) -> bool {
54    content.len() <= VERBATIM_MAX_BYTES
55        || (content.len() <= VERBATIM_LINES_MAX_BYTES
56            && content.lines().count() <= VERBATIM_MAX_LINES)
57}
58
59thread_local! {
60    /// The command line of the shell tool call whose result is compressed
61    /// ([`with_tool_command`]).
62    static TOOL_COMMAND: RefCell<Option<String>> = const { RefCell::new(None) };
63}
64
65/// Run `f` — a compression of one tool result — knowing the command line of
66/// the tool call that produced it: the `command` input of the matching
67/// `tool_use` (Bash and other shell tools). A result of a filtering command
68/// ([`is_filtering_command`]) is then not pruned again: the caller already
69/// chose the lines it wants. The previous scope is restored afterwards, also
70/// on unwind.
71pub fn with_tool_command<R>(command: Option<&str>, f: impl FnOnce() -> R) -> R {
72    struct Restore(Option<String>);
73    impl Drop for Restore {
74        fn drop(&mut self) {
75            let previous = self.0.take();
76            TOOL_COMMAND.with(|command| *command.borrow_mut() = previous);
77        }
78    }
79    let previous = TOOL_COMMAND.with(|current| current.replace(command.map(str::to_owned)));
80    let _restore = Restore(previous);
81    f()
82}
83
84fn keeps_filtered_output(command: &str, output: &str) -> bool {
85    output.len() <= FILTERED_VERBATIM_MAX_BYTES && is_filtering_command(command)
86}
87
88/// True when `command` already selects the lines its output shows: a
89/// verbatim command of the engine's classifier
90/// (`shell::compress::is_verbatim_output`: head/tail, `sed`/`awk`, `jq`,
91/// `wc`, file viewers, as the whole command or its last stage), or a
92/// filter — the grep family, `head`/`tail`, `sed -n`, `awk`, `cut`, `wc`,
93/// `jq`/`yq`, `sort`, `uniq` — as the leading command or the last pipeline
94/// stage of any segment of a compound command.
95///
96/// One filtering segment exempts the whole command line (`cd x && rg …`,
97/// `sed -n … | cut; ls`, but also `cargo build; wc -l f`). Deliberate: the
98/// exemption is bounded by `FILTERED_VERBATIM_MAX_BYTES`, and without it
99/// the result is compressed with its re-read hint, so either side is
100/// lossless — a too-wide match costs tokens, never content, while a strict
101/// every-segment rule would prune the bounded views the caller chained.
102pub fn is_filtering_command(command: &str) -> bool {
103    if lean_ctx::shell::compress::is_verbatim_output(command) {
104        return true;
105    }
106    command
107        .split(['\n', ';'])
108        .flat_map(|part| part.split("&&"))
109        .flat_map(|part| part.split("||"))
110        .any(|segment| {
111            let mut stages = segment.split('|').map(str::trim).filter(|s| !s.is_empty());
112            let first = stages.next();
113            let last = stages.next_back().or(first);
114            first.is_some_and(is_filter_stage) || last.is_some_and(is_filter_stage)
115        })
116}
117
118fn is_filter_stage(stage: &str) -> bool {
119    let mut words = stage
120        .split_whitespace()
121        .skip_while(|word| word.contains('=') && !word.starts_with('-'))
122        .skip_while(|word| matches!(*word, "sudo" | "command" | "env" | "time" | "nice"));
123    let Some(program) = words.next() else {
124        return false;
125    };
126    let program = program.rsplit('/').next().unwrap_or(program);
127    let args: Vec<&str> = words.collect();
128    match program {
129        "grep" | "egrep" | "fgrep" | "rg" | "ag" | "ack" | "awk" | "gawk" | "cut" | "wc" | "jq"
130        | "yq" | "sort" | "uniq" | "nl" | "head" => true,
131        "tail" => !args
132            .iter()
133            .any(|arg| *arg == "-f" || *arg == "-F" || arg.starts_with("--follow")),
134        "sed" => args
135            .iter()
136            .any(|arg| arg.starts_with("-n") || *arg == "--quiet" || *arg == "--silent"),
137        _ => false,
138    }
139}
140
141/// The hint a result compressed against a tee copy ends with. It names the
142/// copy once: `~/…` under the home (no account name, the rules of
143/// `session_elide::locator`, which hold for Bash and PowerShell alike), else
144/// the shell-quoted absolute path — plus the store-relative name
145/// `ctx_expand` resolves. A pure function of the handle and the home, so
146/// byte-stable (#498).
147pub(crate) fn tee_hint(handle: &str) -> String {
148    let path = std::path::Path::new(handle);
149    let location =
150        super::session_elide::home_location(path).unwrap_or_else(|| shell_quoted(handle));
151    let name = path.file_name().map_or_else(
152        || handle.to_owned(),
153        |name| name.to_string_lossy().into_owned(),
154    );
155    format!(
156        "[lean-ctx: full original at {location} — `cat` it to re-read it exactly (no MCP), \
157         or ctx_expand(id=\"{name}\", head=N|search=\"…\"|json_path=\"…\") for a slice]"
158    )
159}
160
161/// `path` as one shell word: unquoted when it is plain, single-quoted
162/// otherwise. Pure, so the hint that embeds it stays byte-stable (#498).
163fn shell_quoted(path: &str) -> String {
164    if !path.is_empty()
165        && path
166            .bytes()
167            .all(|b| b.is_ascii_alphanumeric() || b"/._-+:@%".contains(&b))
168    {
169        path.to_owned()
170    } else {
171        format!("'{}'", path.replace('\'', r"'\''"))
172    }
173}
174
175/// Proxy compression funnel: routes a tool result to the right compressor.
176///
177/// 1. Already-cited research output (from `ctx_url_read` / the web layer) is kept
178///    verbatim — it is distilled and citation-stamped, so the shell pipeline must
179///    not touch its footer or claim markers.
180/// 2. Prose results (web fetches, doc reads, research MCP bridges) are squeezed
181///    by the prose-aware research compressor instead of the log/code-tuned shell
182///    engine.
183/// 3. Everything else (shell/build/search output) flows through the unified
184///    `compress_if_beneficial` pipeline. A `$ ...` command hint is extracted so
185///    the pattern engine gets the same routing as the CLI and MCP paths.
186pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
187    compress_tool_result_for(content, tool_name, COUNTING_FAMILY)
188}
189
190/// Compresses a tool result under a task-aware policy.
191///
192/// A result the policy leaves uncompressed (`compress_tool_output` off,
193/// `log_compression_level` 0, code under `code_preserve`) leaves as every
194/// funnel leaves a result it keeps whole (`policy_whole`): without its
195/// `<lc_safe>` markers, under protection on record under the lineage of its
196/// original (bd M1 on !646).
197pub fn compress_tool_result_with_policy(
198    content: &str,
199    tool_name: Option<&str>,
200    policy: lean_ctx::core::adaptive_policy::CompressionPolicy,
201) -> String {
202    if policy_keeps_whole(content, policy) {
203        return policy_whole(content, tool_name);
204    }
205    compress_tool_result(content, tool_name)
206}
207
208/// Gateway variant of [`compress_tool_result_with_policy`].
209pub fn compress_tool_result_gateway_with_policy(
210    content: &str,
211    tool_name: Option<&str>,
212    family: TokenizerFamily,
213    policy: lean_ctx::core::adaptive_policy::CompressionPolicy,
214) -> String {
215    if policy_keeps_whole(content, policy) {
216        return policy_whole(content, tool_name);
217    }
218    compress_tool_result_gateway_for(content, tool_name, family)
219}
220
221/// Whether `policy` compresses nothing of `content`.
222fn policy_keeps_whole(
223    content: &str,
224    policy: lean_ctx::core::adaptive_policy::CompressionPolicy,
225) -> bool {
226    !policy.compress_tool_output
227        || policy.log_compression_level == 0
228        || policy.code_preserve && looks_like_code(content)
229}
230
231/// `content` as a policy wrapper leaves it uncompressed: the bytes the
232/// funnels pass through untouched stay untouched — a result that already
233/// carries its way back ([`carries_recovery_stub`]) and the result of an
234/// Engine tool ([`is_lean_ctx_tool`]); see [`compress_inner`] for why —
235/// and every other result is kept whole without its `<lc_safe>` markers
236/// ([`whole_without_markers`]).
237fn policy_whole(content: &str, tool_name: Option<&str>) -> String {
238    if carries_recovery_stub(content) || tool_name.is_some_and(is_lean_ctx_tool) {
239        return content.to_owned();
240    }
241    whole_without_markers(content)
242}
243
244fn looks_like_code(content: &str) -> bool {
245    content.lines().any(|line| {
246        let line = line.trim_start();
247        ["fn ", "struct ", "class ", "function ", "def ", "impl "]
248            .iter()
249            .any(|p| line.starts_with(p))
250            || line.contains('{')
251                && line.contains('}')
252                && (line.contains(';') || line.contains("=>"))
253    })
254}
255
256pub fn compress_tool_result_for(
257    content: &str,
258    tool_name: Option<&str>,
259    family: TokenizerFamily,
260) -> String {
261    // Untouched, `<lc_safe>` markers included: see `carries_recovery_stub`.
262    if carries_recovery_stub(content) {
263        return content.to_owned();
264    }
265    let compressed = compress_inner(content, tool_name, family);
266    attach_ccr(content, compressed, CcrAudience::Local)
267}
268
269/// Shape the output of a host-native shell command whose exact command line is
270/// known (`ctx_shape`, fed by a host mod after the native tool ran). Unlike the
271/// wire funnel, the real command reaches the engine, so its command-gated
272/// policies (protected/verbatim commands, build/test guards, per-tool patterns)
273/// apply exactly as for `ctx_shell`. With a known `exit_code` the outcome-aware
274/// path runs (success compresses, failure keeps its diagnostics); without one
275/// the engine's unknown-outcome guard applies. Lossy results carry the same
276/// deterministic CCR recovery handle (#482, #498).
277///
278/// The same rules as the wire funnel hold: an output that already ends with
279/// its way back is returned whole, and every shorter form leaves through
280/// `attach_ccr` — under protection only with a recovery copy bound to the
281/// output's lineage, otherwise whole and noted with its code.
282///
283/// This route is no request: it holds no tool list of the host that will
284/// read the result. It therefore runs as a pass that knows no expand tool
285/// (`sticky_tools::in_pass`) instead of outside any pass, where the bare
286/// name `ctx_expand` would stand in. Under protection no stub is issued
287/// then: the output stays whole with `recovery.handle_not_followable`, and
288/// nothing is stored. Unprotected, the Community tee handle is unchanged.
289pub fn shape_command_output(command: &str, output: &str, exit_code: Option<i32>) -> String {
290    if output.trim().is_empty()
291        || output.len() < 200
292        || fits_verbatim(output)
293        || keeps_filtered_output(command, output)
294    {
295        // Whole, but without its `<lc_safe>` markers, as the engine and the
296        // wire funnel leave every marked output — below 200 bytes as well
297        // (bd N3 on !646).
298        return whole_without_markers(output);
299    }
300    // Untouched, `<lc_safe>` markers included: see `carries_recovery_stub`.
301    if carries_recovery_stub(output) {
302        return output.to_string();
303    }
304    let compressed = match exit_code {
305        Some(code) => {
306            lean_ctx::shell::compress::engine::compress_for_outcome(command, output, code)
307        }
308        None => lean_ctx::shell::compress::engine::compress_if_beneficial_pub(command, output),
309    };
310    super::sticky_tools::in_pass(|| attach_ccr(output, compressed, CcrAudience::Local))
311}
312
313/// [`compress_tool_result`] for a caller that is no request of this proxy:
314/// the output of a host-native tool handed in after it ran (`ctx_shape`,
315/// every tool whose command line is not known).
316///
317/// Such a caller holds no tool list of the host that will read the result,
318/// so no expand tool is known to be followable there. The compression runs
319/// as a pass that knows no tool (`sticky_tools::in_pass`), never outside any
320/// pass, where the bare name `ctx_expand` would stand in. Under protection
321/// no stub is issued then: the text stays whole with
322/// `recovery.handle_not_followable`, and nothing is stored. Unprotected, the
323/// result and its Community tee handle are those of [`compress_tool_result`].
324pub fn shape_tool_output(output: &str, tool_name: Option<&str>) -> String {
325    super::sticky_tools::in_pass(|| compress_tool_result(output, tool_name))
326}
327
328/// [`compress_tool_result`] for the `/v1/compress` gateway contract (#702):
329/// identical compression, but a lossy result advertises its retrieval hash in
330/// LiteLLM's regex-locked `hash=<24hex>` form, so a gateway running the
331/// headroom-guardrail CCR loop (BerriAI/litellm#31681) can inject its retrieve
332/// tool and resolve the original via `GET /v1/retrieve/{hash}`.
333///
334/// Any ambient savings footer is stripped *before* the marker is attached:
335/// savings figures belong in the caller's structured `stats` (#498), while the
336/// marker is functional content that must survive as the last line.
337pub fn compress_tool_result_gateway(content: &str, tool_name: Option<&str>) -> String {
338    compress_tool_result_gateway_for(content, tool_name, COUNTING_FAMILY)
339}
340
341pub fn compress_tool_result_gateway_for(
342    content: &str,
343    tool_name: Option<&str>,
344    family: TokenizerFamily,
345) -> String {
346    // Before the footer strip below: a local stub has the footer's shape.
347    // Untouched, `<lc_safe>` markers included: see `carries_recovery_stub`.
348    if carries_recovery_stub(content) {
349        return content.to_owned();
350    }
351    let compressed = compress_inner(content, tool_name, family);
352    let clean = lean_ctx::core::protocol::strip_trailing_savings_footer(&compressed).to_string();
353    attach_ccr(content, clean, CcrAudience::Gateway)
354}
355
356/// Who reads a CCR stub: a local agent (path handle / in-band marker) or a
357/// remote gateway whose agentic loop scans for `hash=<24hex>` (#702).
358#[derive(Clone, Copy, PartialEq)]
359enum CcrAudience {
360    Local,
361    Gateway,
362}
363
364/// Who reads what a compression pass sends, as the route that runs the pass
365/// knows it ([`observing`]).
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub(crate) enum Reader {
368    /// A model behind a provider: it can call `ctx_expand`, never a route of
369    /// this proxy.
370    #[cfg(feature = "http-server")]
371    Model,
372    /// The caller of `/v1/compress`: it can call this proxy's routes.
373    GatewayCaller,
374}
375
376/// The blocks a compression pass left whole under protection because no
377/// recovery copy could back a shorter form, and why. Content-free towards
378/// every reader: a block is held by its digest only to count it once, and
379/// only codes and counts leave this type.
380#[derive(Debug, Default, Clone, PartialEq, Eq)]
381pub(crate) struct KeptWhole {
382    blocks: BTreeMap<[u8; 32], &'static str>,
383}
384
385impl KeptWhole {
386    /// The first code noted for a block stands: a later pass over the same
387    /// bytes does not count it again.
388    fn note(&mut self, block: &str, code: &'static str) {
389        self.blocks
390            .entry(*blake3::hash(block.as_bytes()).as_bytes())
391            .or_insert(code);
392    }
393
394    #[cfg(feature = "http-server")]
395    pub(crate) fn merge(&mut self, other: Self) {
396        for (block, code) in other.blocks {
397            self.blocks.entry(block).or_insert(code);
398        }
399    }
400
401    #[cfg(feature = "http-server")]
402    pub(crate) fn is_empty(&self) -> bool {
403        self.blocks.is_empty()
404    }
405
406    /// Blocks per code, in code order.
407    #[cfg(feature = "http-server")]
408    pub(crate) fn counts(&self) -> BTreeMap<&'static str, usize> {
409        let mut counts = BTreeMap::new();
410        for code in self.blocks.values() {
411            *counts.entry(*code).or_insert(0) += 1;
412        }
413        counts
414    }
415
416    /// The distinct codes, comma-separated in code order — the value of the
417    /// `x-leanctx-reason-codes` header of a reply that was NOT refused.
418    /// `None`: nothing stayed whole for want of a recovery copy.
419    #[cfg(feature = "http-server")]
420    pub(crate) fn codes(&self) -> Option<String> {
421        let counts = self.counts();
422        (!counts.is_empty()).then(|| counts.keys().copied().collect::<Vec<_>>().join(","))
423    }
424
425    /// `code=count` pairs for a log line.
426    #[cfg(feature = "http-server")]
427    pub(crate) fn summary(&self) -> String {
428        self.counts()
429            .iter()
430            .map(|(code, count)| format!("{code}={count}"))
431            .collect::<Vec<_>>()
432            .join(", ")
433    }
434}
435
436struct Observation {
437    reader: Reader,
438    kept: KeptWhole,
439}
440
441thread_local! {
442    /// The compression pass running on this thread, if a route observes it.
443    /// Compression is synchronous from the route down to [`attach_ccr`].
444    static OBSERVATION: RefCell<Option<Observation>> = const { RefCell::new(None) };
445}
446
447#[cfg(test)]
448thread_local! {
449    /// Every call of [`note_kept_whole`] on this thread. [`KeptWhole`]
450    /// counts a block once however often it is noted, so only this shows a
451    /// note made twice.
452    static NOTE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
453}
454
455/// The calls of [`note_kept_whole`] on this thread so far.
456#[cfg(all(test, feature = "http-server"))]
457pub(crate) fn note_calls() -> usize {
458    NOTE_CALLS.with(std::cell::Cell::get)
459}
460
461/// Run one synchronous compression pass for `reader` and return, next to its
462/// result, the blocks it left whole under protection. An inner pass reports
463/// to its own caller only.
464#[cfg(feature = "http-server")]
465pub(crate) fn observing<T>(reader: Reader, compression: impl FnOnce() -> T) -> (T, KeptWhole) {
466    struct Restore(Option<Observation>);
467    impl Drop for Restore {
468        fn drop(&mut self) {
469            let outer = self.0.take();
470            OBSERVATION.with(|slot| *slot.borrow_mut() = outer);
471        }
472    }
473    let restore = Restore(OBSERVATION.with(|slot| {
474        slot.replace(Some(Observation {
475            reader,
476            kept: KeptWhole::default(),
477        }))
478    }));
479    let result = compression();
480    let kept = OBSERVATION
481        .with(|slot| slot.borrow_mut().take())
482        .map_or_else(KeptWhole::default, |observation| observation.kept);
483    drop(restore);
484    (result, kept)
485}
486
487/// The reader of the pass running on this thread; `None` outside a route.
488fn observed_reader() -> Option<Reader> {
489    OBSERVATION.with(|slot| slot.borrow().as_ref().map(|observation| observation.reader))
490}
491
492/// `block` stays whole under protection for the content-free reason `code`.
493/// Counted for the route that observes the pass; logged otherwise.
494pub(crate) fn note_kept_whole(block: &str, code: &'static str) {
495    #[cfg(test)]
496    NOTE_CALLS.with(|calls| calls.set(calls.get() + 1));
497    OBSERVATION.with(|slot| {
498        if let Some(observation) = slot.borrow_mut().as_mut() {
499            observation.kept.note(block, code);
500        } else {
501            tracing::debug!("lean-ctx proxy: block kept whole, no recovery copy ({code})");
502        }
503    });
504}
505
506/// Whether nothing may be shortened without a recovery copy bound to its
507/// lineage: a policy pack, governed or sovereign mode, or an unloadable
508/// configuration.
509pub(crate) fn protected() -> bool {
510    lean_ctx::core::context_admission::stored::source_authority_required()
511}
512
513/// How a lineage-bound recovery stub opens. Deliberately not the
514/// savings-footer shape (`[lean-ctx: `): a footer strip must never eat it.
515///
516/// The grammar of the stub, stated once: one line,
517/// `[lean-ctx recovery: full original archived — <tool>(id="<64 hex>",
518/// head=N|search="…"|json_path="…") for a slice]`. `<tool>` is the Engine's
519/// expand tool under the name the host of the request registered it with
520/// ([`expand_tool_name`]: at most 128 characters of `[A-Za-z0-9_.:/-]`), so
521/// it can hold neither `]` nor a line break. Everything that recognises a
522/// stub ([`carries_recovery_stub`]) reads the fixed opening and the closing
523/// bracket only, whatever the tool is called.
524const RECOVERY_STUB_OPEN: &str = "[lean-ctx recovery: ";
525
526/// The Engine tool that resolves a recovery id, by its bare name.
527const EXPAND_TOOL: &str = "ctx_expand";
528
529/// The last line of a block that was compressed under protection, for a
530/// model: `tool` — the Engine's expand tool as the host registered it —
531/// resolves the 64-hex `id` under the authority that holds then. A pure
532/// function of the name and the id, so the block stays byte-stable while the
533/// host keeps the name.
534pub(crate) fn recovery_stub_for(tool: &str, id: &RecoveryId) -> String {
535    format!(
536        "{RECOVERY_STUB_OPEN}full original archived — \
537         {tool}(id=\"{}\", head=N|search=\"…\"|json_path=\"…\") for a slice]",
538        id.as_str()
539    )
540}
541
542/// [`recovery_stub_for`] with the tool's bare name.
543#[cfg(test)]
544pub(crate) fn recovery_stub(id: &RecoveryId) -> String {
545    recovery_stub_for(EXPAND_TOOL, id)
546}
547
548/// [`recovery_stub_for`] for the caller of `/v1/compress`, which can follow a
549/// route of this proxy. No `hash=`: the id is not a tee hash, and a LiteLLM
550/// guardrail must not send it to `/v1/retrieve`.
551fn reference_stub(id: &RecoveryId) -> String {
552    format!(
553        "[lean-ctx CCR: full original archived — GET /v1/references/{} on this gateway \
554         returns it while its sources are admitted]",
555        id.as_str()
556    )
557}
558
559/// Upper bound of the length in bytes of a stub with the bare tool name: a
560/// shrink below it gains nothing. A stub with a longer, prefixed name is
561/// caught where it is attached — a block that would not get shorter with its
562/// stub stays as it is.
563const STUB_MAX_BYTES: usize = 256;
564
565/// Text that already ends with a way back to its original. A second pass
566/// passes it through: compressing it again could drop the handle, and the
567/// local stubs have the shape of a savings footer the gateway funnel strips.
568///
569/// It passes through byte for byte, `<lc_safe>` markers included (bd S1 on
570/// !646). Such a text is what an earlier pass of a funnel sent, and that
571/// pass already left it without the markers it handled: the stub is
572/// appended to a compressed form, which the marker handling of
573/// [`compress_inner`] produced. Marker text that is still there is content
574/// of the original block itself, not a marker of this pass. And the bytes
575/// are those on record: under protection the earlier pass recorded exactly
576/// them under the original's lineage (`delivered::record_derived`), and the
577/// provider's cache prefix holds them (#448). A rewrite here would make the
578/// text one of unknown lineage and break that prefix, for no gain.
579fn carries_recovery_stub(content: &str) -> bool {
580    let last = content
581        .trim_end_matches('\n')
582        .rsplit('\n')
583        .next()
584        .unwrap_or_default();
585    last.ends_with(']')
586        && [
587            RECOVERY_STUB_OPEN,
588            "[lean-ctx CCR: full original ",
589            "[lean-ctx: full original ",
590        ]
591        .iter()
592        .any(|open| last.starts_with(open))
593}
594
595/// Make a live-compressed `tool_result` non-lossy (#482): when compression
596/// removed a meaningful amount, tee the verbatim original to the shared
597/// content-addressed store and append a deterministic recovery handle. The
598/// handle is a pure function of the content hash, so the rewritten result is
599/// byte-stable across turns and never invalidates the provider cache prefix
600/// (#448). Passthrough / verbatim results (no real shrink) keep their bytes.
601/// When no recovery copy can be written (an active policy keeps no originless
602/// copies, or the store fails) the original is returned instead of the lossy
603/// form: a fresh result is never shortened without a way back.
604/// "The original" on every such path is the original kept whole as it leaves
605/// a funnel: without its `<lc_safe>` markers ([`keep_whole`]).
606fn attach_ccr(original: &str, result: String, audience: CcrAudience) -> String {
607    use super::sticky_tools;
608    if result == original {
609        return result;
610    }
611    // Every path below that keeps the original keeps it whole, but without
612    // its `<lc_safe>` markers (bd N1 on !646): the form a marked result
613    // leaves the funnel in when nothing of it is shortened.
614    let unmarked = unmarked_form(original);
615    let whole = || keep_whole(original, unmarked.as_deref());
616    // Only the `<lc_safe>` markers were dropped: nothing was lost, so no way
617    // back is needed, and the rule below must not hand the markers back.
618    if unmarked.as_deref() == Some(result.as_str()) {
619        return whole();
620    }
621    let shrink = original.len().saturating_sub(result.len());
622    if original.len() < ccr::MIN_TEE_BYTES || shrink < ccr::MIN_TEE_BYTES {
623        // Too small for a tee, so no way back could be named. Before, an
624        // unprotected result left here shortened as it was — a lossy one
625        // (`[N lines omitted]` from a dedup of short lines) without any
626        // re-read path. A shrink this small is not worth a loss: the
627        // original leaves whole, as it already did under protection.
628        if !protected() || shrink <= STUB_MAX_BYTES {
629            return whole();
630        }
631    }
632    // The gateway funnel on a route whose reader is a model (the forward
633    // pipeline) or is unknown: neither the tee hash nor a proxy route is a
634    // way back that reader can follow. Neither is a stub naming a tool the
635    // host of this request did not list itself, or — under protection — a
636    // stub for a block whose own tool call is not on record in this store
637    // as answered by an Engine of this store (`sticky_tools::expand_tool_for`
638    // states the whole decision). Decided before anything is stored.
639    let tool = (audience == CcrAudience::Local)
640        .then(|| sticky_tools::expand_tool_for(original))
641        .flatten();
642    let followable =
643        tool.is_some() || observed_reader() == Some(Reader::GatewayCaller) || !protected();
644    if !followable {
645        note_kept_whole(original, HANDLE_NOT_FOLLOWABLE);
646        return whole();
647    }
648    match recovery_copy(original) {
649        Some(RecoveryCopy::Bound {
650            id,
651            lineage,
652            project,
653        }) => {
654            let stub = if audience == CcrAudience::Local {
655                recovery_stub_for(tool.as_deref().unwrap_or(EXPAND_TOOL), &id)
656            } else {
657                reference_stub(&id)
658            };
659            let sent = format!("{result}\n{stub}");
660            if sent.len() >= original.len() {
661                return whole();
662            }
663            // The one record a site other than an Engine release point makes
664            // (`delivered::record_derived`). Guaranteed here:
665            // 1. `lineage` came from `lineage_of` for exactly `original`, in
666            //    this request, inside the same project scope (`bound_copy`);
667            // 2. `sent` derives from `original` alone: `result` is the
668            //    compressor's output for that one block, and the rest is the
669            //    fixed stub text with the id of its recovery copy;
670            // 3. no second block takes part, so there is nothing to join —
671            //    a block without a lineage never reaches this arm.
672            let recorded = super::request_project::in_project(&project, || {
673                delivered::record_derived(&delivered::digest(&sent), &lineage)
674            });
675            if recorded {
676                // The model's stub names the expand tool the host listed:
677                // the request's pass holds the stubbed block next to its
678                // original until the request has left (`gate::Issued`). The
679                // gateway caller's stub names a route, not a tool.
680                if audience == CcrAudience::Local {
681                    gate::note_issued(original, &sent);
682                }
683                sent
684            } else {
685                // The shortened block would be of unknown lineage for every
686                // later turn; the original is not.
687                kept_after_refused_record(original, unmarked.as_deref())
688            }
689        }
690        // Gateway (#702): the reader is a model behind a LiteLLM-style gateway.
691        // A local path is useless there; advertise the 24-hex retrieval hash in
692        // the exact shape the guardrail's marker regex captures. The hash is a
693        // pure function of the content, so the stub stays byte-stable (#498).
694        // The `[lean-ctx CCR:` prefix is deliberately NOT the savings-footer
695        // shape (`[lean-ctx: `): this line is functional content — a footer
696        // strip must never eat it.
697        Some(RecoveryCopy::Tee(handle)) if audience == CcrAudience::Gateway => {
698            sticky_tools::mark_ccr_active(0);
699            let hash = ccr::litellm_hash(original);
700            format!(
701                "{result}\n[lean-ctx CCR: full original elided to save tokens — call the \
702                 retrieve tool with hash={hash}, or read {handle} locally]"
703            )
704        }
705        Some(RecoveryCopy::Tee(handle)) => {
706            sticky_tools::mark_ccr_active(0);
707            match ccr::inband_locator(&handle) {
708                Some(marker) => format!(
709                    "{result}\n[lean-ctx: full original elided to save tokens — echo {marker} \
710                     on your next turn to get the verbatim original spliced back inline]"
711                ),
712                None => format!("{result}\n{}", tee_hint(&handle)),
713            }
714        }
715        None => whole(),
716    }
717}
718
719/// The text `original` leaves as when it carries `<lc_safe>` markers and is
720/// kept whole: the markers dropped, every byte between them verbatim.
721/// `None`: there are no markers.
722fn unmarked_form(original: &str) -> Option<String> {
723    lean_ctx::core::protect::has_markers(original)
724        .then(|| lean_ctx::core::protect::compress_preserving(original, str::to_owned))
725}
726
727/// `original` kept whole, as it leaves a funnel: without its `<lc_safe>`
728/// markers (`unmarked`, from [`unmarked_form`]) — [`whole_form`], with a
729/// refused record noted `DERIVED_NOT_RECORDED`.
730fn keep_whole(original: &str, unmarked: Option<&str>) -> String {
731    let whole = whole_form(original, unmarked);
732    if whole.record_refused {
733        note_kept_whole(original, DERIVED_NOT_RECORDED);
734    }
735    whole.text
736}
737
738/// What [`whole_form`] keeps.
739struct WholeForm {
740    text: String,
741    /// The unmarked form could not be put on record, so `text` is
742    /// `original` with its markers. Not noted yet.
743    record_refused: bool,
744}
745
746/// `original` kept whole, without its `<lc_safe>` markers where that keeps
747/// its lineage. Notes nothing: the caller notes a refused record, once.
748///
749/// Under protection the unmarked form is a text derived from `original`,
750/// and a derived text without a record is of unknown lineage for every
751/// later turn (`sealed_origin::Lineage::Unknown`) even where `original`
752/// is not. So (bd N2 on !646):
753/// - `original` has a complete lineage in the proxy's project: the unmarked
754///   form is put on record under it (`delivered::record_derived`). Its
755///   preconditions hold — the lineage is `lineage_of` for exactly
756///   `original`, in this request and inside the proxy's project scope; the
757///   unmarked form derives from that one block alone, with no text added.
758///   Without the record `original` stays with its markers
759///   (`record_refused`): a known lineage is never traded for a cosmetic
760///   change.
761/// - `original` has no lineage, or only an incomplete one (bd N5): there is
762///   nothing to keep. An incomplete lineage makes a text as unknown as none
763///   does (`Lineage::is_complete`; `record_derived` would refuse it too), so
764///   both are treated alike: the unmarked form is no less known than the
765///   original, and nothing is recorded or stored.
766/// - The proxy has no project (bd S2): nothing is looked up or recorded, as
767///   in [`bound_copy`], which refuses a copy then (`NO_PROJECT`). Without a
768///   project no lineage can be bound for this request at all — a lookup
769///   outside a project scope is no lineage of it, and `record_derived`
770///   records nothing without a request project — so the case is that of no
771///   lineage: the unmarked form leaves, unrecorded. Nothing is noted: no
772///   shorter form was refused, and nothing of the block was lost.
773///
774/// The record is written again whenever the same block is kept whole again
775/// (each request, each block). That is idempotent (bd N6):
776/// `delivered::record_derived` is `record_lineage`, whose `store_at` keeps
777/// one entry per derived digest and project and joins a repeat into it
778/// (`Lineage::join`). A union with the same lineage adds no source, and the
779/// presenter reference only moves to the newest place, so a repeat adds
780/// nothing but a fresh time.
781fn whole_form(original: &str, unmarked: Option<&str>) -> WholeForm {
782    let kept = |text: &str, record_refused| WholeForm {
783        text: text.to_owned(),
784        record_refused,
785    };
786    let Some(unmarked) = unmarked else {
787        return kept(original, false);
788    };
789    if !protected() {
790        return kept(unmarked, false);
791    }
792    let Some(project) = super::request_project::current_source_project() else {
793        return kept(unmarked, false);
794    };
795    let recorded = super::request_project::in_project(&project, || {
796        delivered::lineage_of(&delivered::digest(original))
797            .filter(delivered::Lineage::is_complete)
798            .map(|lineage| delivered::record_derived(&delivered::digest(unmarked), &lineage))
799    });
800    if recorded == Some(false) {
801        return kept(original, true);
802    }
803    kept(unmarked, false)
804}
805
806/// `original` kept whole because the record of its shortened form was
807/// refused: noted `DERIVED_NOT_RECORDED` once (bd S3 on !646). The note
808/// stands for the refused shorter form, so it is made whatever happens to
809/// the unmarked form; [`whole_form`] notes nothing, so a refused record of
810/// the unmarked form as well adds no second note.
811fn kept_after_refused_record(original: &str, unmarked: Option<&str>) -> String {
812    note_kept_whole(original, DERIVED_NOT_RECORDED);
813    whole_form(original, unmarked).text
814}
815
816/// [`keep_whole`] for a text whose unmarked form is not at hand yet.
817fn whole_without_markers(original: &str) -> String {
818    keep_whole(original, unmarked_form(original).as_deref())
819}
820
821/// The one place a compressed result gets its way back: store a recovery
822/// copy of `original` and return its handle, or `None` when no copy may
823/// exist — in which case the caller forwards the original instead of the
824/// lossy form.
825///
826/// - Unprotected (Community, developer mode): the originless tee store, as
827///   before.
828/// - Protected (a policy pack, governed or sovereign mode, an unloadable
829///   configuration): a copy exists only for a block whose sources are known
830///   ([`bound_copy`]). The proxy only sees a request body and observed no
831///   read; permission to read is not permission to retain. Without a known,
832///   currently admitted lineage there is no copy and the caller keeps the
833///   original.
834fn recovery_copy(original: &str) -> Option<RecoveryCopy> {
835    if !lean_ctx::core::context_admission::stored::source_authority_required() {
836        return ccr::persist(original).map(RecoveryCopy::Tee);
837    }
838    match bound_copy(original) {
839        Ok(copy) => Some(copy),
840        Err(code) => {
841            note_kept_whole(original, code);
842            None
843        }
844    }
845}
846
847/// The gate of every transformation other than the compressor that replaces
848/// a block by a shorter form under protection (history pruning, truncation):
849/// `shortened` followed by the stub of a recovery copy of `original`, on
850/// record under the original's lineage — or `None`, and the caller keeps
851/// `original` whole. `None` is noted with its code, except where the form
852/// with its stub would not be shorter at all.
853pub(crate) fn shorten_with_copy(original: &str, shortened: &str) -> Option<String> {
854    // Decided before anything is stored: a request whose host did not list
855    // the expand tool itself hands out no stub that names it, and under
856    // protection neither does text that is not one tool-result block whose
857    // call this store's Engine answered (`sticky_tools::expand_tool_for`).
858    let Some(tool) = super::sticky_tools::expand_tool_for(original) else {
859        note_kept_whole(original, HANDLE_NOT_FOLLOWABLE);
860        return None;
861    };
862    let copy = match bound_copy(original) {
863        Ok(copy) => copy,
864        Err(code) => {
865            note_kept_whole(original, code);
866            return None;
867        }
868    };
869    let RecoveryCopy::Bound {
870        id,
871        lineage,
872        project,
873    } = copy
874    else {
875        return None;
876    };
877    let sent = format!("{shortened}\n{}", recovery_stub_for(&tool, &id));
878    if sent.len() >= original.len() {
879        return None;
880    }
881    // `record_derived`, as in `attach_ccr`: the lineage is that of exactly
882    // `original`, looked up in this request and scope; `sent` is a cut of
883    // that one block plus fixed text of the cutting code and the stub.
884    let recorded = super::request_project::in_project(&project, || {
885        delivered::record_derived(&delivered::digest(&sent), &lineage)
886    });
887    if recorded {
888        // This stub names the host's expand tool as well (see `attach_ccr`).
889        gate::note_issued(original, &sent);
890        Some(sent)
891    } else {
892        note_kept_whole(original, DERIVED_NOT_RECORDED);
893        None
894    }
895}
896
897/// A block that an earlier request already carried may not be replaced by a
898/// pointer to that request: nothing in THIS request holds its content.
899pub(crate) const DEDUP_WITHOUT_COPY: &str = "recovery.dedup_without_copy";
900/// The conversation may not be replaced by a summary: no copy backs it.
901#[cfg(feature = "http-server")]
902pub(crate) const SUMMARY_WITHOUT_COPY: &str = "recovery.summary_without_copy";
903
904/// The reader of this pass cannot follow any handle a copy would have.
905const HANDLE_NOT_FOLLOWABLE: &str = "recovery.handle_not_followable";
906/// The copy exists, but the shortened block could not be put on record
907/// under the lineage of its original.
908const DERIVED_NOT_RECORDED: &str = "recovery.derived_not_recorded";
909/// No project of the proxy that sources could be admitted for.
910const NO_PROJECT: &str = "recovery.no_project";
911/// The block is not text the Engine delivered with a complete lineage.
912const UNKNOWN_LINEAGE: &str = "recovery.unknown_lineage";
913
914/// The recovery copy of `original` under protection, or the content-free
915/// code of why there is none. Inside the scope of the proxy's own project
916/// (operator configuration, `request_project`): the Engine's lineage of
917/// exactly this text, and a copy stored under it — which the store accepts
918/// only while every source of that lineage is admitted now. A file-only
919/// lineage lands on the Engine's existing source-bound archive entry for the
920/// same text, so no second copy is written.
921fn bound_copy(original: &str) -> Result<RecoveryCopy, &'static str> {
922    let project = super::request_project::current_source_project().ok_or(NO_PROJECT)?;
923    super::request_project::in_project(&project, || {
924        let lineage = delivered::lineage_of(&delivered::digest(original))
925            .filter(delivered::Lineage::is_complete)
926            .ok_or(UNKNOWN_LINEAGE)?;
927        let id = lean_ctx::core::archive::store_recovery_with_lineage(original, &lineage)
928            .map_err(recovery_code)?;
929        Ok((id, lineage))
930    })
931    .map(|(id, lineage)| RecoveryCopy::Bound {
932        id,
933        lineage: Box::new(lineage),
934        project,
935    })
936}
937
938/// The content-free code of a recovery refusal.
939pub(crate) fn recovery_code(refusal: RecoveryRefusal) -> &'static str {
940    match refusal {
941        RecoveryRefusal::UnknownLineage => UNKNOWN_LINEAGE,
942        RecoveryRefusal::SourceNotPresented => "recovery.source_not_presented",
943        RecoveryRefusal::SourceNoLongerAdmitted => "recovery.source_no_longer_admitted",
944        RecoveryRefusal::NotStorable => "recovery.not_storable",
945        RecoveryRefusal::Missing => "recovery.missing",
946    }
947}
948
949/// Resolve a recovery id under the authority that holds now, for the proxy's
950/// own project. `None`: `id` is not a recovery id at all. Without a project
951/// nothing is looked up.
952#[cfg(feature = "http-server")]
953pub(crate) fn resolve_recovery(id: &str) -> Option<Result<String, &'static str>> {
954    let id = RecoveryId::parse(id)?;
955    let Some(project) = super::request_project::current_source_project() else {
956        // Unprotected deployments hold no recovery copies: not a recovery id.
957        return lean_ctx::core::context_admission::stored::source_authority_required()
958            .then_some(Err(NO_PROJECT));
959    };
960    Some(super::request_project::in_project(&project, || {
961        lean_ctx::core::archive::retrieve_recovery_checked(&id).map_err(recovery_code)
962    }))
963}
964
965/// Where the way back of a compressed result leads.
966enum RecoveryCopy {
967    /// A tee file of the originless store; the value is its handle.
968    Tee(String),
969    /// A copy in the Engine's archive, bound to the lineage of the original
970    /// and stored for `project`.
971    Bound {
972        id: RecoveryId,
973        lineage: Box<delivered::Lineage>,
974        project: std::path::PathBuf,
975    },
976}
977
978fn compress_inner(content: &str, tool_name: Option<&str>, family: TokenizerFamily) -> String {
979    if content.trim().is_empty() {
980        return content.to_string();
981    }
982    // #479: lean-ctx's own MCP tools already applied their compression policy at
983    // the tool boundary — honouring `raw=true`/`bypass`, `<lc_safe>` spans and
984    // the configured aggressiveness. Their `raw` intent lives in the originating
985    // `tool_use` input, which is invisible here, so re-compressing on the wire
986    // would silently undo an explicit `raw=true` and double-compress everything
987    // else. Pass results from `ctx_*` tools through untouched.
988    //
989    // Untouched includes any `<lc_safe>` text in them (bd S1 on !646). The
990    // Engine handles its markers at the tool boundary: its shell compressor
991    // splices protected spans and drops the markers
992    // (`shell::compress::engine`), so a `ctx_shell` result leaves without
993    // them. Marker text that remains is content the tool was asked to
994    // deliver — e.g. a `ctx_read` of a file that itself contains
995    // `<lc_safe>`, verbatim under `raw=true` — and under protection the
996    // Engine recorded exactly these bytes with their lineage
997    // (`delivered::record_tool_delivery`). Stripping it here would alter a
998    // raw read and turn a known lineage into an unknown one.
999    if tool_name.is_some_and(is_lean_ctx_tool) {
1000        return content.to_string();
1001    }
1002
1003    // #709: honour explicit <lc_safe>…</lc_safe> spans on the proxy path too.
1004    // Protected spans pass through verbatim; each unprotected segment flows back
1005    // through the normal funnel (markers are stripped, so this never recurses).
1006    if lean_ctx::core::protect::has_markers(content) {
1007        return lean_ctx::core::protect::compress_preserving(content, |seg| {
1008            compress_inner(seg, tool_name, family)
1009        });
1010    }
1011
1012    // After the marker handling, so a result of any size leaves without its
1013    // `<lc_safe>` markers — below 200 bytes as well (bd N3 on !646): each
1014    // unprotected segment meets these rules itself.
1015    if content.len() < 200 || fits_verbatim(content) {
1016        return content.to_string();
1017    }
1018    if TOOL_COMMAND.with(|command| {
1019        command
1020            .borrow()
1021            .as_deref()
1022            .is_some_and(|command| keeps_filtered_output(command, content))
1023    }) {
1024        return content.to_string();
1025    }
1026
1027    if is_cited_research_output(content) {
1028        if looks_like_markdown(content) {
1029            let prose = compress_prose(content, None);
1030            if prose.compressed_tokens < prose.original_tokens {
1031                return prose.compressed;
1032            }
1033        }
1034        return content.to_string();
1035    }
1036
1037    if extract_command_hint(content).is_none()
1038        && looks_like_prose(content)
1039        && let Some(out) = squeeze_research_prose(content, family)
1040    {
1041        return out;
1042    }
1043
1044    let cmd = infer_command(content, tool_name);
1045
1046    // Proxy fidelity guard. A foreign shell tool gives us at most a generic
1047    // command (`"shell"`) or none, so the engine's command-gated build/test
1048    // verbatim guards never fire. When the *output* is unmistakably a build or
1049    // test run, preserve it verbatim (bounded by safety-line-preserving
1050    // truncation) so compiler errors, panics and test summaries reach the model
1051    // intact — the exact signal a bug-fix task depends on.
1052    let generic_command = cmd.is_empty() || cmd == "shell";
1053    if generic_command
1054        && (output_looks_like_test_run(content) || output_looks_like_build_failure(content))
1055    {
1056        return lean_ctx::shell::compress::engine::preserve_verbatim_pub_for(content, family);
1057    }
1058
1059    lean_ctx::shell::compress::engine::compress_if_beneficial_for(&cmd, content, family)
1060}
1061
1062/// Strong, ecosystem-spanning signals that an output is a *test run* (passing or
1063/// failing). Conservative — matches the summary/result lines a bug-fix task must
1064/// never lose. Only consulted on the proxy path when the real command is unknown.
1065fn output_looks_like_test_run(content: &str) -> bool {
1066    const NEEDLES: &[&str] = &[
1067        "test result:",            // rust
1068        "short test summary info", // pytest
1069        " passed in ",             // pytest summary
1070        " failed in ",             // pytest summary
1071        "=== RUN",                 // go
1072        "--- FAIL:",               // go
1073        "--- PASS:",               // go
1074        "Test Suites:",            // jest
1075        " examples, ",             // rspec ("5 examples, 0 failures")
1076        "FAILED",                  // generic test failure marker
1077    ];
1078    NEEDLES.iter().any(|n| content.contains(n))
1079}
1080
1081/// Strong, specific signals of a build / compile / runtime failure across the
1082/// major toolchains. Used only on the proxy path for generically-named tools so
1083/// the failing diagnostics (paths, lines, messages) survive intact.
1084fn output_looks_like_build_failure(content: &str) -> bool {
1085    const NEEDLES: &[&str] = &[
1086        "error[",                            // rustc (E0277 …)
1087        ": error:",                          // gcc / clang "file.c:12:5: error:"
1088        "fatal error:",                      // gcc / clang
1089        "undefined reference to",            // linker
1090        "panicked at",                       // rust runtime
1091        "could not compile",                 // cargo
1092        "Traceback (most recent call last)", // python
1093        "AssertionError",                    // python / junit
1094        "make: ***",                         // make
1095        "Build FAILED",
1096        "BUILD FAILED",
1097        "Segmentation fault",
1098    ];
1099    NEEDLES.iter().any(|n| content.contains(n))
1100}
1101
1102/// True when `content` is a lean-ctx web read: distilled body + citation footer
1103/// (`Source: …\nSite: … · Retrieved: …`). Such output is re-compression-hostile.
1104fn is_cited_research_output(content: &str) -> bool {
1105    content.contains("· Retrieved: ") && content.contains("\nSource: ")
1106}
1107
1108/// Code/shell symbols whose density cleanly separates source/logs from prose.
1109const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
1110
1111/// Conservative prose detector: substantial, letter-dense, low code-symbol, with
1112/// real sentences and long lines. Code, logs, tables and JSON all fail this.
1113fn looks_like_prose(content: &str) -> bool {
1114    let sample: String = content.chars().take(4000).collect();
1115    let total = sample.chars().count();
1116    if total < 600 {
1117        return false;
1118    }
1119    let total_f = total as f32;
1120    let alpha = sample.chars().filter(|c| c.is_alphabetic()).count() as f32;
1121    let spaces = sample.chars().filter(|c| *c == ' ').count() as f32;
1122    let symbols = sample.chars().filter(|c| CODE_SYMBOLS.contains(*c)).count() as f32;
1123
1124    if alpha / total_f < 0.6 || spaces / total_f < 0.12 || symbols / total_f > 0.06 {
1125        return false;
1126    }
1127    if sample.matches(['.', '!', '?']).count() < 4 {
1128        return false;
1129    }
1130
1131    let non_empty: Vec<&str> = sample.lines().filter(|l| !l.trim().is_empty()).collect();
1132    if non_empty.is_empty() {
1133        return false;
1134    }
1135    let avg_len =
1136        non_empty.iter().map(|l| l.chars().count()).sum::<usize>() as f32 / non_empty.len() as f32;
1137    avg_len >= 40.0
1138}
1139
1140fn looks_like_markdown(content: &str) -> bool {
1141    content.lines().any(|line| {
1142        let trimmed = line.trim_start();
1143        trimmed.starts_with("# ")
1144            || trimmed.starts_with("## ")
1145            || trimmed.starts_with("```")
1146            || trimmed.starts_with("~~~")
1147            || matches!(trimmed.as_bytes(), [b'-' | b'*' | b'+', b' ', ..])
1148            || trimmed.matches('|').count() >= 2
1149    })
1150}
1151
1152/// Apply the prose squeeze, returning a footer-stamped result only when it
1153/// actually saves tokens; otherwise `None` so the normal pipeline can try.
1154fn squeeze_research_prose(content: &str, family: TokenizerFamily) -> Option<String> {
1155    let before = count_tokens_for(content, family);
1156    let squeezed = squeeze_research_prose_body(content);
1157    if squeezed.trim().is_empty() {
1158        return None;
1159    }
1160    let after = count_tokens_for(&squeezed, family);
1161    if after + 2 >= before {
1162        return None;
1163    }
1164    Some(lean_ctx::core::protocol::append_savings_with_info(
1165        &squeezed,
1166        before,
1167        after,
1168        Some("research"),
1169        None,
1170    ))
1171}
1172
1173/// Choose the prose-squeeze body. Only when the content would actually be
1174/// TRUNCATED (over the cap) do we upgrade from FIFO prefix truncation to
1175/// extractive centrality ranking — which keeps the most representative sentences
1176/// instead of just the first ones — via the cache-safe, memoized wire squeeze
1177/// ([`crate::prose_ranker`]), so the cold→warm engine transition never
1178/// changes a frozen-region rewrite (#448/#498). Below the cap the squeeze is a
1179/// lossless dedup pass, so the cheaper truncating squeeze is used.
1180fn squeeze_research_prose_body(content: &str) -> String {
1181    let cap = research_prose_cap();
1182    if content.len() > cap {
1183        return super::prose_ranker::squeeze(content, cap);
1184    }
1185    distill::squeeze_prose(content, cap)
1186}
1187
1188/// True when `name` refers to one of lean-ctx's own `ctx_*` MCP tools, whose
1189/// results are already compressed at the tool boundary and must not be touched
1190/// again by the proxy (#479).
1191///
1192/// Clients namespace MCP tools differently, so a plain `starts_with("ctx_")`
1193/// misses the real-world callers: Claude Code (the reporter's setup) sends
1194/// `mcp__lean-ctx__ctx_shell`, others use `lean-ctx:ctx_read`. Strip the client
1195/// prefix down to the bare tool segment before matching.
1196fn is_lean_ctx_tool(name: &str) -> bool {
1197    bare_tool_name(name).starts_with("ctx_") || name.starts_with("ctx_")
1198}
1199
1200/// The tool segment of a name a client namespaced: what follows the last
1201/// `__` and, in that, the last `:`, `/` or `.`.
1202pub(crate) fn bare_tool_name(name: &str) -> &str {
1203    name.rsplit("__")
1204        .next()
1205        .unwrap_or(name)
1206        .rsplit([':', '/', '.'])
1207        .next()
1208        .unwrap_or(name)
1209}
1210
1211/// Whether `name` — a tool name as a host listed it — is the Engine's expand
1212/// tool under a name a recovery stub can carry: the bare segment is
1213/// `ctx_expand` (the stripping of [`is_lean_ctx_tool`]) and the whole name
1214/// is at most 128 characters of `[A-Za-z0-9_.:/-]`, so it cannot break the
1215/// one-line grammar of the stub. Anything else is not the tool.
1216#[cfg(feature = "http-server")]
1217pub(crate) fn expand_tool_name(name: &str) -> bool {
1218    bare_tool_name(name) == EXPAND_TOOL
1219        && name.len() <= 128
1220        && name
1221            .bytes()
1222            .all(|byte| byte.is_ascii_alphanumeric() || b"_.:/-".contains(&byte))
1223}
1224
1225fn infer_command(content: &str, tool_name: Option<&str>) -> String {
1226    if let Some(cmd) = extract_command_hint(content) {
1227        return cmd;
1228    }
1229
1230    if let Some(name) = tool_name {
1231        let nl = name.to_lowercase();
1232        if nl.contains("bash") || nl.contains("shell") || nl.contains("terminal") {
1233            return "shell".to_string();
1234        }
1235        if nl.contains("search") || nl.contains("grep") || nl.contains("find") {
1236            return "grep".to_string();
1237        }
1238    }
1239
1240    String::new()
1241}
1242
1243fn extract_command_hint(content: &str) -> Option<String> {
1244    for line in content.lines().take(3) {
1245        let trimmed = line.trim();
1246        if let Some(cmd) = trimmed.strip_prefix("$ ") {
1247            return Some(cmd.to_string());
1248        }
1249        if let Some(cmd) = trimmed.strip_prefix("% ") {
1250            return Some(cmd.to_string());
1251        }
1252    }
1253    None
1254}
1255
1256#[cfg(test)]
1257#[path = "compress_tests.rs"]
1258mod tests;
1259
1260#[cfg(all(test, feature = "http-server"))]
1261#[path = "compress_recovery_tests.rs"]
1262mod recovery_tests;