Skip to main content

lean_ctx/proxy/
compress.rs

1use std::cell::RefCell;
2use std::collections::BTreeMap;
3
4use super::ccr;
5use super::prose_compress::compress_prose;
6use crate::core::archive::{RecoveryId, RecoveryRefusal, delivered};
7use crate::core::tokens::{COUNTING_FAMILY, TokenizerFamily, count_tokens_for};
8use crate::core::web::distill;
9
10#[path = "compress_gate.rs"]
11pub(crate) mod gate;
12
13/// Byte-ish budget for the research-prose squeeze (~5k tokens on English prose).
14/// Only oversized prose is truncated; the squeeze's main job is dedup + blank-collapse,
15/// not cutting.
16const RESEARCH_PROSE_CAP: usize = 20_000;
17const RESEARCH_PROSE_CAP_ENV: &str = "LEAN_CTX_RESEARCH_PROSE_CAP";
18
19fn research_prose_cap() -> usize {
20    std::env::var(RESEARCH_PROSE_CAP_ENV)
21        .ok()
22        .and_then(|v| v.trim().parse::<usize>().ok())
23        .filter(|cap| *cap > 0)
24        .unwrap_or(RESEARCH_PROSE_CAP)
25}
26
27/// Proxy compression funnel: routes a tool result to the right compressor.
28///
29/// 1. Already-cited research output (from `ctx_url_read` / the web layer) is kept
30///    verbatim — it is distilled and citation-stamped, so the shell pipeline must
31///    not touch its footer or claim markers.
32/// 2. Prose results (web fetches, doc reads, research MCP bridges) are squeezed
33///    by the prose-aware research compressor instead of the log/code-tuned shell
34///    engine.
35/// 3. Everything else (shell/build/search output) flows through the unified
36///    `compress_if_beneficial` pipeline. A `$ ...` command hint is extracted so
37///    the pattern engine gets the same routing as the CLI and MCP paths.
38pub fn compress_tool_result(content: &str, tool_name: Option<&str>) -> String {
39    compress_tool_result_for(content, tool_name, COUNTING_FAMILY)
40}
41
42/// Compresses a tool result under a task-aware policy.
43pub fn compress_tool_result_with_policy(
44    content: &str,
45    tool_name: Option<&str>,
46    policy: crate::proxy::adaptive_policy::CompressionPolicy,
47) -> String {
48    if !policy.compress_tool_output || policy.log_compression_level == 0 {
49        return content.to_owned();
50    }
51    if policy.code_preserve && looks_like_code(content) {
52        return content.to_owned();
53    }
54    compress_tool_result(content, tool_name)
55}
56
57/// Gateway variant of [`compress_tool_result_with_policy`].
58pub fn compress_tool_result_gateway_with_policy(
59    content: &str,
60    tool_name: Option<&str>,
61    family: TokenizerFamily,
62    policy: crate::proxy::adaptive_policy::CompressionPolicy,
63) -> String {
64    if !policy.compress_tool_output || policy.log_compression_level == 0 {
65        return content.to_owned();
66    }
67    if policy.code_preserve && looks_like_code(content) {
68        return content.to_owned();
69    }
70    compress_tool_result_gateway_for(content, tool_name, family)
71}
72
73fn looks_like_code(content: &str) -> bool {
74    content.lines().any(|line| {
75        let line = line.trim_start();
76        ["fn ", "struct ", "class ", "function ", "def ", "impl "]
77            .iter()
78            .any(|p| line.starts_with(p))
79            || line.contains('{')
80                && line.contains('}')
81                && (line.contains(';') || line.contains("=>"))
82    })
83}
84
85pub fn compress_tool_result_for(
86    content: &str,
87    tool_name: Option<&str>,
88    family: TokenizerFamily,
89) -> String {
90    if carries_recovery_stub(content) {
91        return content.to_owned();
92    }
93    let compressed = compress_inner(content, tool_name, family);
94    attach_ccr(content, compressed, CcrAudience::Local)
95}
96
97/// Shape the output of a host-native shell command whose exact command line is
98/// known (`ctx_shape`, fed by a host mod after the native tool ran). Unlike the
99/// wire funnel, the real command reaches the engine, so its command-gated
100/// policies (protected/verbatim commands, build/test guards, per-tool patterns)
101/// apply exactly as for `ctx_shell`. With a known `exit_code` the outcome-aware
102/// path runs (success compresses, failure keeps its diagnostics); without one
103/// the engine's unknown-outcome guard applies. Lossy results carry the same
104/// deterministic CCR recovery handle (#482, #498).
105///
106/// The same rules as the wire funnel hold: an output that already ends with
107/// its way back is returned whole, and every shorter form leaves through
108/// `attach_ccr` — under protection only with a recovery copy bound to the
109/// output's lineage, otherwise whole and noted with its code.
110///
111/// This route is no request: it holds no tool list of the host that will
112/// read the result. It therefore runs as a pass that knows no expand tool
113/// (`sticky_tools::in_pass`) instead of outside any pass, where the bare
114/// name `ctx_expand` would stand in. Under protection no stub is issued
115/// then: the output stays whole with `recovery.handle_not_followable`, and
116/// nothing is stored. Unprotected, the Community tee handle is unchanged.
117pub fn shape_command_output(command: &str, output: &str, exit_code: Option<i32>) -> String {
118    if output.trim().is_empty() || output.len() < 200 {
119        return output.to_string();
120    }
121    if carries_recovery_stub(output) {
122        return output.to_string();
123    }
124    let compressed = match exit_code {
125        Some(code) => crate::shell::compress::engine::compress_for_outcome(command, output, code),
126        None => crate::shell::compress::engine::compress_if_beneficial_pub(command, output),
127    };
128    super::sticky_tools::in_pass(|| attach_ccr(output, compressed, CcrAudience::Local))
129}
130
131/// [`compress_tool_result`] for a caller that is no request of this proxy:
132/// the output of a host-native tool handed in after it ran (`ctx_shape`,
133/// every tool whose command line is not known).
134///
135/// Such a caller holds no tool list of the host that will read the result,
136/// so no expand tool is known to be followable there. The compression runs
137/// as a pass that knows no tool (`sticky_tools::in_pass`), never outside any
138/// pass, where the bare name `ctx_expand` would stand in. Under protection
139/// no stub is issued then: the text stays whole with
140/// `recovery.handle_not_followable`, and nothing is stored. Unprotected, the
141/// result and its Community tee handle are those of [`compress_tool_result`].
142pub fn shape_tool_output(output: &str, tool_name: Option<&str>) -> String {
143    super::sticky_tools::in_pass(|| compress_tool_result(output, tool_name))
144}
145
146/// [`compress_tool_result`] for the `/v1/compress` gateway contract (#702):
147/// identical compression, but a lossy result advertises its retrieval hash in
148/// LiteLLM's regex-locked `hash=<24hex>` form, so a gateway running the
149/// headroom-guardrail CCR loop (BerriAI/litellm#31681) can inject its retrieve
150/// tool and resolve the original via `GET /v1/retrieve/{hash}`.
151///
152/// Any ambient savings footer is stripped *before* the marker is attached:
153/// savings figures belong in the caller's structured `stats` (#498), while the
154/// marker is functional content that must survive as the last line.
155pub fn compress_tool_result_gateway(content: &str, tool_name: Option<&str>) -> String {
156    compress_tool_result_gateway_for(content, tool_name, COUNTING_FAMILY)
157}
158
159pub fn compress_tool_result_gateway_for(
160    content: &str,
161    tool_name: Option<&str>,
162    family: TokenizerFamily,
163) -> String {
164    // Before the footer strip below: a local stub has the footer's shape.
165    if carries_recovery_stub(content) {
166        return content.to_owned();
167    }
168    let compressed = compress_inner(content, tool_name, family);
169    let clean = crate::core::protocol::strip_trailing_savings_footer(&compressed).to_string();
170    attach_ccr(content, clean, CcrAudience::Gateway)
171}
172
173/// Who reads a CCR stub: a local agent (path handle / in-band marker) or a
174/// remote gateway whose agentic loop scans for `hash=<24hex>` (#702).
175#[derive(Clone, Copy, PartialEq)]
176enum CcrAudience {
177    Local,
178    Gateway,
179}
180
181/// Who reads what a compression pass sends, as the route that runs the pass
182/// knows it ([`observing`]).
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub(crate) enum Reader {
185    /// A model behind a provider: it can call `ctx_expand`, never a route of
186    /// this proxy.
187    #[cfg(feature = "http-server")]
188    Model,
189    /// The caller of `/v1/compress`: it can call this proxy's routes.
190    GatewayCaller,
191}
192
193/// The blocks a compression pass left whole under protection because no
194/// recovery copy could back a shorter form, and why. Content-free towards
195/// every reader: a block is held by its digest only to count it once, and
196/// only codes and counts leave this type.
197#[derive(Debug, Default, Clone, PartialEq, Eq)]
198pub(crate) struct KeptWhole {
199    blocks: BTreeMap<[u8; 32], &'static str>,
200}
201
202impl KeptWhole {
203    /// The first code noted for a block stands: a later pass over the same
204    /// bytes does not count it again.
205    fn note(&mut self, block: &str, code: &'static str) {
206        self.blocks
207            .entry(*blake3::hash(block.as_bytes()).as_bytes())
208            .or_insert(code);
209    }
210
211    #[cfg(feature = "http-server")]
212    pub(crate) fn merge(&mut self, other: Self) {
213        for (block, code) in other.blocks {
214            self.blocks.entry(block).or_insert(code);
215        }
216    }
217
218    #[cfg(feature = "http-server")]
219    pub(crate) fn is_empty(&self) -> bool {
220        self.blocks.is_empty()
221    }
222
223    /// Blocks per code, in code order.
224    #[cfg(feature = "http-server")]
225    pub(crate) fn counts(&self) -> BTreeMap<&'static str, usize> {
226        let mut counts = BTreeMap::new();
227        for code in self.blocks.values() {
228            *counts.entry(*code).or_insert(0) += 1;
229        }
230        counts
231    }
232
233    /// The distinct codes, comma-separated in code order — the value of the
234    /// `x-leanctx-reason-codes` header of a reply that was NOT refused.
235    /// `None`: nothing stayed whole for want of a recovery copy.
236    #[cfg(feature = "http-server")]
237    pub(crate) fn codes(&self) -> Option<String> {
238        let counts = self.counts();
239        (!counts.is_empty()).then(|| counts.keys().copied().collect::<Vec<_>>().join(","))
240    }
241
242    /// `code=count` pairs for a log line.
243    #[cfg(feature = "http-server")]
244    pub(crate) fn summary(&self) -> String {
245        self.counts()
246            .iter()
247            .map(|(code, count)| format!("{code}={count}"))
248            .collect::<Vec<_>>()
249            .join(", ")
250    }
251}
252
253struct Observation {
254    reader: Reader,
255    kept: KeptWhole,
256}
257
258thread_local! {
259    /// The compression pass running on this thread, if a route observes it.
260    /// Compression is synchronous from the route down to [`attach_ccr`].
261    static OBSERVATION: RefCell<Option<Observation>> = const { RefCell::new(None) };
262}
263
264/// Run one synchronous compression pass for `reader` and return, next to its
265/// result, the blocks it left whole under protection. An inner pass reports
266/// to its own caller only.
267#[cfg(feature = "http-server")]
268pub(crate) fn observing<T>(reader: Reader, compression: impl FnOnce() -> T) -> (T, KeptWhole) {
269    struct Restore(Option<Observation>);
270    impl Drop for Restore {
271        fn drop(&mut self) {
272            let outer = self.0.take();
273            OBSERVATION.with(|slot| *slot.borrow_mut() = outer);
274        }
275    }
276    let restore = Restore(OBSERVATION.with(|slot| {
277        slot.replace(Some(Observation {
278            reader,
279            kept: KeptWhole::default(),
280        }))
281    }));
282    let result = compression();
283    let kept = OBSERVATION
284        .with(|slot| slot.borrow_mut().take())
285        .map_or_else(KeptWhole::default, |observation| observation.kept);
286    drop(restore);
287    (result, kept)
288}
289
290/// The reader of the pass running on this thread; `None` outside a route.
291fn observed_reader() -> Option<Reader> {
292    OBSERVATION.with(|slot| slot.borrow().as_ref().map(|observation| observation.reader))
293}
294
295/// `block` stays whole under protection for the content-free reason `code`.
296/// Counted for the route that observes the pass; logged otherwise.
297pub(crate) fn note_kept_whole(block: &str, code: &'static str) {
298    OBSERVATION.with(|slot| {
299        if let Some(observation) = slot.borrow_mut().as_mut() {
300            observation.kept.note(block, code);
301        } else {
302            tracing::debug!("lean-ctx proxy: block kept whole, no recovery copy ({code})");
303        }
304    });
305}
306
307/// Whether nothing may be shortened without a recovery copy bound to its
308/// lineage: a policy pack, governed or sovereign mode, or an unloadable
309/// configuration.
310pub(crate) fn protected() -> bool {
311    crate::core::context_admission::stored::source_authority_required()
312}
313
314/// How a lineage-bound recovery stub opens. Deliberately not the
315/// savings-footer shape (`[lean-ctx: `): a footer strip must never eat it.
316///
317/// The grammar of the stub, stated once: one line,
318/// `[lean-ctx recovery: full original archived — <tool>(id="<64 hex>",
319/// head=N|search="…"|json_path="…") for a slice]`. `<tool>` is the Engine's
320/// expand tool under the name the host of the request registered it with
321/// ([`expand_tool_name`]: at most 128 characters of `[A-Za-z0-9_.:/-]`), so
322/// it can hold neither `]` nor a line break. Everything that recognises a
323/// stub ([`carries_recovery_stub`]) reads the fixed opening and the closing
324/// bracket only, whatever the tool is called.
325const RECOVERY_STUB_OPEN: &str = "[lean-ctx recovery: ";
326
327/// The Engine tool that resolves a recovery id, by its bare name.
328const EXPAND_TOOL: &str = "ctx_expand";
329
330/// The last line of a block that was compressed under protection, for a
331/// model: `tool` — the Engine's expand tool as the host registered it —
332/// resolves the 64-hex `id` under the authority that holds then. A pure
333/// function of the name and the id, so the block stays byte-stable while the
334/// host keeps the name.
335pub(crate) fn recovery_stub_for(tool: &str, id: &RecoveryId) -> String {
336    format!(
337        "{RECOVERY_STUB_OPEN}full original archived — \
338         {tool}(id=\"{}\", head=N|search=\"…\"|json_path=\"…\") for a slice]",
339        id.as_str()
340    )
341}
342
343/// [`recovery_stub_for`] with the tool's bare name.
344#[cfg(test)]
345pub(crate) fn recovery_stub(id: &RecoveryId) -> String {
346    recovery_stub_for(EXPAND_TOOL, id)
347}
348
349/// [`recovery_stub_for`] for the caller of `/v1/compress`, which can follow a
350/// route of this proxy. No `hash=`: the id is not a tee hash, and a LiteLLM
351/// guardrail must not send it to `/v1/retrieve`.
352fn reference_stub(id: &RecoveryId) -> String {
353    format!(
354        "[lean-ctx CCR: full original archived — GET /v1/references/{} on this gateway \
355         returns it while its sources are admitted]",
356        id.as_str()
357    )
358}
359
360/// Upper bound of the length in bytes of a stub with the bare tool name: a
361/// shrink below it gains nothing. A stub with a longer, prefixed name is
362/// caught where it is attached — a block that would not get shorter with its
363/// stub stays as it is.
364const STUB_MAX_BYTES: usize = 256;
365
366/// Text that already ends with a way back to its original. A second pass
367/// passes it through: compressing it again could drop the handle, and the
368/// local stubs have the shape of a savings footer the gateway funnel strips.
369fn carries_recovery_stub(content: &str) -> bool {
370    let last = content
371        .trim_end_matches('\n')
372        .rsplit('\n')
373        .next()
374        .unwrap_or_default();
375    last.ends_with(']')
376        && [
377            RECOVERY_STUB_OPEN,
378            "[lean-ctx CCR: full original ",
379            "[lean-ctx: full original ",
380        ]
381        .iter()
382        .any(|open| last.starts_with(open))
383}
384
385/// Make a live-compressed `tool_result` non-lossy (#482): when compression
386/// removed a meaningful amount, tee the verbatim original to the shared
387/// content-addressed store and append a deterministic recovery handle. The
388/// handle is a pure function of the content hash, so the rewritten result is
389/// byte-stable across turns and never invalidates the provider cache prefix
390/// (#448). Passthrough / verbatim results (no real shrink) keep their bytes.
391/// When no recovery copy can be written (an active policy keeps no originless
392/// copies, or the store fails) the original is returned instead of the lossy
393/// form: a fresh result is never shortened without a way back.
394fn attach_ccr(original: &str, result: String, audience: CcrAudience) -> String {
395    use super::sticky_tools;
396    if result == original {
397        return result;
398    }
399    let shrink = original.len().saturating_sub(result.len());
400    if original.len() < ccr::MIN_TEE_BYTES || shrink < ccr::MIN_TEE_BYTES {
401        // Too small for a tee: unprotected, the result leaves as it is.
402        if !protected() {
403            return result;
404        }
405        // Under protection a changed block leaves only with the stub of a
406        // recovery copy. Where the stub costs more than this pass saved,
407        // nothing is gained and nothing is changed — not a refusal, no code.
408        if shrink <= STUB_MAX_BYTES {
409            return original.to_string();
410        }
411    }
412    // The gateway funnel on a route whose reader is a model (the forward
413    // pipeline) or is unknown: neither the tee hash nor a proxy route is a
414    // way back that reader can follow. Neither is a stub naming a tool the
415    // host of this request did not list itself, or — under protection — a
416    // stub for a block whose own tool call is not on record in this store
417    // as answered by an Engine of this store (`sticky_tools::expand_tool_for`
418    // states the whole decision). Decided before anything is stored.
419    let tool = (audience == CcrAudience::Local)
420        .then(|| sticky_tools::expand_tool_for(original))
421        .flatten();
422    let followable =
423        tool.is_some() || observed_reader() == Some(Reader::GatewayCaller) || !protected();
424    if !followable {
425        note_kept_whole(original, HANDLE_NOT_FOLLOWABLE);
426        return original.to_string();
427    }
428    match recovery_copy(original) {
429        Some(RecoveryCopy::Bound {
430            id,
431            lineage,
432            project,
433        }) => {
434            let stub = if audience == CcrAudience::Local {
435                recovery_stub_for(tool.as_deref().unwrap_or(EXPAND_TOOL), &id)
436            } else {
437                reference_stub(&id)
438            };
439            let sent = format!("{result}\n{stub}");
440            if sent.len() >= original.len() {
441                return original.to_string();
442            }
443            // The one record a site other than an Engine release point makes
444            // (`delivered::record_derived`). Guaranteed here:
445            // 1. `lineage` came from `lineage_of` for exactly `original`, in
446            //    this request, inside the same project scope (`bound_copy`);
447            // 2. `sent` derives from `original` alone: `result` is the
448            //    compressor's output for that one block, and the rest is the
449            //    fixed stub text with the id of its recovery copy;
450            // 3. no second block takes part, so there is nothing to join —
451            //    a block without a lineage never reaches this arm.
452            let recorded = super::request_project::in_project(&project, || {
453                delivered::record_derived(&delivered::digest(&sent), &lineage)
454            });
455            if recorded {
456                // The model's stub names the expand tool the host listed:
457                // the request's pass holds the stubbed block next to its
458                // original until the request has left (`gate::Issued`). The
459                // gateway caller's stub names a route, not a tool.
460                if audience == CcrAudience::Local {
461                    gate::note_issued(original, &sent);
462                }
463                sent
464            } else {
465                // The shortened block would be of unknown lineage for every
466                // later turn; the original is not.
467                note_kept_whole(original, DERIVED_NOT_RECORDED);
468                original.to_string()
469            }
470        }
471        // Gateway (#702): the reader is a model behind a LiteLLM-style gateway.
472        // A local path is useless there; advertise the 24-hex retrieval hash in
473        // the exact shape the guardrail's marker regex captures. The hash is a
474        // pure function of the content, so the stub stays byte-stable (#498).
475        // The `[lean-ctx CCR:` prefix is deliberately NOT the savings-footer
476        // shape (`[lean-ctx: `): this line is functional content — a footer
477        // strip must never eat it.
478        Some(RecoveryCopy::Tee(handle)) if audience == CcrAudience::Gateway => {
479            sticky_tools::mark_ccr_active(0);
480            let hash = ccr::litellm_hash(original);
481            format!(
482                "{result}\n[lean-ctx CCR: full original elided to save tokens — call the \
483                 retrieve tool with hash={hash}, or read {handle} locally]"
484            )
485        }
486        Some(RecoveryCopy::Tee(handle)) => {
487            sticky_tools::mark_ccr_active(0);
488            match ccr::inband_locator(&handle) {
489                Some(marker) => format!(
490                    "{result}\n[lean-ctx: full original elided to save tokens — echo {marker} \
491                     on your next turn to get the verbatim original spliced back inline]"
492                ),
493                None => format!(
494                    "{result}\n[lean-ctx: full original at {handle} — read it directly (no MCP), or \
495                     ctx_expand(id=\"{handle}\", head=N|search=\"…\"|json_path=\"…\") for a slice]"
496                ),
497            }
498        }
499        None => original.to_string(),
500    }
501}
502
503/// The one place a compressed result gets its way back: store a recovery
504/// copy of `original` and return its handle, or `None` when no copy may
505/// exist — in which case the caller forwards the original instead of the
506/// lossy form.
507///
508/// - Unprotected (Community, developer mode): the originless tee store, as
509///   before.
510/// - Protected (a policy pack, governed or sovereign mode, an unloadable
511///   configuration): a copy exists only for a block whose sources are known
512///   ([`bound_copy`]). The proxy only sees a request body and observed no
513///   read; permission to read is not permission to retain. Without a known,
514///   currently admitted lineage there is no copy and the caller keeps the
515///   original.
516fn recovery_copy(original: &str) -> Option<RecoveryCopy> {
517    if !crate::core::context_admission::stored::source_authority_required() {
518        return ccr::persist(original).map(RecoveryCopy::Tee);
519    }
520    match bound_copy(original) {
521        Ok(copy) => Some(copy),
522        Err(code) => {
523            note_kept_whole(original, code);
524            None
525        }
526    }
527}
528
529/// The gate of every transformation other than the compressor that replaces
530/// a block by a shorter form under protection (history pruning, truncation):
531/// `shortened` followed by the stub of a recovery copy of `original`, on
532/// record under the original's lineage — or `None`, and the caller keeps
533/// `original` whole. `None` is noted with its code, except where the form
534/// with its stub would not be shorter at all.
535pub(crate) fn shorten_with_copy(original: &str, shortened: &str) -> Option<String> {
536    // Decided before anything is stored: a request whose host did not list
537    // the expand tool itself hands out no stub that names it, and under
538    // protection neither does text that is not one tool-result block whose
539    // call this store's Engine answered (`sticky_tools::expand_tool_for`).
540    let Some(tool) = super::sticky_tools::expand_tool_for(original) else {
541        note_kept_whole(original, HANDLE_NOT_FOLLOWABLE);
542        return None;
543    };
544    let copy = match bound_copy(original) {
545        Ok(copy) => copy,
546        Err(code) => {
547            note_kept_whole(original, code);
548            return None;
549        }
550    };
551    let RecoveryCopy::Bound {
552        id,
553        lineage,
554        project,
555    } = copy
556    else {
557        return None;
558    };
559    let sent = format!("{shortened}\n{}", recovery_stub_for(&tool, &id));
560    if sent.len() >= original.len() {
561        return None;
562    }
563    // `record_derived`, as in `attach_ccr`: the lineage is that of exactly
564    // `original`, looked up in this request and scope; `sent` is a cut of
565    // that one block plus fixed text of the cutting code and the stub.
566    let recorded = super::request_project::in_project(&project, || {
567        delivered::record_derived(&delivered::digest(&sent), &lineage)
568    });
569    if recorded {
570        // This stub names the host's expand tool as well (see `attach_ccr`).
571        gate::note_issued(original, &sent);
572        Some(sent)
573    } else {
574        note_kept_whole(original, DERIVED_NOT_RECORDED);
575        None
576    }
577}
578
579/// A block that an earlier request already carried may not be replaced by a
580/// pointer to that request: nothing in THIS request holds its content.
581pub(crate) const DEDUP_WITHOUT_COPY: &str = "recovery.dedup_without_copy";
582/// The conversation may not be replaced by a summary: no copy backs it.
583#[cfg(feature = "http-server")]
584pub(crate) const SUMMARY_WITHOUT_COPY: &str = "recovery.summary_without_copy";
585
586/// The reader of this pass cannot follow any handle a copy would have.
587const HANDLE_NOT_FOLLOWABLE: &str = "recovery.handle_not_followable";
588/// The copy exists, but the shortened block could not be put on record
589/// under the lineage of its original.
590const DERIVED_NOT_RECORDED: &str = "recovery.derived_not_recorded";
591/// No project of the proxy that sources could be admitted for.
592const NO_PROJECT: &str = "recovery.no_project";
593/// The block is not text the Engine delivered with a complete lineage.
594const UNKNOWN_LINEAGE: &str = "recovery.unknown_lineage";
595
596/// The recovery copy of `original` under protection, or the content-free
597/// code of why there is none. Inside the scope of the proxy's own project
598/// (operator configuration, `request_project`): the Engine's lineage of
599/// exactly this text, and a copy stored under it — which the store accepts
600/// only while every source of that lineage is admitted now. A file-only
601/// lineage lands on the Engine's existing source-bound archive entry for the
602/// same text, so no second copy is written.
603fn bound_copy(original: &str) -> Result<RecoveryCopy, &'static str> {
604    let project = super::request_project::current_source_project().ok_or(NO_PROJECT)?;
605    super::request_project::in_project(&project, || {
606        let lineage = delivered::lineage_of(&delivered::digest(original))
607            .filter(delivered::Lineage::is_complete)
608            .ok_or(UNKNOWN_LINEAGE)?;
609        let id = crate::core::archive::store_recovery_with_lineage(original, &lineage)
610            .map_err(recovery_code)?;
611        Ok((id, lineage))
612    })
613    .map(|(id, lineage)| RecoveryCopy::Bound {
614        id,
615        lineage: Box::new(lineage),
616        project,
617    })
618}
619
620/// The content-free code of a recovery refusal.
621pub(crate) fn recovery_code(refusal: RecoveryRefusal) -> &'static str {
622    match refusal {
623        RecoveryRefusal::UnknownLineage => UNKNOWN_LINEAGE,
624        RecoveryRefusal::SourceNotPresented => "recovery.source_not_presented",
625        RecoveryRefusal::SourceNoLongerAdmitted => "recovery.source_no_longer_admitted",
626        RecoveryRefusal::NotStorable => "recovery.not_storable",
627        RecoveryRefusal::Missing => "recovery.missing",
628    }
629}
630
631/// Resolve a recovery id under the authority that holds now, for the proxy's
632/// own project. `None`: `id` is not a recovery id at all. Without a project
633/// nothing is looked up.
634#[cfg(feature = "http-server")]
635pub(crate) fn resolve_recovery(id: &str) -> Option<Result<String, &'static str>> {
636    let id = RecoveryId::parse(id)?;
637    let Some(project) = super::request_project::current_source_project() else {
638        // Unprotected deployments hold no recovery copies: not a recovery id.
639        return crate::core::context_admission::stored::source_authority_required()
640            .then_some(Err(NO_PROJECT));
641    };
642    Some(super::request_project::in_project(&project, || {
643        crate::core::archive::retrieve_recovery_checked(&id).map_err(recovery_code)
644    }))
645}
646
647/// Where the way back of a compressed result leads.
648enum RecoveryCopy {
649    /// A tee file of the originless store; the value is its handle.
650    Tee(String),
651    /// A copy in the Engine's archive, bound to the lineage of the original
652    /// and stored for `project`.
653    Bound {
654        id: RecoveryId,
655        lineage: Box<delivered::Lineage>,
656        project: std::path::PathBuf,
657    },
658}
659
660fn compress_inner(content: &str, tool_name: Option<&str>, family: TokenizerFamily) -> String {
661    if content.trim().is_empty() || content.len() < 200 {
662        return content.to_string();
663    }
664
665    // #479: lean-ctx's own MCP tools already applied their compression policy at
666    // the tool boundary — honouring `raw=true`/`bypass`, `<lc_safe>` spans and
667    // the configured aggressiveness. Their `raw` intent lives in the originating
668    // `tool_use` input, which is invisible here, so re-compressing on the wire
669    // would silently undo an explicit `raw=true` and double-compress everything
670    // else. Pass results from `ctx_*` tools through untouched.
671    if tool_name.is_some_and(is_lean_ctx_tool) {
672        return content.to_string();
673    }
674
675    // #709: honour explicit <lc_safe>…</lc_safe> spans on the proxy path too.
676    // Protected spans pass through verbatim; each unprotected segment flows back
677    // through the normal funnel (markers are stripped, so this never recurses).
678    if crate::core::protect::has_markers(content) {
679        return crate::core::protect::compress_preserving(content, |seg| {
680            compress_inner(seg, tool_name, family)
681        });
682    }
683
684    if is_cited_research_output(content) {
685        if looks_like_markdown(content) {
686            let prose = compress_prose(content, None);
687            if prose.compressed_tokens < prose.original_tokens {
688                return prose.compressed;
689            }
690        }
691        return content.to_string();
692    }
693
694    if extract_command_hint(content).is_none()
695        && looks_like_prose(content)
696        && let Some(out) = squeeze_research_prose(content, family)
697    {
698        return out;
699    }
700
701    let cmd = infer_command(content, tool_name);
702
703    // Proxy fidelity guard. A foreign shell tool gives us at most a generic
704    // command (`"shell"`) or none, so the engine's command-gated build/test
705    // verbatim guards never fire. When the *output* is unmistakably a build or
706    // test run, preserve it verbatim (bounded by safety-line-preserving
707    // truncation) so compiler errors, panics and test summaries reach the model
708    // intact — the exact signal a bug-fix task depends on.
709    let generic_command = cmd.is_empty() || cmd == "shell";
710    if generic_command
711        && (output_looks_like_test_run(content) || output_looks_like_build_failure(content))
712    {
713        return crate::shell::compress::engine::preserve_verbatim_pub_for(content, family);
714    }
715
716    crate::shell::compress::engine::compress_if_beneficial_for(&cmd, content, family)
717}
718
719/// Strong, ecosystem-spanning signals that an output is a *test run* (passing or
720/// failing). Conservative — matches the summary/result lines a bug-fix task must
721/// never lose. Only consulted on the proxy path when the real command is unknown.
722fn output_looks_like_test_run(content: &str) -> bool {
723    const NEEDLES: &[&str] = &[
724        "test result:",            // rust
725        "short test summary info", // pytest
726        " passed in ",             // pytest summary
727        " failed in ",             // pytest summary
728        "=== RUN",                 // go
729        "--- FAIL:",               // go
730        "--- PASS:",               // go
731        "Test Suites:",            // jest
732        " examples, ",             // rspec ("5 examples, 0 failures")
733        "FAILED",                  // generic test failure marker
734    ];
735    NEEDLES.iter().any(|n| content.contains(n))
736}
737
738/// Strong, specific signals of a build / compile / runtime failure across the
739/// major toolchains. Used only on the proxy path for generically-named tools so
740/// the failing diagnostics (paths, lines, messages) survive intact.
741fn output_looks_like_build_failure(content: &str) -> bool {
742    const NEEDLES: &[&str] = &[
743        "error[",                            // rustc (E0277 …)
744        ": error:",                          // gcc / clang "file.c:12:5: error:"
745        "fatal error:",                      // gcc / clang
746        "undefined reference to",            // linker
747        "panicked at",                       // rust runtime
748        "could not compile",                 // cargo
749        "Traceback (most recent call last)", // python
750        "AssertionError",                    // python / junit
751        "make: ***",                         // make
752        "Build FAILED",
753        "BUILD FAILED",
754        "Segmentation fault",
755    ];
756    NEEDLES.iter().any(|n| content.contains(n))
757}
758
759/// True when `content` is a lean-ctx web read: distilled body + citation footer
760/// (`Source: …\nSite: … · Retrieved: …`). Such output is re-compression-hostile.
761fn is_cited_research_output(content: &str) -> bool {
762    content.contains("· Retrieved: ") && content.contains("\nSource: ")
763}
764
765/// Code/shell symbols whose density cleanly separates source/logs from prose.
766const CODE_SYMBOLS: &str = "{}<>;=|\\$`";
767
768/// Conservative prose detector: substantial, letter-dense, low code-symbol, with
769/// real sentences and long lines. Code, logs, tables and JSON all fail this.
770fn looks_like_prose(content: &str) -> bool {
771    let sample: String = content.chars().take(4000).collect();
772    let total = sample.chars().count();
773    if total < 600 {
774        return false;
775    }
776    let total_f = total as f32;
777    let alpha = sample.chars().filter(|c| c.is_alphabetic()).count() as f32;
778    let spaces = sample.chars().filter(|c| *c == ' ').count() as f32;
779    let symbols = sample.chars().filter(|c| CODE_SYMBOLS.contains(*c)).count() as f32;
780
781    if alpha / total_f < 0.6 || spaces / total_f < 0.12 || symbols / total_f > 0.06 {
782        return false;
783    }
784    if sample.matches(['.', '!', '?']).count() < 4 {
785        return false;
786    }
787
788    let non_empty: Vec<&str> = sample.lines().filter(|l| !l.trim().is_empty()).collect();
789    if non_empty.is_empty() {
790        return false;
791    }
792    let avg_len =
793        non_empty.iter().map(|l| l.chars().count()).sum::<usize>() as f32 / non_empty.len() as f32;
794    avg_len >= 40.0
795}
796
797fn looks_like_markdown(content: &str) -> bool {
798    content.lines().any(|line| {
799        let trimmed = line.trim_start();
800        trimmed.starts_with("# ")
801            || trimmed.starts_with("## ")
802            || trimmed.starts_with("```")
803            || trimmed.starts_with("~~~")
804            || matches!(trimmed.as_bytes(), [b'-' | b'*' | b'+', b' ', ..])
805            || trimmed.matches('|').count() >= 2
806    })
807}
808
809/// Apply the prose squeeze, returning a footer-stamped result only when it
810/// actually saves tokens; otherwise `None` so the normal pipeline can try.
811fn squeeze_research_prose(content: &str, family: TokenizerFamily) -> Option<String> {
812    let before = count_tokens_for(content, family);
813    let squeezed = squeeze_research_prose_body(content);
814    if squeezed.trim().is_empty() {
815        return None;
816    }
817    let after = count_tokens_for(&squeezed, family);
818    if after + 2 >= before {
819        return None;
820    }
821    Some(crate::core::protocol::append_savings_with_info(
822        &squeezed,
823        before,
824        after,
825        Some("research"),
826        None,
827    ))
828}
829
830/// Choose the prose-squeeze body. Only when the content would actually be
831/// TRUNCATED (over the cap) do we upgrade from FIFO prefix truncation to
832/// extractive centrality ranking — which keeps the most representative sentences
833/// instead of just the first ones — via the cache-safe, memoized wire squeeze
834/// ([`crate::proxy::prose_ranker`]), so the cold→warm engine transition never
835/// changes a frozen-region rewrite (#448/#498). Below the cap the squeeze is a
836/// lossless dedup pass, so the cheaper truncating squeeze is used.
837fn squeeze_research_prose_body(content: &str) -> String {
838    let cap = research_prose_cap();
839    if content.len() > cap {
840        return super::prose_ranker::squeeze(content, cap);
841    }
842    distill::squeeze_prose(content, cap)
843}
844
845/// True when `name` refers to one of lean-ctx's own `ctx_*` MCP tools, whose
846/// results are already compressed at the tool boundary and must not be touched
847/// again by the proxy (#479).
848///
849/// Clients namespace MCP tools differently, so a plain `starts_with("ctx_")`
850/// misses the real-world callers: Claude Code (the reporter's setup) sends
851/// `mcp__lean-ctx__ctx_shell`, others use `lean-ctx:ctx_read`. Strip the client
852/// prefix down to the bare tool segment before matching.
853fn is_lean_ctx_tool(name: &str) -> bool {
854    bare_tool_name(name).starts_with("ctx_") || name.starts_with("ctx_")
855}
856
857/// The tool segment of a name a client namespaced: what follows the last
858/// `__` and, in that, the last `:`, `/` or `.`.
859pub(crate) fn bare_tool_name(name: &str) -> &str {
860    name.rsplit("__")
861        .next()
862        .unwrap_or(name)
863        .rsplit([':', '/', '.'])
864        .next()
865        .unwrap_or(name)
866}
867
868/// Whether `name` — a tool name as a host listed it — is the Engine's expand
869/// tool under a name a recovery stub can carry: the bare segment is
870/// `ctx_expand` (the stripping of [`is_lean_ctx_tool`]) and the whole name
871/// is at most 128 characters of `[A-Za-z0-9_.:/-]`, so it cannot break the
872/// one-line grammar of the stub. Anything else is not the tool.
873#[cfg(feature = "http-server")]
874pub(crate) fn expand_tool_name(name: &str) -> bool {
875    bare_tool_name(name) == EXPAND_TOOL
876        && name.len() <= 128
877        && name
878            .bytes()
879            .all(|byte| byte.is_ascii_alphanumeric() || b"_.:/-".contains(&byte))
880}
881
882fn infer_command(content: &str, tool_name: Option<&str>) -> String {
883    if let Some(cmd) = extract_command_hint(content) {
884        return cmd;
885    }
886
887    if let Some(name) = tool_name {
888        let nl = name.to_lowercase();
889        if nl.contains("bash") || nl.contains("shell") || nl.contains("terminal") {
890            return "shell".to_string();
891        }
892        if nl.contains("search") || nl.contains("grep") || nl.contains("find") {
893            return "grep".to_string();
894        }
895    }
896
897    String::new()
898}
899
900fn extract_command_hint(content: &str) -> Option<String> {
901    for line in content.lines().take(3) {
902        let trimmed = line.trim();
903        if let Some(cmd) = trimmed.strip_prefix("$ ") {
904            return Some(cmd.to_string());
905        }
906        if let Some(cmd) = trimmed.strip_prefix("% ") {
907            return Some(cmd.to_string());
908        }
909    }
910    None
911}
912
913#[cfg(test)]
914#[path = "compress_tests.rs"]
915mod tests;
916
917#[cfg(test)]
918#[path = "compress_recovery_tests.rs"]
919mod recovery_tests;