Skip to main content

lean_ctx/tools/ctx_read/
mod.rs

1use std::path::Path;
2
3use crate::core::cache::SessionCache;
4use crate::core::compressor;
5use crate::core::deps;
6use crate::core::entropy;
7use crate::core::plugins::{PluginManager, executor::HookPoint};
8use crate::core::protocol;
9use crate::core::signatures;
10use crate::core::symbol_map::{self, SymbolMap};
11use crate::core::tokens::count_tokens;
12use crate::tools::CrpMode;
13// `pub(crate)`: the conformance suite renders modes directly for its
14// accuracy invariants (GL#441).
15pub(crate) mod render;
16pub(crate) use render::*;
17/// Type-safe read-mode vocabulary (#528): single source of truth for which
18/// modes exist and how each is classified.
19pub(crate) mod mode;
20pub(crate) use mode::ReadMode;
21#[cfg(test)]
22mod tests;
23
24/// Pre-counted read output carrying the output string, resolved mode,
25/// and token count computed during mode processing.
26pub struct ReadOutput {
27    pub content: String,
28    pub resolved_mode: String,
29    /// Approximate output token count from mode processing.
30    /// The dispatch layer recounts the final assembled string for accurate savings.
31    pub output_tokens: usize,
32}
33
34/// SSOT via [`ReadMode`] (#528): the `map`/`signatures` summaries whose rendered
35/// body is stored per-file in `compressed_outputs`. Unknown modes are not
36/// cacheable, matching the prior `["map","signatures"].contains(mode)`.
37fn is_cacheable_mode(mode: &str) -> bool {
38    mode.parse::<ReadMode>()
39        .is_ok_and(|m| m.is_compressed_cacheable())
40}
41
42/// `#361` anti-inflation capping applies to whole-file views (`full` and the
43/// lossy summaries `map`/`signatures`/`aggressive`/`entropy`/`task`/…), where the
44/// raw file is a strict superset of the information and is therefore never a
45/// worse answer when the framing happens to inflate on a small file. `full` is
46/// included: an `auto` read can resolve to `full` and reach this path, and its
47/// header must not push the cost above raw. Selection and delta views have
48/// view-specific semantics — `lines:` returns a window, `reference` a pointer,
49/// `diff` a delta, `raw` the bytes — so replacing them with the whole file would
50/// be wrong, not cheaper, and they are never capped.
51fn mode_allows_raw_cap(mode: &str) -> bool {
52    // SSOT via [`ReadMode`] (#528). Unknown modes keep the prior default of
53    // `true` (only `lines:`/`reference`/`diff`/`raw` opt out of the #361 cap).
54    mode.parse::<ReadMode>()
55        .map_or(true, |m| m.allows_raw_cap())
56}
57
58fn compressed_cache_key(
59    mode: &str,
60    crp_mode: CrpMode,
61    task: Option<&str>,
62    aggressiveness: Option<f64>,
63    protect: &[String],
64) -> String {
65    // Bump when the rendered map/signatures body changes shape so stale
66    // pre-line-range entries are not served from an older session cache.
67    let versioned_mode = match mode {
68        "map" => "map:v2",
69        "signatures" => "signatures:v2",
70        _ => mode,
71    };
72    let base = if crp_mode.is_tdd() {
73        format!("{versioned_mode}:tdd")
74    } else {
75        versioned_mode.to_string()
76    };
77    // map/signatures output now embeds a task-relevant body, so task-aware and
78    // task-free variants must cache under distinct keys.
79    let keyed = match task.map(str::trim).filter(|t| !t.is_empty()) {
80        Some(t) => {
81            use std::hash::{Hash, Hasher};
82            let mut h = std::collections::hash_map::DefaultHasher::new();
83            t.hash(&mut h);
84            format!("{base}:t{:x}", h.finish())
85        }
86        None => base,
87    };
88    // Aggressiveness and the explicit protect list both change lossy output, so
89    // both must change the key (#498). Empty fragments keep pre-feature keys
90    // byte-identical, so unmodified reads still hit their existing cache entries.
91    let mut key = keyed;
92    let aggr_frag = crate::core::aggressiveness::cache_fragment(aggressiveness);
93    if !aggr_frag.is_empty() {
94        key = format!("{key}:{aggr_frag}");
95    }
96    let protect_frag = crate::core::protect::protect_fragment(protect);
97    if !protect_frag.is_empty() {
98        key = format!("{key}:{protect_frag}");
99    }
100    key
101}
102
103/// Appends the reactive recovery footer to a compressed view, leading with the
104/// MCP-free "read the path directly" route. Tier (`off|minimal|full`) and wording
105/// are resolved centrally in [`crate::core::recovery`] so `ctx_read`, the shell
106/// tee and archive handles all speak the same grammar. Only lossy/compressed
107/// modes reach this helper, so the footer is naturally absent from `full`/`raw`.
108fn append_compressed_hint(output: &str, file_path: &str) -> String {
109    match crate::core::recovery::read_footer(file_path) {
110        Some(footer) => format!("{output}\n{footer}"),
111        None => output.to_string(),
112    }
113}
114
115/// Reads a file as UTF-8 with lossy fallback, enforcing binary detection and max read size limit.
116/// Defense-in-depth: verifies that the canonical path stays within the process's project root
117/// (if determinable) even though callers SHOULD have already jail-checked the path.
118pub fn read_file_lossy(path: &str) -> Result<String, std::io::Error> {
119    if crate::core::binary_detect::is_binary_file(path) {
120        let msg = crate::core::binary_detect::binary_file_message(path);
121        return Err(std::io::Error::other(msg));
122    }
123
124    {
125        let canonical =
126            crate::core::pathutil::safe_canonicalize_bounded(std::path::Path::new(path), 2000);
127        if let Ok(cwd) = std::env::current_dir() {
128            let root = crate::core::pathutil::safe_canonicalize_bounded(&cwd, 2000);
129            if !canonical.starts_with(&root) {
130                let allow = crate::core::pathjail::allow_paths_from_env_and_config();
131                let data_dir_ok = crate::core::data_dir::lean_ctx_data_dir()
132                    .is_ok_and(|d| canonical.starts_with(d));
133                let tmp_ok = canonical.starts_with(std::env::temp_dir());
134                if !allow.iter().any(|a| canonical.starts_with(a)) && !data_dir_ok && !tmp_ok {
135                    tracing::warn!(
136                        "defense-in-depth: path may escape project root: {}",
137                        canonical.display()
138                    );
139                }
140            }
141        }
142    }
143
144    let cap = crate::core::limits::max_read_bytes();
145
146    let file = open_with_retry(path)?;
147    let meta = file
148        .metadata()
149        .map_err(|e| std::io::Error::other(format!("cannot stat open file descriptor: {e}")))?;
150    if meta.len() > cap as u64 {
151        return Err(std::io::Error::other(format!(
152            "file too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
153             Increase the limit or use a line-range read: mode=\"lines:1-100\"",
154            meta.len(),
155            cap
156        )));
157    }
158
159    use std::io::Read;
160    let mut bytes = Vec::with_capacity(meta.len() as usize);
161    std::io::BufReader::new(file).read_to_end(&mut bytes)?;
162    let s = match String::from_utf8(bytes) {
163        Ok(s) => s,
164        Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
165    };
166    Ok(crate::core::io_boundary::strip_utf8_bom(s))
167}
168
169/// Opens a file, retrying once after a brief pause on NotFound.
170/// Works around overlay/FUSE stat-cache races in container runtimes (Docker, Codex).
171/// Uses O_NOFOLLOW on Unix for TOCTOU symlink protection.
172fn open_with_retry(path: &str) -> Result<std::fs::File, std::io::Error> {
173    match open_nofollow(path) {
174        Ok(f) => Ok(f),
175        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
176            std::thread::sleep(std::time::Duration::from_millis(50));
177            open_nofollow(path).map_err(|e| {
178                if e.kind() == std::io::ErrorKind::NotFound {
179                    std::io::Error::other(format!(
180                        "file not found: {path} — verify the path with ctx_tree or ctx_search"
181                    ))
182                } else {
183                    e
184                }
185            })
186        }
187        Err(e) => Err(e),
188    }
189}
190
191#[cfg(unix)]
192fn open_nofollow(path: &str) -> Result<std::fs::File, std::io::Error> {
193    use std::os::unix::fs::OpenOptionsExt;
194    use std::path::Path;
195
196    let p = Path::new(path);
197    // Canonicalize the parent directory (resolving symlinks in the directory path)
198    // but apply O_NOFOLLOW only to the final file component. This prevents
199    // symlink-following attacks on the target file while allowing legitimate
200    // directory symlinks (e.g., /tmp → /private/tmp on macOS).
201    if let (Some(parent), Some(filename)) = (p.parent(), p.file_name())
202        && parent.exists()
203    {
204        let canonical_parent = crate::core::pathutil::safe_canonicalize_bounded(parent, 2000);
205        let canonical_path = canonical_parent.join(filename);
206        return std::fs::OpenOptions::new()
207            .read(true)
208            .custom_flags(libc::O_NOFOLLOW)
209            .open(&canonical_path);
210    }
211
212    // Fallback: direct open with O_NOFOLLOW
213    std::fs::OpenOptions::new()
214        .read(true)
215        .custom_flags(libc::O_NOFOLLOW)
216        .open(path)
217}
218
219#[cfg(not(unix))]
220fn open_nofollow(path: &str) -> Result<std::fs::File, std::io::Error> {
221    std::fs::File::open(path)
222}
223
224/// Reads a file through the cache and applies the requested compression mode.
225pub fn handle(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
226    handle_with_options(cache, path, mode, false, crp_mode, None)
227}
228
229/// Like `handle`, but invalidates the cache first to force a fresh disk read.
230pub fn handle_fresh(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
231    handle_with_options(cache, path, mode, true, crp_mode, None)
232}
233
234/// Reads a file with task-aware filtering to prioritize task-relevant content.
235pub fn handle_with_task(
236    cache: &mut SessionCache,
237    path: &str,
238    mode: &str,
239    crp_mode: CrpMode,
240    task: Option<&str>,
241) -> String {
242    handle_with_options(cache, path, mode, false, crp_mode, task)
243}
244
245/// Like `handle_with_task`, also returns the resolved mode name and pre-counted tokens.
246pub fn handle_with_task_resolved(
247    cache: &mut SessionCache,
248    path: &str,
249    mode: &str,
250    crp_mode: CrpMode,
251    task: Option<&str>,
252) -> ReadOutput {
253    handle_with_options_resolved(
254        cache,
255        path,
256        mode,
257        false,
258        crp_mode,
259        task,
260        ReadTuning::resolve(None, &[]),
261    )
262}
263
264/// Like [`handle_with_task_resolved`] but with an explicit per-call
265/// aggressiveness (the `ctx_read` `aggressiveness` arg, #714). `None` falls back
266/// to the `LEAN_CTX_AGGRESSIVENESS` env var / config field.
267pub fn handle_with_task_resolved_tuned(
268    cache: &mut SessionCache,
269    path: &str,
270    mode: &str,
271    crp_mode: CrpMode,
272    task: Option<&str>,
273    aggressiveness: Option<f64>,
274    protect: &[String],
275) -> ReadOutput {
276    handle_with_options_resolved(
277        cache,
278        path,
279        mode,
280        false,
281        crp_mode,
282        task,
283        ReadTuning::resolve(aggressiveness, protect),
284    )
285}
286
287/// Fresh read with task-aware filtering (invalidates cache first).
288pub fn handle_fresh_with_task(
289    cache: &mut SessionCache,
290    path: &str,
291    mode: &str,
292    crp_mode: CrpMode,
293    task: Option<&str>,
294) -> String {
295    handle_with_options(cache, path, mode, true, crp_mode, task)
296}
297
298/// Fresh read with task-aware filtering, also returns the resolved mode name and pre-counted tokens.
299pub fn handle_fresh_with_task_resolved(
300    cache: &mut SessionCache,
301    path: &str,
302    mode: &str,
303    crp_mode: CrpMode,
304    task: Option<&str>,
305) -> ReadOutput {
306    handle_with_options_resolved(
307        cache,
308        path,
309        mode,
310        true,
311        crp_mode,
312        task,
313        ReadTuning::resolve(None, &[]),
314    )
315}
316
317/// Fresh-read variant of [`handle_with_task_resolved_tuned`] (#714).
318pub fn handle_fresh_with_task_resolved_tuned(
319    cache: &mut SessionCache,
320    path: &str,
321    mode: &str,
322    crp_mode: CrpMode,
323    task: Option<&str>,
324    aggressiveness: Option<f64>,
325    protect: &[String],
326) -> ReadOutput {
327    handle_with_options_resolved(
328        cache,
329        path,
330        mode,
331        true,
332        crp_mode,
333        task,
334        ReadTuning::resolve(aggressiveness, protect),
335    )
336}
337
338fn handle_with_options(
339    cache: &mut SessionCache,
340    path: &str,
341    mode: &str,
342    fresh: bool,
343    crp_mode: CrpMode,
344    task: Option<&str>,
345) -> String {
346    handle_with_options_resolved(
347        cache,
348        path,
349        mode,
350        fresh,
351        crp_mode,
352        task,
353        ReadTuning::resolve(None, &[]),
354    )
355    .content
356}
357
358/// `LEAN_CTX_FORCE_FRESH=1` — an explicit operator override that always forces a
359/// cold full read, independent of conversation scoping.
360fn force_fresh_env() -> bool {
361    static FORCE_FRESH: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
362    *FORCE_FRESH.get_or_init(|| {
363        std::env::var("LEAN_CTX_FORCE_FRESH").is_ok_and(|v| v == "1" || v == "true")
364    })
365}
366
367/// Detects a subagent (forked agent) execution context via `CURSOR_TASK_ID`.
368///
369/// A subagent must never be served a stub for content only the parent received.
370/// That used to be enforced by force-freshing *every* subagent read; with
371/// conversation scoping (#954/#955) the subagent instead runs under its own scope
372/// (`conversation::current_conversation_id` → `task:{id}`), so the stub gate
373/// withholds cross-agent stubs precisely while restoring the subagent's *own*
374/// cheap re-reads. The blanket force-fresh is therefore kept only as the fallback
375/// when scoping is disabled (#956).
376fn is_subagent_context() -> bool {
377    static IS_SUBAGENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
378    *IS_SUBAGENT.get_or_init(|| std::env::var("CURSOR_TASK_ID").is_ok_and(|v| !v.is_empty()))
379}
380
381fn handle_with_options_resolved(
382    cache: &mut SessionCache,
383    path: &str,
384    mode: &str,
385    fresh: bool,
386    crp_mode: CrpMode,
387    task: Option<&str>,
388    tuning: ReadTuning<'_>,
389) -> ReadOutput {
390    // Subagent reads no longer force-fresh wholesale: conversation scoping gives
391    // each subagent its own `task:{id}` scope, so the stub gate already withholds
392    // any cross-agent stub while keeping the subagent's own re-reads cheap (#956).
393    // The blanket force-fresh remains only when scoping is off, and an explicit
394    // `LEAN_CTX_FORCE_FRESH` always wins.
395    let effective_fresh = fresh
396        || force_fresh_env()
397        || (is_subagent_context() && !crate::core::conversation::scope_enabled());
398
399    // Plugin seam: notify listeners before the read resolves. Guarded so the hot
400    // path never allocates or spawns a thread unless a plugin opts into pre_read.
401    if PluginManager::has_listener("pre_read") {
402        PluginManager::fire_hook_background(HookPoint::PreRead {
403            path: path.to_string(),
404        });
405    }
406
407    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
408        bt.next_seq();
409    }
410    let mut result =
411        handle_with_options_inner(cache, path, mode, effective_fresh, crp_mode, task, tuning);
412
413    if let Some(entry) = cache.get_mut(path) {
414        entry.last_mode.clone_from(&result.resolved_mode);
415    }
416
417    // SSOT via [`ReadMode`] (#528): lossy summaries may elide shared blocks.
418    let dedup_allowed = result
419        .resolved_mode
420        .parse::<ReadMode>()
421        .is_ok_and(|m| m.is_lossy_summary());
422    if dedup_allowed && let Some(deduped) = cache.apply_dedup(path, &result.content) {
423        let new_tokens = count_tokens(&deduped);
424        if new_tokens < result.output_tokens {
425            result.content = deduped;
426            result.output_tokens = new_tokens;
427        }
428    }
429
430    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
431        let original_tokens = cache.get(path).map_or(0, |e| e.original_tokens);
432        bt.record_read(
433            path,
434            &result.resolved_mode,
435            result.output_tokens,
436            original_tokens,
437        );
438
439        // Quality signals (#538): compressed reads count as clean until a
440        // bounce proves otherwise (the bounce signal outweighs 6:1); large
441        // full reads of never-bouncing extensions are wasted compression
442        // opportunities and push the learned threshold up.
443        // SSOT via [`ReadMode`] (#528): only verbatim `full` and the `diff`
444        // delta are uncompressed. A resolved window is always the canonical
445        // `lines:N-M` (parses to `Lines` ⇒ compressed); the default of `true`
446        // for the unreachable bare `"lines"` keeps prior behaviour everywhere a
447        // real resolved mode can occur.
448        let compressed = result
449            .resolved_mode
450            .parse::<ReadMode>()
451            .map_or(true, |m| m.counts_as_compressed());
452        if compressed {
453            crate::core::adaptive_thresholds::record_quality_signal(
454                path,
455                crate::core::threshold_learning::QualitySignal::CleanCompressed,
456            );
457        } else if result.resolved_mode == "full"
458            && result.output_tokens > 2000
459            && bt.bounce_rate_for_extension(path).unwrap_or(0.0) < 0.05
460        {
461            crate::core::adaptive_thresholds::record_quality_signal(
462                path,
463                crate::core::threshold_learning::QualitySignal::WastedFull,
464            );
465        }
466    }
467
468    // Plugin seam: emit the realized compression stats. Same zero-cost guard.
469    if PluginManager::has_listener("post_compress") {
470        let original_tokens = cache.get(path).map_or(0, |e| e.original_tokens);
471        PluginManager::fire_hook_background(HookPoint::PostCompress {
472            path: path.to_string(),
473            original_tokens,
474            compressed_tokens: result.output_tokens,
475        });
476    }
477
478    // Stigmergy (#540): deposit a Hot scent for this read in the background
479    // (the field file lock may briefly block; never stall the read path). The
480    // foreign-claim hint is intentionally NOT appended to the body: it carries a
481    // relative timestamp ("claimed Nm ago"), which would make the output a
482    // non-pure function of wall-clock time and defeat provider prompt caching
483    // (#498). The deposit remains so the field still reflects active work.
484    {
485        let self_agent = crate::core::scent_field::scent_agent_id();
486        let scent_path = crate::core::pathutil::normalize_tool_path(path);
487        std::thread::spawn(move || {
488            crate::core::scent_field::deposit(
489                self_agent,
490                crate::core::scent_field::ScentKind::Hot,
491                &scent_path,
492                0.3,
493            );
494        });
495    }
496
497    result
498}
499
500/// Attempt to serve a `mode="full"` cache hit (`[unchanged …]`) using only a
501/// shared borrow of the cache.
502///
503/// Returns `None` when the file is not cached, was modified on disk, full
504/// content was never delivered, or the cache policy forbids stubbing — in those
505/// cases the caller must fall back to the write path.
506///
507/// This is the read-locked fast path: it needs no `&mut SessionCache`, so the
508/// dominant "re-read an unchanged file" case proceeds under a shared lock and
509/// parallel reads of distinct files no longer serialize on a global write lock.
510pub fn try_stub_hit_readonly(cache: &SessionCache, path: &str) -> Option<ReadOutput> {
511    // Resolve the caller *fresh* (TTL-bypassed): the stub gate's concurrency
512    // detection must see a just-appeared second chat with zero lag, else a stub
513    // could leak across chats in the pre-detection window (#1042).
514    let current_conversation = crate::core::conversation::current_conversation_id_fresh();
515    try_stub_hit_readonly_scoped(cache, path, current_conversation.as_deref())
516}
517
518/// Conversation-scoped core of [`try_stub_hit_readonly`]. The current
519/// conversation id is injected (not read from the global resolver) so the
520/// conversation gate can be tested deterministically without global state.
521fn try_stub_hit_readonly_scoped(
522    cache: &SessionCache,
523    path: &str,
524    current_conversation: Option<&str>,
525) -> Option<ReadOutput> {
526    let no_deg = crate::core::config::Config::load().no_degrade_effective();
527    let prof = crate::core::profiles::active_profile();
528    let force_full = no_deg
529        || (prof.read.default_mode_effective() == "full"
530            && prof.compression.crp_mode_effective() == "off");
531    let policy_allows_stub =
532        crate::server::compaction_sync::effective_cache_policy() != "safe" && !force_full;
533    if !policy_allows_stub {
534        return None;
535    }
536
537    // Warm path: a live in-memory entry is the freshest source of truth.
538    if let Some(file_ref) = cache.get_file_ref_readonly(path) {
539        let (cached_mtime, cached_hash, line_count, delivered_conv) = {
540            let entry = cache.get(path)?;
541            (
542                entry.stored_mtime,
543                entry.hash.clone(),
544                entry.line_count,
545                entry.delivered_conversation.clone(),
546            )
547        };
548        if crate::core::cache::is_cache_entry_stale_verified(path, cached_mtime, &cached_hash)
549            || !cache.is_full_delivered(path)
550        {
551            return None;
552        }
553        // Conversation scoping (#954): only stub when THIS conversation received
554        // the content. A different (or unknown) conversation re-delivers in full
555        // rather than emit a misleading stub. `current == None` (hooks absent)
556        // preserves legacy process-scoped behavior, so single-chat hit rates are
557        // unchanged.
558        if !crate::core::conversation::conversation_allows_stub(
559            current_conversation,
560            delivered_conv.as_deref(),
561        ) {
562            crate::core::cache_telemetry::record_conversation_mismatch();
563            return None;
564        }
565        cache.record_cache_hit(path);
566        return Some(render_unchanged_stub(&file_ref, path, line_count));
567    }
568
569    // Cold fallback (#955): no live entry (e.g. after a daemon restart or idle
570    // clear). Serve the stub from the persisted index iff the file is unchanged
571    // AND the *same known* conversation is asking — a stricter gate than the warm
572    // path, because a cold stub crosses a process boundary (no "no context →
573    // legacy" escape; see `conversation_allows_cold_stub`).
574    let rec = crate::core::read_stub_index::lookup(path)?;
575    if crate::core::cache::is_cache_entry_stale_verified(path, rec.stored_mtime(), &rec.hash) {
576        return None;
577    }
578    if !crate::core::conversation::conversation_allows_cold_stub(
579        current_conversation,
580        rec.delivered_conversation.as_deref(),
581    ) {
582        crate::core::cache_telemetry::record_conversation_mismatch();
583        return None;
584    }
585    Some(render_unchanged_stub(&rec.file_ref, path, rec.line_count))
586}
587
588/// Renders the `[unchanged …]` stub body shared by the warm and cold stub paths.
589///
590/// #498 determinism: the stub is a pure function of (file_ref, path, line_count),
591/// so identical re-reads stay byte-stable and provider prompt caching applies.
592/// The `fresh=true` escape is a *static* suffix (no rotating proof lines or
593/// read-count notes), so a re-reader in non-meta mode still sees how to force the
594/// content (#513) without breaking byte-stability.
595fn render_unchanged_stub(file_ref: &str, path: &str, line_count: usize) -> ReadOutput {
596    let short = protocol::shorten_path(path);
597    let out = if crate::core::protocol::meta_visible() {
598        format!(
599            "{file_ref}={short} [unchanged {line_count}L]\nUnchanged on disk. Use fresh=true to force re-read.",
600        )
601    } else {
602        format!("{file_ref}={short} [unchanged {line_count}L · fresh=true to re-read]")
603    };
604    let out = crate::core::redaction::redact_text_if_enabled(&out);
605    let sent = count_tokens(&out);
606    ReadOutput {
607        content: out,
608        resolved_mode: "full".into(),
609        output_tokens: sent,
610    }
611}
612
613/// Outcome of [`resolve_explicit_delta_mode`]: the (possibly rewritten) read
614/// mode plus an optional advisory note to surface to the agent.
615#[derive(Debug, Clone, PartialEq, Eq)]
616pub struct DeltaExplicitDecision {
617    /// The mode the read should proceed with (rewritten only when the feature
618    /// fires; otherwise the caller's mode, unchanged).
619    pub mode: String,
620    /// A byte-stable advisory appended to the read body when the mode was
621    /// rewritten to `diff`. `None` when nothing was rewritten or the collapse
622    /// was a silent `lines:`→`full` stub.
623    pub note: Option<String>,
624}
625
626/// Decide whether an **explicit** `full`/`lines:N-M` re-read of a session-cached
627/// file should be served as a delta instead of re-emitting content the model
628/// already holds (the `delta_explicit` opt-in; env `LCTX_DELTA_EXPLICIT`).
629///
630/// Returns the mode the read should proceed with:
631/// - **Changed on disk** (verified mtime+md5 stale) and full content is cached →
632///   `diff`, plus an advisory note. The diff carries exactly the new
633///   information in a fraction of the tokens.
634/// - **Unchanged** and the request is `lines:` of an already-fully-delivered
635///   file → `full`, so the read collapses to the ~15-token `[unchanged]` stub
636///   instead of re-extracting a window the model has seen.
637/// - Otherwise the caller's `mode` is returned untouched.
638///
639/// First reads (nothing cached) and `fresh=true` are never affected — the
640/// caller gates those before calling. Staleness uses the **verified** variant
641/// ([`crate::core::cache::is_cache_entry_stale_verified`]) so a same-second
642/// write on a coarse-granularity filesystem cannot be mistaken for "unchanged"
643/// and yield a misleading empty diff (#498 determinism).
644///
645/// Pure w.r.t. (cache, path, mode, enabled): no wall-clock, counters, or
646/// randomness enter the result, so identical inputs stay byte-stable.
647pub fn resolve_explicit_delta_mode(
648    cache: &SessionCache,
649    path: &str,
650    mode: &str,
651    explicit_mode: bool,
652    fresh: bool,
653    enabled: bool,
654) -> DeltaExplicitDecision {
655    let unchanged = DeltaExplicitDecision {
656        mode: mode.to_string(),
657        note: None,
658    };
659    if fresh || !enabled || !explicit_mode || !(mode == "full" || mode.starts_with("lines:")) {
660        return unchanged;
661    }
662    let Some(entry) = cache.get(path) else {
663        // First read this session — nothing to diff against.
664        return unchanged;
665    };
666    let stale =
667        crate::core::cache::is_cache_entry_stale_verified(path, entry.stored_mtime, &entry.hash);
668    if stale {
669        // Only divert to a diff when full content is actually cached: the diff
670        // base is that full content (see `handle_diff`), never a compressed
671        // view. Without it, `handle_diff` would have nothing to compare.
672        if entry.content().is_some() {
673            return DeltaExplicitDecision {
674                mode: "diff".to_string(),
675                note: Some(format!(
676                    "[delta-explicit] requested mode={mode} served as a diff: the file \
677                     changed since your last read and the diff is the new information. \
678                     Pass fresh=true if you need the full content re-emitted."
679                )),
680            };
681        }
682        return unchanged;
683    }
684    // Unchanged on disk: a `lines:` window of a file already delivered in full
685    // re-emits text the model holds — collapse to the full-mode stub
686    // (~15 tokens). A plain `full` re-read already hits that stub downstream.
687    if mode.starts_with("lines:") && cache.is_full_delivered(path) {
688        return DeltaExplicitDecision {
689            mode: "full".to_string(),
690            note: None,
691        };
692    }
693    unchanged
694}
695
696fn handle_with_options_inner(
697    cache: &mut SessionCache,
698    path: &str,
699    mode: &str,
700    fresh: bool,
701    crp_mode: CrpMode,
702    task: Option<&str>,
703    tuning: ReadTuning<'_>,
704) -> ReadOutput {
705    let file_ref = cache.get_file_ref(path);
706    let short = protocol::shorten_path(path);
707    let ext = Path::new(path)
708        .extension()
709        .and_then(|e| e.to_str())
710        .unwrap_or("");
711
712    // #1150: a path the operator marked "never compress" is always returned in
713    // full — exact bytes matter more than token savings for these files (golden
714    // snapshots, byte-asserted fixtures, security-sensitive configs). Every lossy
715    // mode (auto, aggressive, signatures, density, diff, …) collapses to the
716    // verbatim full read; `raw` (already verbatim) and explicit `lines:` slices
717    // are left as the user asked. The default config protects nothing, so this is
718    // a fast no-op for everyone who hasn't opted in.
719    let mode = if mode != "raw"
720        && !mode.starts_with("lines:")
721        && crate::core::config::Config::load()
722            .proxy
723            .is_path_compress_protected(path)
724    {
725        "full"
726    } else {
727        mode
728    };
729
730    if fresh {
731        if mode == "diff" {
732            let warning = "[warning] fresh+diff is redundant — fresh invalidates cache, no diff possible. Use mode=full with fresh=true instead.";
733            return ReadOutput {
734                content: warning.to_string(),
735                resolved_mode: "diff".into(),
736                output_tokens: count_tokens(warning),
737            };
738        }
739        cache.invalidate(path);
740    }
741
742    if mode == "diff" {
743        let (out, _) = handle_diff(cache, path, &file_ref);
744        let out = crate::core::redaction::redact_text_if_enabled(&out);
745        let sent = count_tokens(&out);
746        return ReadOutput {
747            content: out,
748            resolved_mode: "diff".into(),
749            output_tokens: sent,
750        };
751    }
752
753    if mode != "full"
754        && let Some(existing) = cache.get(path)
755    {
756        let stale = crate::core::cache::is_cache_entry_stale_verified(
757            path,
758            existing.stored_mtime,
759            &existing.hash,
760        );
761        if stale {
762            cache.invalidate(path);
763        }
764    }
765
766    // Snapshot the minimal immutable data the miss paths need, then drop the
767    // borrow before any mutable operations (set_compressed, invalidate, store).
768    let cache_snapshot = cache
769        .get(path)
770        .map(|existing| (existing.original_tokens, existing.content()));
771
772    if let Some((original_tokens, content_opt)) = cache_snapshot {
773        // Resolve the read mode first — and *cache-aware* for `auto`. Handing the
774        // live cache to the resolver is what lets an `auto` re-read of an
775        // unchanged, already-fully-delivered file short-circuit to
776        // ("full", "cache_hit") and collapse to the cheap ~13-token `[unchanged]`
777        // stub, exactly like an explicit `full` re-read. The previous call passed
778        // no cache, so that branch was dead code and every `auto` re-read
779        // re-delivered the whole file ("re-reads aren't cached"). Resolving
780        // up-front also lets us hit the compressed-output cache BEFORE
781        // decompressing the full body (avoids ~2-5ms zstd on hits). The
782        // aggressiveness knob (#714) still routes `auto` through the density path.
783        let resolved_mode = if mode == "auto" {
784            tuning
785                .auto_density_mode()
786                .unwrap_or_else(|| resolve_auto_mode(Some(cache), path, original_tokens, task))
787        } else {
788            mode.to_string()
789        };
790
791        if resolved_mode == "full" {
792            // Read-locked stub fast path (single source of truth, shared with
793            // the registered handler's concurrent read-lock attempt). Reached by
794            // an explicit `mode=full` and by `auto` that resolved to a full
795            // cache-hit, so both collapse identically to the `[unchanged]` stub.
796            if let Some(out) = try_stub_hit_readonly(cache, path) {
797                return out;
798            }
799            let (out, _) = handle_full_with_auto_delta(cache, path, &file_ref, &short, ext, task);
800            let out = crate::core::redaction::redact_text_if_enabled(&out);
801            let sent = count_tokens(&out);
802            return ReadOutput {
803                content: out,
804                resolved_mode: "full".into(),
805                output_tokens: sent,
806            };
807        }
808
809        if is_cacheable_mode(&resolved_mode) {
810            let cache_key = compressed_cache_key(
811                &resolved_mode,
812                crp_mode,
813                task,
814                tuning.aggressiveness,
815                tuning.protect,
816            );
817            let compressed_hit = cache.get_compressed(path, &cache_key).cloned();
818            if let Some(cached_output) = compressed_hit {
819                cache.record_cache_hit(path);
820                let out = crate::core::redaction::redact_text_if_enabled(&cached_output);
821                let sent = count_tokens(&out);
822                return ReadOutput {
823                    content: out,
824                    resolved_mode,
825                    output_tokens: sent,
826                };
827            }
828        }
829
830        if let Some(content) = content_opt {
831            let (out, _) = process_mode_tuned(
832                &content,
833                &resolved_mode,
834                &file_ref,
835                &short,
836                ext,
837                original_tokens,
838                crp_mode,
839                path,
840                task,
841                tuning,
842            );
843            // #361 anti-inflation for lossy whole-file summaries (auto OR
844            // explicit): map/signatures/… must never cost more than the raw file.
845            // Selection/delta views keep their exact shape (see
846            // mode_allows_raw_cap). Cap before caching so re-read hits serve the
847            // same capped, byte-stable body.
848            let out = if mode_allows_raw_cap(&resolved_mode) {
849                let framed_tokens = count_tokens(&out);
850                cap_to_raw(out, framed_tokens, &content, original_tokens)
851            } else {
852                out
853            };
854            if is_cacheable_mode(&resolved_mode) {
855                let cache_key = compressed_cache_key(
856                    &resolved_mode,
857                    crp_mode,
858                    task,
859                    tuning.aggressiveness,
860                    tuning.protect,
861                );
862                cache.set_compressed(path, &cache_key, out.clone());
863            }
864            let out = crate::core::redaction::redact_text_if_enabled(&out);
865            let sent = count_tokens(&out);
866            return ReadOutput {
867                content: out,
868                resolved_mode,
869                output_tokens: sent,
870            };
871        }
872        cache.invalidate(path);
873    }
874
875    let content = match read_file_lossy(path) {
876        Ok(c) => c,
877        Err(e) => {
878            let msg = format!("ERROR: {e}");
879            let tokens = count_tokens(&msg);
880            return ReadOutput {
881                content: msg,
882                resolved_mode: "error".into(),
883                output_tokens: tokens,
884            };
885        }
886    };
887
888    let store_result = cache.store(path, &content);
889
890    // Skip expensive hint computation for line-range reads and first reads.
891    // Hints are only useful from the 2nd read onwards when the file is contextually relevant.
892    let is_line_range = mode.starts_with("lines:");
893    let hints = crate::core::profiles::active_profile().output_hints;
894    let is_repeat_read = store_result.read_count > 1;
895    let similar_hint = if !is_line_range && is_repeat_read && hints.semantic_hint() {
896        find_similar_and_update_semantic_index(path, &content)
897    } else {
898        None
899    };
900    let graph_hint = if !is_line_range && is_repeat_read && hints.related_hint() {
901        build_graph_related_hint(path)
902    } else {
903        None
904    };
905
906    if mode == "full" {
907        cache.mark_full_delivered(path);
908        let (mut output, _) = format_full_output(
909            &file_ref,
910            &short,
911            ext,
912            &content,
913            store_result.original_tokens,
914            store_result.line_count,
915            task,
916        );
917        if let Some(hint) = &graph_hint {
918            output.push_str(&format!("\n{hint}"));
919        }
920        if let Some(hint) = similar_hint {
921            output.push_str(&format!("\n{hint}"));
922        }
923        let framed_tokens = count_tokens(&output);
924        let output = cap_to_raw(
925            output,
926            framed_tokens,
927            &content,
928            store_result.original_tokens,
929        );
930        let output = crate::core::redaction::redact_text_if_enabled(&output);
931        let sent = count_tokens(&output);
932        return ReadOutput {
933            content: output,
934            resolved_mode: "full".into(),
935            output_tokens: sent,
936        };
937    }
938
939    let resolved_mode = if mode == "auto" {
940        tuning
941            .auto_density_mode()
942            .unwrap_or_else(|| resolve_auto_mode(None, path, store_result.original_tokens, task))
943    } else {
944        mode.to_string()
945    };
946
947    let (output, _sent) = process_mode_tuned(
948        &content,
949        &resolved_mode,
950        &file_ref,
951        &short,
952        ext,
953        store_result.original_tokens,
954        crp_mode,
955        path,
956        task,
957        tuning,
958    );
959    // #361 anti-inflation for lossy whole-file summaries (auto OR explicit);
960    // selection/delta views keep their exact shape (see mode_allows_raw_cap).
961    // Cap first, then cache the pure capped body so re-reads stay byte-stable
962    // (#498) — the optional, read-state-dependent navigation hints below are
963    // appended to the returned value only, never to the cached body.
964    let mut output = if mode_allows_raw_cap(&resolved_mode) {
965        let framed_tokens = count_tokens(&output);
966        cap_to_raw(
967            output,
968            framed_tokens,
969            &content,
970            store_result.original_tokens,
971        )
972    } else {
973        output
974    };
975    if is_cacheable_mode(&resolved_mode) {
976        let cache_key = compressed_cache_key(
977            &resolved_mode,
978            crp_mode,
979            task,
980            tuning.aggressiveness,
981            tuning.protect,
982        );
983        cache.set_compressed(path, &cache_key, output.clone());
984    }
985    if let Some(hint) = &graph_hint {
986        output.push_str(&format!("\n{hint}"));
987    }
988    if let Some(hint) = similar_hint {
989        output.push_str(&format!("\n{hint}"));
990    }
991    let output = crate::core::redaction::redact_text_if_enabled(&output);
992    let final_tokens = count_tokens(&output);
993    ReadOutput {
994        content: output,
995        resolved_mode,
996        output_tokens: final_tokens,
997    }
998}
999
1000pub fn is_instruction_file(path: &str) -> bool {
1001    let lower = path.to_lowercase();
1002    let filename = std::path::Path::new(&lower)
1003        .file_name()
1004        .and_then(|f| f.to_str())
1005        .unwrap_or("");
1006
1007    matches!(
1008        filename,
1009        "skill.md"
1010            | "agents.md"
1011            | "rules.md"
1012            | ".cursorrules"
1013            | ".clinerules"
1014            | "lean-ctx.md"
1015            | "lean-ctx.mdc"
1016    ) || lower.contains("/skills/")
1017        || lower.contains("/.cursor/rules/")
1018        || lower.contains("/.claude/rules/")
1019        || lower.contains("/agents.md")
1020}
1021
1022/// #361 anti-inflation invariant: a `ctx_read` must never cost more tokens than
1023/// reading the raw file would. Framing (file-ref header, deps/exports summary,
1024/// savings footer, navigation hints) only earns its keep on large files and
1025/// repeated reads — on a cold read of a small file it is pure overhead, the
1026/// exact inflation an independent benchmark measured (#361). When the framed
1027/// payload exceeds the bare content we ship the content verbatim, so a read is
1028/// break-even at worst and a win whenever a compressed mode or a cached re-read
1029/// applies. Re-reads are unaffected: the cache keys on path and re-derives the
1030/// file ref, so dropping the cold header here costs nothing on the next read.
1031///
1032/// `framed_tokens` and `raw_tokens` are both measured pre-redaction (redaction
1033/// is roughly token-neutral and applied to whichever string wins), so the
1034/// comparison is apples-to-apples with `original_tokens`. Empty files
1035/// (`raw_tokens == 0`) keep their framing so the reader still gets a signal.
1036fn cap_to_raw(
1037    framed: String,
1038    framed_tokens: usize,
1039    raw_content: &str,
1040    raw_tokens: usize,
1041) -> String {
1042    if raw_tokens > 0 && framed_tokens > raw_tokens {
1043        raw_content.to_string()
1044    } else {
1045        framed
1046    }
1047}
1048
1049/// Delegates to the unified `auto_mode_resolver::resolve()`.
1050/// Resolve `auto` to a concrete mode.
1051///
1052/// Pass `Some(cache)` on the warm read path: the resolver then short-circuits an
1053/// unchanged, already-fully-delivered file to `("full", "cache_hit")` so the
1054/// caller can collapse the re-read to the cheap `[unchanged]` stub instead of
1055/// re-delivering the whole body. Pass `None` only where no session cache exists
1056/// (the CLI cold path), which forces a stateless cold resolution.
1057fn resolve_auto_mode(
1058    cache: Option<&SessionCache>,
1059    file_path: &str,
1060    original_tokens: usize,
1061    task: Option<&str>,
1062) -> String {
1063    let ctx = crate::core::auto_mode_resolver::AutoModeContext {
1064        path: file_path,
1065        token_count: original_tokens,
1066        task,
1067        cache,
1068    };
1069    crate::core::auto_mode_resolver::resolve(&ctx).mode
1070}
1071
1072fn find_similar_and_update_semantic_index(path: &str, content: &str) -> Option<String> {
1073    const MAX_CONTENT_BYTES_FOR_SEMANTIC: usize = 32_768;
1074
1075    if content.len() > MAX_CONTENT_BYTES_FOR_SEMANTIC {
1076        return None;
1077    }
1078
1079    let cfg = crate::core::config::Config::load();
1080    let profile = crate::core::config::MemoryProfile::effective(&cfg);
1081    if !profile.semantic_cache_enabled() {
1082        return None;
1083    }
1084
1085    let project_root = detect_project_root(path);
1086    let session_id = format!("{}", std::process::id());
1087    let mut index = crate::core::semantic_cache::SemanticCacheIndex::load_or_create(&project_root);
1088
1089    let similar = index.find_similar(content, 0.7);
1090    let relevant: Vec<_> = similar
1091        .into_iter()
1092        .filter(|(p, _)| p != path)
1093        .take(3)
1094        .collect();
1095
1096    index.add_file(path, content, &session_id);
1097    if let Err(e) = index.save(&project_root) {
1098        tracing::warn!("lean-ctx: failed to persist semantic index: {e}");
1099    }
1100
1101    if relevant.is_empty() {
1102        return None;
1103    }
1104
1105    let hints: Vec<String> = relevant
1106        .iter()
1107        .map(|(p, score)| format!("  {p} ({:.0}% similar)", score * 100.0))
1108        .collect();
1109
1110    Some(format!(
1111        "[semantic: {} similar file(s) in cache]\n{}",
1112        relevant.len(),
1113        hints.join("\n")
1114    ))
1115}
1116
1117fn detect_project_root(path: &str) -> String {
1118    crate::core::protocol::detect_project_root_or_cwd(path)
1119}
1120
1121fn build_graph_related_hint(path: &str) -> Option<String> {
1122    let project_root = detect_project_root(path);
1123    crate::core::graph_context::build_related_hint(path, &project_root, 5)
1124}
1125
1126const AUTO_DELTA_THRESHOLD: f64 = 0.6;
1127
1128/// Re-reads from disk; if content changed and delta is compact, sends auto-delta.
1129fn handle_full_with_auto_delta(
1130    cache: &mut SessionCache,
1131    path: &str,
1132    file_ref: &str,
1133    short: &str,
1134    ext: &str,
1135    task: Option<&str>,
1136) -> (String, usize) {
1137    let _mode_guard = crate::core::savings_footer::ModeGuard::new("full");
1138    let Ok(disk_content) = read_file_lossy(path) else {
1139        cache.record_cache_hit(path);
1140        if let Some(existing) = cache.get(path) {
1141            if !crate::core::protocol::meta_visible()
1142                && let Some(cached) = existing.content()
1143            {
1144                return format_full_output(
1145                    file_ref,
1146                    short,
1147                    ext,
1148                    &cached,
1149                    existing.original_tokens,
1150                    existing.line_count,
1151                    task,
1152                );
1153            }
1154            let out = format!(
1155                "[using cached version — file read failed]\n{file_ref}={short} cached {}t {}L",
1156                existing.read_count(),
1157                existing.line_count
1158            );
1159            let sent = count_tokens(&out);
1160            return (out, sent);
1161        }
1162        let out = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1163            format!("[file read failed and no cached version available] {file_ref}={short}")
1164        } else {
1165            format!("[file read failed and no cached version available] {short}")
1166        };
1167        let sent = count_tokens(&out);
1168        return (out, sent);
1169    };
1170
1171    let no_deg = crate::core::config::Config::load().no_degrade_effective();
1172    let prof = crate::core::profiles::active_profile();
1173    let force_full = no_deg
1174        || (prof.read.default_mode_effective() == "full"
1175            && prof.compression.crp_mode_effective() == "off");
1176
1177    let old_content = cache
1178        .get(path)
1179        .and_then(crate::core::cache::CacheEntry::content)
1180        .unwrap_or_default();
1181    let store_result = cache.store(path, &disk_content);
1182
1183    if store_result.was_hit {
1184        let policy_allows_stub =
1185            crate::server::compaction_sync::effective_cache_policy() != "safe" && !force_full;
1186        if policy_allows_stub && store_result.full_content_delivered {
1187            let out = if crate::core::protocol::meta_visible() {
1188                format!(
1189                    "{file_ref}={short} [unchanged {}L]\nUnchanged on disk. Use fresh=true to force re-read.",
1190                    store_result.line_count
1191                )
1192            } else {
1193                // #498 determinism: byte-stable cache-hit stub (see
1194                // try_stub_hit_readonly). The `fresh=true` escape is a static
1195                // suffix, so non-meta re-readers still see how to force content (#513).
1196                format!(
1197                    "{file_ref}={short} [unchanged {}L · fresh=true to re-read]",
1198                    store_result.line_count
1199                )
1200            };
1201            let sent = count_tokens(&out);
1202            return (out, sent);
1203        }
1204        cache.mark_full_delivered(path);
1205        return format_full_output(
1206            file_ref,
1207            short,
1208            ext,
1209            &disk_content,
1210            store_result.original_tokens,
1211            store_result.line_count,
1212            task,
1213        );
1214    }
1215
1216    let diff = compressor::diff_content(&old_content, &disk_content);
1217    let diff_tokens = count_tokens(&diff);
1218    let full_tokens = store_result.original_tokens;
1219
1220    if !force_full
1221        && full_tokens > 0
1222        && (diff_tokens as f64) < (full_tokens as f64 * AUTO_DELTA_THRESHOLD)
1223    {
1224        let savings = protocol::format_savings(full_tokens, diff_tokens);
1225        let head = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1226            format!("{file_ref}={short}")
1227        } else {
1228            short.to_string()
1229        };
1230        let out = format!(
1231            "{head} [auto-delta] ∆{}L\n{diff}\n{savings}",
1232            disk_content.lines().count()
1233        );
1234        return (out, diff_tokens);
1235    }
1236
1237    format_full_output(
1238        file_ref,
1239        short,
1240        ext,
1241        &disk_content,
1242        store_result.original_tokens,
1243        store_result.line_count,
1244        task,
1245    )
1246}
1247
1248fn handle_diff(cache: &mut SessionCache, path: &str, file_ref: &str) -> (String, usize) {
1249    let _mode_guard = crate::core::savings_footer::ModeGuard::new("diff");
1250    let short = protocol::shorten_path(path);
1251    let old_content = cache
1252        .get(path)
1253        .and_then(crate::core::cache::CacheEntry::content);
1254
1255    let new_content = match read_file_lossy(path) {
1256        Ok(c) => c,
1257        Err(e) => {
1258            let msg = format!("ERROR: {e}");
1259            let tokens = count_tokens(&msg);
1260            return (msg, tokens);
1261        }
1262    };
1263
1264    let original_tokens = count_tokens(&new_content);
1265
1266    let diff_output = if let Some(old) = &old_content {
1267        compressor::diff_content(old, &new_content)
1268    } else {
1269        // No previous version cached — store content for future diffs but
1270        // return a short guidance message instead of dumping the full file.
1271        cache.store(path, &new_content);
1272        let msg = format!(
1273            "{file_ref}={short} [no cached version for diff — use mode=full first, then diff on re-read]"
1274        );
1275        let sent = count_tokens(&msg);
1276        return (msg, sent);
1277    };
1278
1279    cache.store(path, &new_content);
1280
1281    let sent = count_tokens(&diff_output);
1282    let savings = protocol::format_savings(original_tokens, sent);
1283    let head = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1284        format!("{file_ref}={short}")
1285    } else {
1286        short
1287    };
1288    (format!("{head} [diff]\n{diff_output}\n{savings}"), sent)
1289}