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