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