Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5
6use rmcp::ErrorData;
7use rmcp::model::Tool;
8use serde_json::{Map, Value};
9
10use crate::core::cache::ReuseOutcome;
11use crate::server::tool_trait::{
12    McpTool, ToolContext, ToolOutput, get_bool, get_f64, get_int, get_str, get_str_array,
13    require_resolved_path,
14};
15
16/// Per-file lock that serializes concurrent reads of the same path.
17///
18/// When multiple subagents read sequentially through a shared set of files,
19/// they tend to hit the same path at the same time. Without per-file locking
20/// they all contend on the global cache write lock while doing redundant I/O.
21/// This lock ensures only one thread reads a given file from disk; the others
22/// wait cheaply on the per-file mutex, then hit the warm cache.
23///
24/// Backed by the shared `core::path_locks` registry so reads and edits of the
25/// same path coordinate through a single mutex (see issue #320).
26fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
27    crate::core::path_locks::per_file_lock(path)
28}
29
30pub struct CtxReadTool;
31
32#[path = "ctx_read_delivery.rs"]
33mod delivery;
34use delivery::{
35    CacheSourceIdentity, PendingCacheDelivery, PendingCrossAgentDelivery, PendingReadDelivery,
36};
37
38pub(super) struct PreparedRead {
39    pub(super) output: ToolOutput,
40    delivery: Option<PendingReadDelivery>,
41}
42
43impl PreparedRead {
44    pub(super) fn commit(self, ctx: &ToolContext, record_agent_budget: bool) -> ToolOutput {
45        if let Some(delivery) = self.delivery {
46            delivery.commit(ctx, &self.output, record_agent_budget);
47        }
48        self.output
49    }
50}
51
52#[path = "ctx_read_dispatch.rs"]
53mod dispatch;
54
55impl CtxReadTool {
56    #[allow(clippy::unused_self)]
57    pub(super) fn handle_inner(
58        &self,
59        args: &Map<String, Value>,
60        ctx: &ToolContext,
61        path: &str,
62        engine_interface_v1: bool,
63    ) -> Result<ToolOutput, ErrorData> {
64        self.handle_inner_prepared(args, ctx, path, engine_interface_v1)
65            .map(|prepared| prepared.commit(ctx, true))
66    }
67
68    #[allow(clippy::unused_self)]
69    pub(super) fn handle_inner_prepared(
70        &self,
71        args: &Map<String, Value>,
72        ctx: &ToolContext,
73        path: &str,
74        engine_interface_v1: bool,
75    ) -> Result<PreparedRead, ErrorData> {
76        let session_lock = ctx
77            .session
78            .as_ref()
79            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
80        let cache_lock = ctx
81            .cache
82            .as_ref()
83            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
84
85        let current_task = {
86            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
87            let mut attempt = 0u32;
88            loop {
89                // #1018: use try_read_owned instead of Handle::block_on to avoid
90                // the async-runtime-saturation anti-pattern on Windows.
91                if let Ok(guard) = session_lock.clone().try_read_owned() {
92                    break guard
93                        .task
94                        .as_ref()
95                        .map(|t| (t.description.clone(), t.intent.clone()));
96                }
97                attempt += 1;
98                if std::time::Instant::now() >= deadline {
99                    tracing::warn!(
100                        "session read-lock timeout after {attempt} attempts in ctx_read for {path}"
101                    );
102                    break None;
103                }
104                std::thread::sleep(std::time::Duration::from_millis(25));
105            }
106        };
107        // #1590: `auto_infer_task` fabricates descriptions like
108        // "Working on /repo/src/printer (explore)" from touched-file patterns.
109        // That is fine as a telemetry hint, but its "keywords" (Working,
110        // explore, a directory path) carry no signal about a file's contents —
111        // filtering a file down to a quarter of its lines on that basis, or
112        // pinning it to `full` as an intent target, invents a task the caller
113        // never stated. Only an explicitly set task steers a read.
114        let task_is_inferred = current_task
115            .as_ref()
116            .is_some_and(|(_, intent)| !task_intent_steers_read(intent.as_deref()));
117        let current_task = current_task.map(|(description, _)| description);
118        let task_ref = if task_is_inferred {
119            None
120        } else {
121            current_task.as_deref()
122        };
123        // #513: `raw=true` is the intuitive "give me the exact bytes" escape an
124        // agent reaches for. Alias it to mode="raw" (verbatim, unframed) and
125        // force a fresh disk read below so a re-read never collapses to an
126        // `[unchanged]`/auto-delta stub. An explicit raw flag wins over `mode`.
127        let arg_raw = get_bool(args, "raw").unwrap_or(false);
128        let explicit_mode_arg = resolve_explicit_mode(arg_raw, get_str(args, "mode"));
129        let explicit_mode = explicit_mode_arg.is_some();
130        // #1209: a malformed line-range payload (e.g. `lines:44:48` with a colon
131        // instead of a dash) must fail loudly, not silently return an empty
132        // window on small files or bounce to a full-file dump on large ones.
133        // `lines:` and `anchored:` share `parse_line_range`, so validating both
134        // line-range modes at the boundary catches the typo for either. Other
135        // modes are left untouched: bare `density:` is a valid fallback and
136        // unknown keywords keep the historical warn-and-fall-back behaviour.
137        if let Some(ref requested) = explicit_mode_arg
138            && (requested.starts_with("lines:") || requested.starts_with("anchored:"))
139            && let Err(e) = requested.parse::<crate::tools::ctx_read::ReadMode>()
140        {
141            return Err(ErrorData::invalid_params(e.user_message(), None));
142        }
143        let configured_mode = (!explicit_mode)
144            .then(crate::core::auto_mode_resolver::configured_default_mode)
145            .flatten();
146        let learned_mode = if !explicit_mode && configured_mode.is_none() {
147            if let Ok(cache) = cache_lock.try_read() {
148                Some(crate::tools::ctx_smart_read::select_mode_with_task(
149                    &cache, path, task_ref,
150                ))
151            } else {
152                tracing::debug!(
153                    "cache lock contested during auto-mode selection for {path}; \
154                     falling back to full"
155                );
156                None
157            }
158        } else {
159            None
160        };
161        let mut mode = crate::core::auto_mode_resolver::resolve_mode_precedence(
162            explicit_mode_arg,
163            configured_mode,
164            learned_mode,
165            "full",
166        );
167        let mut fresh = get_bool(args, "fresh").unwrap_or(false);
168        // Reacquire original bytes under current rules; an older compressed
169        // view can have omitted the classification marker that now blocks it.
170        if crate::core::policy::runtime::is_active() {
171            fresh = true;
172        }
173        // #513: a raw/verbatim request always reads from disk — the whole point
174        // is exact current bytes, never a cached stub or delta.
175        if arg_raw || engine_interface_v1 {
176            fresh = true;
177        }
178        let cache_policy = crate::server::compaction_sync::effective_cache_policy();
179        let cache_policy_bypassed = cache_policy == "off";
180        if cache_policy_bypassed {
181            fresh = true;
182        }
183        let aggressiveness =
184            crate::core::aggressiveness::effective(get_f64(args, "aggressiveness"));
185        let protect = get_str_array(args, "protect").unwrap_or_default();
186        // One-knob UX: when the caller sets aggressiveness without pinning a mode,
187        // route through the proven density path at the mapped target. An explicit
188        // mode (incl. entropy/task) instead has the knob tune it via ReadTuning.
189        if !explicit_mode && let Some(a) = aggressiveness {
190            // SSOT mode construction via the typed `ReadMode` (#528): the typed
191            // `Density` Display emits the same `density:0.NN` the pipeline parses.
192            mode = crate::tools::ctx_read::ReadMode::Density(
193                crate::core::aggressiveness::AggressivenessProfile::from_level(a).density_target,
194            )
195            .to_string();
196        }
197        // `start_line` (and its `offset`/`limit` aliases) can pin a line window.
198        // The resolution lives in `apply_line_window`/`resolve_line_window` so
199        // the runtime path and the unit tests share one implementation and can
200        // never drift (GitHub #432 aliases, #259 explicit-mode, #253 line-1).
201        apply_line_window(
202            &mut mode,
203            &mut fresh,
204            explicit_mode,
205            get_int(args, "start_line"),
206            get_int(args, "offset"),
207            get_int(args, "limit"),
208        );
209
210        // A concrete per-call request outranks saved views and adaptive heuristics.
211        // `auto` explicitly delegates the choice; mandatory admission still runs.
212        let pinned_mode = explicit_mode && mode != "auto";
213        if pinned_mode
214            && (matches!(mode.as_str(), "raw" | "full" | "full-compact")
215                || mode.starts_with("lines:")
216                || mode.starts_with("anchored"))
217        {
218            // Exact/full requests must not collapse to a cache stub or a delta,
219            // including when the older delta_explicit preference is enabled.
220            fresh = true;
221        }
222
223        let pressure_action = ctx.pressure_snapshot.as_ref().map(|p| &p.recommendation);
224        let resolved_agent_id = ctx.agent_id.as_ref().and_then(|a| match a.try_read() {
225            Ok(guard) => guard.clone(),
226            Err(_) => None,
227        });
228        let gate_result = if pinned_mode {
229            crate::server::context_gate::pre_dispatch_pinned_read_for_agent(
230                path,
231                &mode,
232                resolved_agent_id.as_deref(),
233            )
234        } else {
235            crate::server::context_gate::pre_dispatch_read_for_agent(
236                path,
237                &mode,
238                task_ref,
239                Some(&ctx.project_root),
240                pressure_action,
241                resolved_agent_id.as_deref(),
242                fresh,
243            )
244        };
245        let mut engine_policy_admission = engine::admission_or_reject(
246            engine_interface_v1,
247            &gate_result,
248            &mode,
249            &ctx.project_root,
250            path,
251        )?;
252        let budget_warning = gate_result.budget_warning.clone();
253        // #513: an explicit raw/verbatim request is never silently downgraded by
254        // the budget gate — the caller asked for exact bytes.
255        let mut mode_override_note: Option<String> = None;
256        if mode != "raw"
257            && let Some(overridden) = gate_result.overridden_mode
258        {
259            if explicit_mode {
260                let reason = gate_result.reason.unwrap_or("context-gate");
261                // #1588: an override the caller cannot escape is a dead end.
262                // Name the escape hatch for the two heuristics that honour it.
263                let escape = if matches!(reason, "bounce-prevention" | "intent-target") {
264                    ", pass fresh=true to keep the requested mode"
265                } else {
266                    ""
267                };
268                mode_override_note = Some(format!(
269                    "[mode overridden: {mode} -> {overridden}, reason={reason}{escape}]"
270                ));
271            }
272            mode = overridden;
273        }
274
275        let (instruction_mode, instruction_mode_note) = resolve_instruction_file_mode(path, &mode);
276        let (mut mode, degrade_warning) =
277            if instruction_mode_note.is_some() || instruction_mode != mode {
278                (instruction_mode, None)
279            } else if pinned_mode
280                || mode == "raw"
281                || mode.starts_with("anchored")
282                || mode.starts_with("lines:")
283            {
284                // #513: raw bypasses context-pressure degradation (which would
285                // otherwise downgrade to signatures under Block), exactly like
286                // instruction files — explicit lossless modes mean lossless.
287                (mode, None)
288            } else {
289                auto_degrade_read_mode(&mode)
290            };
291        engine::require_aggressive(
292            engine_interface_v1,
293            &mode,
294            &ctx.project_root,
295            path,
296            &mut engine_policy_admission,
297        )?;
298
299        // Delta-aware explicit re-reads (opt-in: config `delta_explicit`, env
300        // LCTX_DELTA_EXPLICIT). Re-requesting full/lines:N-M content for a file
301        // this session already read re-emits content the model already holds;
302        // when the file changed on disk, a diff carries the same information in
303        // a fraction of the tokens, and an unchanged lines: request of a
304        // fully-delivered file collapses to the full-mode stub. The decision is
305        // a pure function of (cache, path, mode) — see
306        // `ctx_read::resolve_explicit_delta_mode`. First reads are unaffected;
307        // fresh=true always bypasses. Runs BEFORE the lines:→fresh guard below
308        // so a changed-file lines: re-read can still be diverted to a diff.
309        let mut delta_explicit_note: Option<String> = None;
310        if !fresh
311            && explicit_mode
312            && (mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
313            && crate::core::config::Config::load().delta_explicit_effective()
314            && let Ok(cache) = cache_lock.try_read()
315        {
316            let decision = crate::tools::ctx_read::resolve_explicit_delta_mode(
317                &cache,
318                path,
319                &mode,
320                explicit_mode,
321                fresh,
322                true,
323            );
324            mode = decision.mode;
325            delta_explicit_note = decision.note;
326        }
327
328        if mode.starts_with("lines:") {
329            fresh = true;
330        }
331
332        engine::reject_non_text_extension(
333            engine_interface_v1,
334            &ctx.project_root,
335            path,
336            &mut engine_policy_admission,
337        )?;
338        if crate::core::binary_detect::is_llm_viewable_image(path) {
339            // Text detectors cannot inspect pixels: the gateway says so, and
340            // withholds the image where every detector is mandatory.
341            let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
342            let note = crate::core::context_admission::admit_media(path, bytes)
343                .map_err(|error| ErrorData::invalid_params(error.to_string(), None))?;
344            return read_image_file(path).map(|mut output| {
345                if let (Some(note), Some(blocks)) = (note, output.content_blocks.as_mut()) {
346                    blocks.push(rmcp::model::ContentBlock::text(note));
347                }
348                PreparedRead {
349                    output,
350                    delivery: None,
351                }
352            });
353        }
354        if !engine_interface_v1 && crate::core::binary_detect::is_binary_file(path) {
355            let msg = crate::core::binary_detect::binary_file_message(path);
356            return Err(ErrorData::invalid_params(msg, None));
357        }
358        if !engine_interface_v1 {
359            let cap = crate::core::limits::max_read_bytes() as u64;
360            if let Ok(meta) = std::fs::metadata(path)
361                && meta.len() > cap
362            {
363                let msg = format!(
364                    "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
365                     Use mode=\"lines:1-100\" or start_line+limit for partial reads, \
366                     mode=\"anchored\" with start_line+limit for edit-ready windows, \
367                     or increase the limit.",
368                    meta.len(),
369                    cap
370                );
371                return Err(ErrorData::invalid_params(msg, None));
372            }
373        }
374
375        // Compaction-aware: if host compacted since last check, reset delivery flags
376        // so post-compaction reads deliver full content instead of stubs.
377        if !fresh
378            && let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir()
379            && let Ok(mut cache) = cache_lock.try_write()
380        {
381            crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
382        }
383
384        // Fast path: if both per-file lock and cache write-lock are immediately
385        // available, execute inline without spawning a thread. This avoids thread +
386        // channel overhead for the ~90% of calls that are cache hits.
387        let read_timeout = std::time::Duration::from_secs(30);
388        let cancelled = Arc::new(AtomicBool::new(false));
389        let engine_snapshot = engine::SourceSnapshot::default();
390        let pending_cache = Arc::new(Mutex::new(PendingCacheDelivery::default()));
391        // Hash once for cross-agent delivery (avoids re-reading on record).
392        let delivery_metadata = (!engine_interface_v1
393            && crate::core::config::Config::load().ocla.delivery_enabled())
394        .then(|| crate::tools::ctx_read::file_blake3_prefix(path))
395        .flatten();
396        let (output, resolved_mode, original, is_cache_hit, file_ref, _cache_stats, reuse_outcome) = {
397            let crp_mode = ctx.crp_mode;
398            let fast_result = 'fast: {
399                let file_lock = per_file_lock(path);
400                let Some(_file_guard) = file_lock.try_lock().ok() else {
401                    break 'fast None;
402                };
403
404                // Phase 1 (shared lock): the dominant case is re-reading an
405                // unchanged file. Serve the `[unchanged]` stub under a *read* lock
406                // so parallel reads of distinct files run concurrently instead of
407                // serializing on the global write lock. `auto` is included because
408                // a warm `auto` re-read of a fully-delivered file resolves to a
409                // full cache-hit; `try_stub_hit_readonly` self-guards (returns None
410                // unless full content was delivered and the file is unchanged), so a
411                // first or compressed-only `auto` read still falls through to
412                // Phase 2. When aggressiveness is set `mode` was already rewritten
413                // to `density:` upstream, so it never reaches this `auto` branch.
414                if !fresh
415                    && (mode == "full" || mode == "full-compact" || mode == "auto")
416                    && let Ok(cache) = cache_lock.try_read()
417                    && let Some(read_output) =
418                        crate::tools::ctx_read::try_stub_hit_readonly(&cache, path)
419                {
420                    let hit = read_output.is_cache_hit;
421                    let content = read_output.content;
422                    let rmode = read_output.resolved_mode;
423                    let orig = cache.get(path).map_or(0, |e| e.original_tokens);
424                    let fref = cache.file_ref_map().get(path).cloned();
425                    let stats = cache.get_stats();
426                    let stats_snapshot = (stats.total_reads(), stats.cache_hits());
427                    break 'fast Some((
428                        content,
429                        rmode,
430                        orig,
431                        hit,
432                        fref,
433                        stats_snapshot,
434                        ReuseOutcome::UnchangedStub,
435                    ));
436                }
437
438                // Misses use the slow path's double-check sequence: it does a
439                // second cache check, computes without the global lock, then
440                // briefly takes a write lock to store the result.
441                None
442            };
443
444            if let Some(result) = fast_result {
445                result
446            } else {
447                let cache_lock = cache_lock.clone();
448                let mode = mode.clone();
449                let task_owned = current_task.clone();
450                let protect_owned = protect.clone();
451                let path_owned = path.to_string();
452                let project_root_owned = ctx.project_root.clone();
453                let cancel_flag = cancelled.clone();
454                let snapshot_worker = engine_snapshot.clone();
455                let pending_cache_worker = pending_cache.clone();
456                let (tx, rx) = std::sync::mpsc::sync_channel(1);
457                crate::core::task_spine::TaskSpine::spawn_thread(move || {
458                    let file_lock = per_file_lock(&path_owned);
459
460                    let _file_guard = {
461                        let deadline =
462                            std::time::Instant::now() + std::time::Duration::from_secs(25);
463                        loop {
464                            if cancel_flag.load(Ordering::Relaxed) {
465                                return;
466                            }
467                            if let Ok(guard) = file_lock.try_lock() {
468                                break guard;
469                            }
470                            if std::time::Instant::now() >= deadline {
471                                tracing::error!(
472                                    "ctx_read: per-file lock timeout after 25s for {path_owned}"
473                                );
474                                let _ = tx.send((
475                                    format!("per-file lock contention for {path_owned} — retry in a moment"),
476                                    "error".to_string(),
477                                    0,
478                                    false,
479                                    None,
480                                    (0, 0),
481                                    ReuseOutcome::Cold,
482                                ));
483                                return;
484                            }
485                            std::thread::sleep(std::time::Duration::from_millis(50));
486                        }
487                    };
488
489                    if cancel_flag.load(Ordering::Relaxed) {
490                        return;
491                    }
492
493                    // ── Two-Phase Read (#1098) ──────────────────────────
494                    //
495                    // Phase 1 (read lock): try the [unchanged] stub — this is the
496                    // ~70% case (repeated reads of unchanged files). Previously
497                    // missing in the slow path, forcing every slow-path call into
498                    // the expensive write-lock branch.
499                    if !fresh
500                        && (mode == "full" || mode == "full-compact" || mode == "auto")
501                        && let Ok(cache) = cache_lock.try_read()
502                        && let Some(read_output) =
503                            crate::tools::ctx_read::try_stub_hit_readonly(&cache, &path_owned)
504                    {
505                        let content = read_output.content;
506                        let rmode = read_output.resolved_mode;
507                        let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
508                        let hit = true;
509                        let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
510                        let stats = cache.get_stats();
511                        let stats_snapshot = (stats.total_reads(), stats.cache_hits());
512                        let _ = tx.send((
513                            content,
514                            rmode,
515                            orig,
516                            hit,
517                            fref,
518                            stats_snapshot,
519                            ReuseOutcome::UnchangedStub,
520                        ));
521                        return;
522                    }
523
524                    // The session-local stub is checked first so the current
525                    // agent's own delivery always wins. On a miss, a verified
526                    // cross-agent delivery can avoid the disk read below.
527                    if !crate::tools::ctx_read::effective_fresh_for_delivery(fresh)
528                        && let Some(fp) = delivery_metadata
529                        && let Some(read_output) = crate::tools::ctx_read::try_cross_agent_stub(
530                            &path_owned,
531                            &mode,
532                            fp.hash,
533                            fp.mtime,
534                            crp_mode,
535                            crate::tools::ctx_read::ReadTuning::resolve(
536                                aggressiveness,
537                                &protect_owned,
538                            ),
539                        )
540                    {
541                        let _ = tx.send((
542                            read_output.content,
543                            read_output.resolved_mode,
544                            0,
545                            read_output.is_cache_hit,
546                            None,
547                            (0, 0),
548                            ReuseOutcome::CrossFileRef,
549                        ));
550                        return;
551                    }
552
553                    // Phase 2a: disk I/O under per-file lock but WITHOUT cache lock.
554                    let preread = match engine::read_source(
555                        engine_interface_v1,
556                        &path_owned,
557                        &project_root_owned,
558                        &snapshot_worker,
559                    ) {
560                        Ok(c) => Some(c),
561                        Err(e) => {
562                            tracing::warn!("ctx_read: cannot read {path_owned}: {e}");
563                            if engine_interface_v1 {
564                                let _ = tx.send((
565                                    "Engine v1 source read failed".to_owned(),
566                                    "error".into(),
567                                    0,
568                                    false,
569                                    None,
570                                    (0, 0),
571                                    ReuseOutcome::Cold,
572                                ));
573                                return;
574                            }
575                            None
576                        }
577                    };
578
579                    if cancel_flag.load(Ordering::Relaxed) {
580                        return;
581                    }
582
583                    // ── Phase 2b: Three-sub-phase read (#807) ──────────
584                    //
585                    // Previously held the global cache write-lock for the
586                    // entire computation (tree-sitter, entropy compression).
587                    // For large files this caused 30+ second lock holds and
588                    // cascading timeouts for all concurrent tool calls.
589                    //
590                    // New: prepare (brief lock) → compute (no lock) → store (brief lock).
591
592                    // #1590: an inferred task never steers a lossy view.
593                    let task_ref = if task_is_inferred {
594                        None
595                    } else {
596                        task_owned.as_deref()
597                    };
598                    let tuning =
599                        crate::tools::ctx_read::ReadTuning::resolve(aggressiveness, &protect_owned);
600
601                    // Helper: acquire write lock with deadline. `None` means the
602                    // lock stayed contended past the deadline; callers degrade
603                    // to an uncached read instead of failing it (#1925).
604                    macro_rules! acquire_write {
605                        ($deadline_secs:expr, $label:expr) => {{
606                            let deadline =
607                                std::time::Instant::now() + cache_lock_deadline($deadline_secs);
608                            loop {
609                                if cancel_flag.load(Ordering::Relaxed) {
610                                    return;
611                                }
612                                if let Ok(guard) = cache_lock.try_write() {
613                                    break Some(guard);
614                                }
615                                if std::time::Instant::now() >= deadline {
616                                    tracing::warn!(
617                                        "ctx_read: cache write-lock timeout ({}) for {path_owned}, \
618                                         serving uncached",
619                                        $label,
620                                    );
621                                    break None;
622                                }
623                                std::thread::sleep(std::time::Duration::from_millis(50));
624                            }
625                        }};
626                    }
627
628                    // Work that needs no cache state runs before the write lock
629                    // (#1925). The first `count_tokens` call builds the BPE tables
630                    // (seconds in debug builds); done under the lock it starved
631                    // every concurrent read into the deadline. Counting the
632                    // preread here also turns the count inside `cache.store()`
633                    // into a token-cache hit.
634                    let preread_tokens = preread.as_deref().map(crate::core::tokens::count_tokens);
635                    let mode_eff = if mode != "raw"
636                        && !mode.starts_with("lines:")
637                        && crate::core::config::Config::load()
638                            .proxy
639                            .is_path_compress_protected(&path_owned)
640                    {
641                        "full".to_string()
642                    } else {
643                        mode.clone()
644                    };
645
646                    // 2b-i: Brief write lock — prepare cache state, resolve
647                    // mode, check for hits. Sub-millisecond: HashMap lookups,
648                    // staleness checks, raw-content storage for new files.
649                    let (outcome, source_identity) = 'prepare: {
650                        let Some(mut cache) = acquire_write!(10, "prepare 10s") else {
651                            match prepare_uncached(
652                                preread,
653                                preread_tokens,
654                                &path_owned,
655                                &mode_eff,
656                                &tuning,
657                                task_ref,
658                            ) {
659                                Ok(uncached) => break 'prepare (uncached, None),
660                                Err(msg) => {
661                                    let _ = tx.send((
662                                        msg,
663                                        "error".into(),
664                                        0,
665                                        false,
666                                        None,
667                                        (0, 0),
668                                        ReuseOutcome::Cold,
669                                    ));
670                                    return;
671                                }
672                            }
673                        };
674                        let mut reuse_outcome = if cache_policy_bypassed {
675                            ReuseOutcome::PolicyBypass
676                        } else if fresh {
677                            ReuseOutcome::FreshBypass
678                        } else {
679                            ReuseOutcome::Cold
680                        };
681
682                        let file_ref = cache.get_file_ref(&path_owned);
683
684                        let effective_fresh = fresh
685                            || crate::tools::ctx_read::force_fresh_env()
686                            || (crate::tools::ctx_read::is_subagent_context()
687                                && !crate::core::conversation::scope_enabled());
688
689                        if effective_fresh {
690                            cache.invalidate(&path_owned);
691                        }
692
693                        if !effective_fresh {
694                            // #1584: `diff` is the one mode for which a stale
695                            // entry is the *point* — it holds the baseline the
696                            // delta is computed against. Dropping it here left
697                            // `handle_diff` with nothing to compare and made
698                            // every post-edit diff answer "no cached version".
699                            // Every other mode still refuses to serve content
700                            // that no longer matches the file on disk.
701                            let stale = mode_eff != "diff"
702                                && cache.get(&path_owned).is_some_and(|e| {
703                                    crate::core::cache::is_cache_entry_stale_verified(
704                                        &path_owned,
705                                        e.stored_mtime,
706                                        &e.hash,
707                                    )
708                                });
709                            if stale {
710                                cache.invalidate(&path_owned);
711                                reuse_outcome = ReuseOutcome::Stale;
712                            }
713                        }
714
715                        let snap = cache
716                            .get(&path_owned)
717                            .map(|e| (e.original_tokens, e.content()));
718
719                        // #1584: `diff` is a delta view, not a whole-file
720                        // render. It needs the cached baseline and has no arm in
721                        // `process_mode_tuned`, so letting it fall through to the
722                        // generic compute path made the MCP handler answer
723                        // "[WARNING: unknown mode 'diff']" and return the entire
724                        // file — while the CLI path handled it correctly. Both
725                        // paths now share `handle_diff`.
726                        let outcome = if mode_eff == "diff" {
727                            let (out, _sent, baseline) = if fresh {
728                                let warning = "[warning] fresh+diff is redundant — fresh invalidates the cache, so no baseline is left to diff against. Use mode=full with fresh=true instead.";
729                                (
730                                    warning.to_string(),
731                                    crate::core::tokens::count_tokens(warning),
732                                    None,
733                                )
734                            } else {
735                                crate::tools::ctx_read::prepare_diff(&cache, &path_owned, &file_ref)
736                            };
737                            let out = crate::core::redaction::redact_text_if_enabled(&out);
738                            let orig = baseline.as_deref().map_or_else(
739                                || cache.get(&path_owned).map_or(0, |e| e.original_tokens),
740                                crate::core::tokens::count_tokens,
741                            );
742                            pending_cache_worker
743                                .lock()
744                                .unwrap_or_else(std::sync::PoisonError::into_inner)
745                                .diff_baseline = baseline;
746                            let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
747                            let s = cache.get_stats();
748                            PrepareOutcome::Hit(
749                                out,
750                                "diff".to_string(),
751                                orig,
752                                false,
753                                fref,
754                                (s.total_reads(), s.cache_hits()),
755                                reuse_outcome,
756                            )
757                        } else if let Some((orig_tok, content_opt)) = snap {
758                            let resolved = if mode_eff == "auto" {
759                                tuning.auto_density_mode().unwrap_or_else(|| {
760                                    crate::tools::ctx_read::resolve_auto_mode(
761                                        Some(&cache),
762                                        &path_owned,
763                                        orig_tok,
764                                        None,
765                                        task_ref,
766                                    )
767                                })
768                            } else {
769                                mode_eff
770                            };
771
772                            if (resolved == "full" || resolved == "full-compact")
773                                && let Some(out) = crate::tools::ctx_read::try_stub_hit_readonly(
774                                    &cache,
775                                    &path_owned,
776                                )
777                            {
778                                let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
779                                let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
780                                let s = cache.get_stats();
781                                PrepareOutcome::Hit(
782                                    out.content,
783                                    out.resolved_mode,
784                                    orig,
785                                    true,
786                                    fref,
787                                    (s.total_reads(), s.cache_hits()),
788                                    ReuseOutcome::UnchangedStub,
789                                )
790                            } else if crate::tools::ctx_read::is_cacheable_mode(&resolved) {
791                                let ck = crate::tools::ctx_read::request_scoped_key(
792                                    crate::tools::ctx_read::compressed_cache_key(
793                                        &resolved,
794                                        crp_mode,
795                                        task_ref,
796                                        tuning.aggressiveness,
797                                        tuning.protect,
798                                    ),
799                                    mode == "auto",
800                                );
801                                if let Some(hit) = cache.get_compressed(&path_owned, &ck).cloned() {
802                                    crate::core::auto_mode_resolver::count_source(
803                                        "compressed_cache_hit",
804                                    );
805                                    let hit = crate::core::redaction::redact_text_if_enabled(&hit);
806                                    let orig =
807                                        cache.get(&path_owned).map_or(0, |e| e.original_tokens);
808                                    let fref =
809                                        cache.file_ref_map().get(path_owned.as_str()).cloned();
810                                    let s = cache.get_stats();
811                                    PrepareOutcome::Hit(
812                                        hit,
813                                        resolved,
814                                        orig,
815                                        true,
816                                        fref,
817                                        (s.total_reads(), s.cache_hits()),
818                                        ReuseOutcome::RenderCacheHit,
819                                    )
820                                } else {
821                                    if reuse_outcome == ReuseOutcome::Cold
822                                        && cache.was_compressed_variant_evicted(&path_owned, &ck)
823                                    {
824                                        reuse_outcome = ReuseOutcome::VariantEvicted;
825                                    }
826                                    let c = content_opt
827                                        .or_else(|| preread.as_deref().map(String::from));
828                                    PrepareOutcome::Compute {
829                                        file_ref,
830                                        resolved_mode: resolved,
831                                        content: c.unwrap_or_default(),
832                                        original_tokens: orig_tok,
833                                        reuse_outcome,
834                                        cacheable: true,
835                                    }
836                                }
837                            } else {
838                                let c =
839                                    content_opt.or_else(|| preread.as_deref().map(String::from));
840                                PrepareOutcome::Compute {
841                                    file_ref,
842                                    resolved_mode: resolved,
843                                    content: c.unwrap_or_default(),
844                                    original_tokens: orig_tok,
845                                    reuse_outcome,
846                                    cacheable: true,
847                                }
848                            }
849                        } else {
850                            let raw = match preread {
851                                Some(c) if !c.is_empty() => c,
852                                _ => match crate::tools::ctx_read::read_file_lossy(&path_owned) {
853                                    Ok(c) if !c.is_empty() => c,
854                                    Ok(_) => {
855                                        tracing::debug!(
856                                            "ctx_read: skipping cache for empty content: {path_owned}"
857                                        );
858                                        let _ = tx.send((
859                                            format!("File is empty: {path_owned}"),
860                                            "error".into(),
861                                            0,
862                                            false,
863                                            None,
864                                            (0, 0),
865                                            ReuseOutcome::Cold,
866                                        ));
867                                        return;
868                                    }
869                                    Err(e) => {
870                                        tracing::debug!(
871                                            "ctx_read: skipping cache for empty content: {path_owned}"
872                                        );
873                                        let _ = tx.send((
874                                            format!("Cannot read file: {path_owned}: {e}"),
875                                            "error".into(),
876                                            0,
877                                            false,
878                                            None,
879                                            (0, 0),
880                                            ReuseOutcome::Cold,
881                                        ));
882                                        return;
883                                    }
884                                },
885                            };
886                            let sr = cache.store(&path_owned, &raw);
887                            let resolved = if mode_eff == "auto" {
888                                tuning.auto_density_mode().unwrap_or_else(|| {
889                                    crate::tools::ctx_read::resolve_auto_mode(
890                                        None,
891                                        &path_owned,
892                                        sr.original_tokens,
893                                        Some(sr.line_count),
894                                        task_ref,
895                                    )
896                                })
897                            } else {
898                                mode_eff
899                            };
900                            PrepareOutcome::Compute {
901                                file_ref,
902                                resolved_mode: resolved,
903                                content: raw,
904                                original_tokens: sr.original_tokens,
905                                reuse_outcome,
906                                cacheable: true,
907                            }
908                        };
909                        let identity = cache.get(&path_owned).map(CacheSourceIdentity::from_entry);
910                        (outcome, identity)
911                    }; // write lock released
912
913                    if let PrepareOutcome::Hit(c, rm, orig, hit, fref, ss, reuse_outcome) = outcome
914                    {
915                        // Update last_mode for compressed-cache hits so the auto-mode
916                        // resolver can reuse this mode on future re-reads (#E26).
917                        let mut pending = pending_cache_worker
918                            .lock()
919                            .unwrap_or_else(std::sync::PoisonError::into_inner);
920                        let diff_baseline = pending.diff_baseline.take();
921                        *pending = PendingCacheDelivery {
922                            identity: source_identity,
923                            last_mode: Some(rm.clone()),
924                            diff_baseline,
925                            ..PendingCacheDelivery::default()
926                        };
927                        let _ = tx.send((c, rm, orig, hit, fref, ss, reuse_outcome));
928                        return;
929                    }
930                    let PrepareOutcome::Compute {
931                        file_ref,
932                        resolved_mode,
933                        content: compute_content,
934                        original_tokens,
935                        reuse_outcome,
936                        cacheable,
937                    } = outcome
938                    else {
939                        unreachable!()
940                    };
941
942                    if cancel_flag.load(Ordering::Relaxed) {
943                        return;
944                    }
945
946                    // 2b-ii: Heavy computation WITHOUT cache lock.
947                    // Tree-sitter, entropy compression, mode rendering all
948                    // run under the per-file mutex only (serializes same-file
949                    // reads, but does not block other files or tool calls).
950                    let short = crate::core::protocol::shorten_path(&path_owned);
951                    let ext_s = std::path::Path::new(&*path_owned)
952                        .extension()
953                        .and_then(|e| e.to_str())
954                        .unwrap_or("");
955
956                    let source_hash = blake3::hash(compute_content.as_bytes());
957                    let mut source_fingerprint = [0u8; 12];
958                    source_fingerprint.copy_from_slice(&source_hash.as_bytes()[..12]);
959                    let (mut computed, rmode) = if resolved_mode == "full"
960                        || resolved_mode == "full-compact"
961                    {
962                        if resolved_mode == "full-compact" {
963                            let (out, _) = crate::tools::ctx_read::format_full_compact_output(
964                                &compute_content,
965                            );
966                            (out, "full-compact".to_string())
967                        } else {
968                            let lc = compute_content.lines().count();
969                            let (out, _) = crate::tools::ctx_read::format_full_output(
970                                &file_ref,
971                                &short,
972                                ext_s,
973                                &compute_content,
974                                original_tokens,
975                                lc,
976                                task_ref,
977                            );
978                            let ft = crate::core::tokens::count_tokens(&out);
979                            let out = crate::tools::ctx_read::cap_to_raw(
980                                out,
981                                ft,
982                                &compute_content,
983                                original_tokens,
984                                "full",
985                            );
986                            (out, "full".to_string())
987                        }
988                    } else {
989                        // #1910: a fallback inside an `auto` read returns the
990                        // bare file, bannerless.
991                        let _auto_guard = (mode == "auto")
992                            .then(crate::tools::ctx_read::render::AutoRequestGuard::new);
993                        let (out, _) = crate::tools::ctx_read::process_mode_tuned(
994                            &compute_content,
995                            &resolved_mode,
996                            &file_ref,
997                            &short,
998                            ext_s,
999                            original_tokens,
1000                            crp_mode,
1001                            &path_owned,
1002                            task_ref,
1003                            tuning,
1004                        );
1005                        let out = if crate::tools::ctx_read::mode_allows_raw_cap(&resolved_mode) {
1006                            let ft = crate::core::tokens::count_tokens(&out);
1007                            crate::tools::ctx_read::cap_to_raw(
1008                                out,
1009                                ft,
1010                                &compute_content,
1011                                original_tokens,
1012                                &resolved_mode,
1013                            )
1014                        } else {
1015                            out
1016                        };
1017                        (out, resolved_mode)
1018                    };
1019
1020                    computed = crate::core::redaction::redact_text_if_enabled(&computed);
1021                    if let Some(note) = crate::core::context_admission::note_for(&compute_content) {
1022                        computed.push('\n');
1023                        computed.push_str(&note);
1024                    }
1025
1026                    if cancel_flag.load(Ordering::Relaxed) {
1027                        return;
1028                    }
1029
1030                    // Warming source bytes is acquisition; variants/full flags imply
1031                    // delivery and are committed only if this result is included.
1032                    // An uncached fallback (`F?` ref, #1925) never feeds the cache.
1033                    let compressed_variant = (cacheable
1034                        && crate::tools::ctx_read::is_cacheable_mode(&rmode))
1035                    .then(|| {
1036                        // #1910: an `auto` request's fallback is bannerless, an
1037                        // explicit one is not — they must never share a variant.
1038                        let key = crate::tools::ctx_read::request_scoped_key(
1039                            crate::tools::ctx_read::compressed_cache_key(
1040                                &rmode,
1041                                crp_mode,
1042                                task_ref,
1043                                tuning.aggressiveness,
1044                                tuning.protect,
1045                            ),
1046                            mode == "auto",
1047                        );
1048                        (key, computed.clone())
1049                    });
1050                    *pending_cache_worker
1051                        .lock()
1052                        .unwrap_or_else(std::sync::PoisonError::into_inner) =
1053                        PendingCacheDelivery {
1054                            identity: source_identity,
1055                            compressed_variant,
1056                            full_content: cacheable
1057                                && matches!(rmode.as_str(), "full" | "full-compact"),
1058                            source_fingerprint: Some(source_fingerprint),
1059                            last_mode: cacheable.then(|| rmode.clone()),
1060                            record_bounce_read: true,
1061                            diff_baseline: None,
1062                        };
1063                    let _ = tx.send((
1064                        computed,
1065                        rmode,
1066                        original_tokens,
1067                        false,
1068                        Some(file_ref),
1069                        (0, 0),
1070                        reuse_outcome,
1071                    ));
1072                });
1073                if let Ok(result) = rx.recv_timeout(read_timeout) {
1074                    result
1075                } else {
1076                    cancelled.store(true, Ordering::Relaxed);
1077                    tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
1078                    let msg = format!(
1079                        "ERROR: ctx_read timed out after {}s reading {path}. \
1080                     The file may be very large or a blocking I/O issue occurred. \
1081                     Try mode=\"lines:1-100\" for a partial read.",
1082                        read_timeout.as_secs()
1083                    );
1084                    return Err(ErrorData::internal_error(msg, None));
1085                }
1086            } // end else (slow path)
1087        };
1088
1089        engine::reject_read_failure_if_enabled(
1090            engine_interface_v1,
1091            &resolved_mode,
1092            &ctx.project_root,
1093            path,
1094            &mut engine_policy_admission,
1095        )?;
1096        engine::require_aggressive(
1097            engine_interface_v1,
1098            &resolved_mode,
1099            &ctx.project_root,
1100            path,
1101            &mut engine_policy_admission,
1102        )?;
1103        if resolved_mode == "error" {
1104            return Err(ErrorData::invalid_params(output, None));
1105        }
1106
1107        let mut output = output;
1108        // Raw and receipt-backed contracts retain their exact payload. Only a
1109        // newly acquired source can produce a current optional Pro hint.
1110        let code_hint = if !engine_interface_v1 && resolved_mode != "raw" && !is_cache_hit {
1111            engine_snapshot.code_hint(path)
1112        } else {
1113            None
1114        };
1115        let engine_warning = engine_snapshot.record_if_enabled(
1116            &ctx.project_root,
1117            engine_policy_admission,
1118            &mut output,
1119        );
1120        let output_tokens = crate::core::tokens::count_tokens(&output);
1121
1122        let cache_delivery = std::mem::take(
1123            &mut *pending_cache
1124                .lock()
1125                .unwrap_or_else(std::sync::PoisonError::into_inner),
1126        );
1127        // A pre-read disk hash may describe older bytes. Relay only when it
1128        // agrees with the source that actually supplied this rendered result.
1129        let cross_agent = if is_cache_hit {
1130            None
1131        } else {
1132            delivery_metadata
1133                .filter(|fp| cache_delivery.source_fingerprint.as_ref() == Some(&fp.hash))
1134                .map(|fp| {
1135                    let relay_key = (matches!(resolved_mode.as_str(), "map" | "signatures")
1136                        && output.len() <= 8192)
1137                        .then(|| {
1138                            crate::tools::ctx_read::compressed_cache_key(
1139                                &resolved_mode,
1140                                ctx.crp_mode,
1141                                None,
1142                                aggressiveness,
1143                                &protect,
1144                            )
1145                        });
1146                    PendingCrossAgentDelivery {
1147                        hash: fp.hash,
1148                        mtime: fp.mtime,
1149                        line_count: fp.line_count,
1150                        output_tokens,
1151                        output: output.clone(),
1152                        relay_key,
1153                    }
1154                })
1155        };
1156
1157        // #1098: graph-related hints (callers/callees) are now computed AFTER the
1158        // cache lock is released. They involve SQLite queries (~50-200ms) that
1159        // previously blocked all parallel reads while holding the write lock.
1160        let graph_hint = if !is_cache_hit
1161            && !resolved_mode.starts_with("lines:")
1162            && crate::core::profiles::active_profile()
1163                .output_hints
1164                .related_hint()
1165        {
1166            crate::tools::ctx_read::graph_related_hint(path)
1167        } else {
1168            None
1169        };
1170
1171        // Cross-source hints: gated by profile `cross_source_hint` (default off).
1172        // When enabled, appends issue/PR/schema references from the property
1173        // graph. Skipped when graph.db doesn't exist (#682).
1174        // Legacy graph edges carry no source authority for protected reuse.
1175        let hints_suffix = if crate::core::profiles::active_profile()
1176            .output_hints
1177            .cross_source_hint()
1178            && !crate::core::policy::runtime::is_active()
1179        {
1180            let graph_db =
1181                crate::core::property_graph::graph_dir(&ctx.project_root).join("graph.db");
1182            let graph = graph_db
1183                .exists()
1184                .then(|| crate::core::property_graph::CodeGraph::open(&ctx.project_root))
1185                .transpose()
1186                .ok()
1187                .flatten();
1188            graph.map_or_else(String::new, |graph| {
1189                let edges = graph.all_cross_source_edges();
1190                if edges.is_empty() {
1191                    String::new()
1192                } else {
1193                    let ranges = scoped_read_ranges(&resolved_mode);
1194                    let relative_path =
1195                        crate::core::graph_index::graph_relative_key(path, &ctx.project_root);
1196                    let hints = crate::core::cross_source_hints::hints_for_file_matching(
1197                        path,
1198                        &edges,
1199                        &ctx.project_root,
1200                        |hint| {
1201                            ranges.as_ref().is_none_or(|ranges| {
1202                                hint_intersects_ranges(hint, ranges, &graph, &relative_path)
1203                            })
1204                        },
1205                    );
1206                    crate::core::cross_source_hints::format_hints(&hints)
1207                }
1208            })
1209        } else {
1210            String::new()
1211        };
1212
1213        // Rule injection (#1325): discover and append rules scoped to this file
1214        // path (CLAUDE.md, AGENTS.md, .cursor/rules, .claude/rules) so the agent
1215        // receives the same context it would get from the native Read tool.
1216        let rules_suffix = {
1217            let client_id = ctx
1218                .client_name
1219                .as_ref()
1220                .map(|c| c.blocking_read().clone())
1221                .unwrap_or_default();
1222            crate::core::rule_discovery::rules_suffix_for_read(path, &ctx.project_root, &client_id)
1223        };
1224        let mut warnings: Vec<&str> = engine_warning.as_deref().into_iter().collect();
1225        if let Some(ref w) = budget_warning {
1226            warnings.push(w.as_str());
1227        }
1228        if let Some(ref w) = degrade_warning {
1229            warnings.push(w.as_str());
1230        }
1231        if let Some(ref w) = delta_explicit_note {
1232            warnings.push(w.as_str());
1233        }
1234        if let Some(ref w) = mode_override_note {
1235            warnings.push(w.as_str());
1236        }
1237        if let Some(ref w) = instruction_mode_note {
1238            warnings.push(w.as_str());
1239        }
1240        let file_summary = extract_file_summary(&output, path);
1241        let graph_suffix = graph_hint.map(|h| format!("\n{h}")).unwrap_or_default();
1242        // #977: notices (mode override, budget, degradation, delta) go BEFORE the
1243        // payload so client-side truncation of large outputs cannot hide them.
1244        let final_output = if !warnings.is_empty() {
1245            format!(
1246                "{}\n\n{output}{hints_suffix}{graph_suffix}{rules_suffix}",
1247                warnings.join("\n")
1248            )
1249        } else if hints_suffix.is_empty() && graph_suffix.is_empty() && rules_suffix.is_empty() {
1250            output
1251        } else {
1252            format!("{output}{hints_suffix}{graph_suffix}{rules_suffix}")
1253        };
1254        // Proactive context: gated by profile `proactive_context` (default off).
1255        // When enabled, auto-expands previously compressed content that is
1256        // keyword-relevant to the current read (up to 2000 tokens).
1257        let final_output = if crate::core::profiles::active_profile()
1258            .output_hints
1259            .proactive_context()
1260        {
1261            let proactive_query = format!(
1262                "ctx_read path={path} mode={resolved_mode} task={}",
1263                task_ref.unwrap_or_default()
1264            );
1265            if let Some(block) =
1266                crate::core::relevance_tracker::proactive_context_for_path(&proactive_query, path)
1267            {
1268                format!("{final_output}{block}")
1269            } else {
1270                final_output
1271            }
1272        } else {
1273            final_output
1274        };
1275
1276        // Keep paid annotations outside the pending source/relay cache payload;
1277        // an expired license must never recover an old paid analysis as fresh.
1278        let final_output = match code_hint {
1279            Some(note) => format!("{final_output}\n\n{note}"),
1280            None => final_output,
1281        };
1282
1283        // Monotonic guard (#1326): re-count tokens on the fully assembled output
1284        // (including hints, warnings, proactive context) and verify the compressed
1285        // result is actually smaller than the original. If annotations inflated the
1286        // output beyond the raw baseline, report zero savings so the ledger stays
1287        // honest. We keep the compressed form (it may still be more useful than raw)
1288        // but correct the accounting.
1289        let final_tokens = crate::core::tokens::count_tokens(&final_output);
1290        let verified_saved = original.saturating_sub(final_tokens);
1291
1292        let delivery = PendingReadDelivery {
1293            path: path.to_owned(),
1294            cache_delivery,
1295            cross_agent,
1296            file_ref,
1297            file_summary,
1298            resolved_mode: resolved_mode.clone(),
1299            original_tokens: original,
1300            reuse_outcome,
1301            is_cache_hit,
1302            agent_id: resolved_agent_id,
1303        };
1304        Ok(PreparedRead {
1305            delivery: Some(delivery),
1306            output: ToolOutput {
1307                text: final_output,
1308                original_tokens: original,
1309                saved_tokens: verified_saved,
1310                mode: Some(resolved_mode),
1311                path: Some(path.to_string()),
1312                changed: false,
1313                shell_outcome: None,
1314                content_blocks: None,
1315            },
1316        })
1317    }
1318}
1319
1320#[path = "ctx_read_engine.rs"]
1321mod engine;
1322// #660 LOC gate: the MCP tool definition lives in its own module.
1323#[path = "ctx_read_image.rs"]
1324mod image;
1325#[path = "ctx_read_schema.rs"]
1326mod schema;
1327use image::read_image_file;
1328// #660 LOC gate: leaf helpers live in their own module.
1329#[path = "ctx_read_helpers.rs"]
1330mod helpers;
1331pub(crate) use helpers::task_intent_steers_read;
1332// `apply_verdict`'s only caller in this module is the inline test file, which
1333// reaches it as `super::apply_verdict` — hence the cfg(test) import.
1334#[cfg(test)]
1335use helpers::apply_verdict;
1336use helpers::{auto_degrade_read_mode, extract_file_summary, record_attribution_result};
1337
1338// #660 LOC gate: cache-lock deadline and the uncached fallback (#1925).
1339#[path = "ctx_read_uncached.rs"]
1340mod uncached;
1341use uncached::{PrepareOutcome, cache_lock_deadline, prepare_uncached};
1342
1343#[path = "ctx_read_window.rs"]
1344mod window;
1345// #1993: the batch read resolves `raw=true` the same way.
1346pub(super) use window::resolve_explicit_mode;
1347#[allow(unused_imports)]
1348// lines_mode + resolve_line_window used in #[cfg(test)] ctx_read_inline_tests
1349use window::{
1350    apply_line_window, hint_intersects_ranges, lines_mode, resolve_instruction_file_mode,
1351    resolve_line_window, resolve_raw_alias, scoped_read_ranges,
1352};
1353
1354// #660 LOC gate: inline tests split out to keep this file under the line cap.
1355#[cfg(test)]
1356#[path = "ctx_read_inline_tests.rs"]
1357mod tests;
1358
1359#[cfg(test)]
1360#[path = "ctx_read_security_tests.rs"]
1361mod security_tests;
1362
1363#[cfg(test)]
1364#[path = "ctx_read_gateway_tests.rs"]
1365mod gateway_tests;
1366
1367// #660 LOC gate: repo-param tests split out to keep this file under the line
1368// cap — see `ctx_read_repo_param_tests.rs`.
1369
1370#[cfg(test)]
1371#[path = "ctx_read_repo_param_tests.rs"]
1372mod repo_param_tests;
1373
1374#[cfg(test)]
1375#[path = "ctx_read_override_tests.rs"]
1376mod override_tests;