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 resolved_agent_id = ctx.agent_id.as_ref().and_then(|a| match a.try_read() {
224            Ok(guard) => guard.clone(),
225            Err(_) => None,
226        });
227        let gate_result = if pinned_mode {
228            crate::server::context_gate::pre_dispatch_pinned_read_for_agent(
229                path,
230                &mode,
231                resolved_agent_id.as_deref(),
232            )
233        } else {
234            crate::server::context_gate::pre_dispatch_read_for_agent(
235                path,
236                &mode,
237                task_ref,
238                Some(&ctx.project_root),
239                resolved_agent_id.as_deref(),
240                fresh,
241            )
242        };
243        let mut engine_policy_admission = engine::admission_or_reject(
244            engine_interface_v1,
245            &gate_result,
246            &mode,
247            &ctx.project_root,
248            path,
249        )?;
250        let budget_warning = gate_result.budget_warning.clone();
251        // #513: an explicit raw/verbatim request is never silently downgraded by
252        // the budget gate — the caller asked for exact bytes.
253        let mut mode_override_note: Option<String> = None;
254        if mode != "raw"
255            && let Some(overridden) = gate_result.overridden_mode
256        {
257            if explicit_mode {
258                let reason = gate_result.reason.unwrap_or("context-gate");
259                // #1588: an override the caller cannot escape is a dead end.
260                // Name the escape hatch for the two heuristics that honour it.
261                let escape = if matches!(
262                    reason,
263                    "bounce-prevention" | "intent-target" | "learned-full"
264                ) {
265                    ", pass fresh=true to keep the requested mode"
266                } else {
267                    ""
268                };
269                mode_override_note = Some(format!(
270                    "[mode overridden: {mode} -> {overridden}, reason={reason}{escape}]"
271                ));
272            }
273            mode = overridden;
274        }
275
276        let (instruction_mode, instruction_mode_note) = resolve_instruction_file_mode(path, &mode);
277        let mut mode = instruction_mode;
278        engine::require_aggressive(
279            engine_interface_v1,
280            &mode,
281            &ctx.project_root,
282            path,
283            &mut engine_policy_admission,
284        )?;
285
286        // Delta-aware explicit re-reads (opt-in: config `delta_explicit`, env
287        // LCTX_DELTA_EXPLICIT). Re-requesting full/lines:N-M content for a file
288        // this session already read re-emits content the model already holds;
289        // when the file changed on disk, a diff carries the same information in
290        // a fraction of the tokens, and an unchanged lines: request of a
291        // fully-delivered file collapses to the full-mode stub. The decision is
292        // a pure function of (cache, path, mode) — see
293        // `ctx_read::resolve_explicit_delta_mode`. First reads are unaffected;
294        // fresh=true always bypasses. Runs BEFORE the lines:→fresh guard below
295        // so a changed-file lines: re-read can still be diverted to a diff.
296        let mut delta_explicit_note: Option<String> = None;
297        if !fresh
298            && explicit_mode
299            && (mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
300            && crate::core::config::Config::load().delta_explicit_effective()
301            && let Ok(cache) = cache_lock.try_read()
302        {
303            let decision = crate::tools::ctx_read::resolve_explicit_delta_mode(
304                &cache,
305                path,
306                &mode,
307                explicit_mode,
308                fresh,
309                true,
310            );
311            mode = decision.mode;
312            delta_explicit_note = decision.note;
313        }
314
315        if mode.starts_with("lines:") {
316            fresh = true;
317        }
318
319        engine::reject_non_text_extension(
320            engine_interface_v1,
321            &ctx.project_root,
322            path,
323            &mut engine_policy_admission,
324        )?;
325        // A directory has no text to read; failing with the OS error ("Is a
326        // directory") left the agent guessing. Answer with its entries, as
327        // ctx_tree would, so the next call can name a file.
328        if !engine_interface_v1 && std::path::Path::new(path).is_dir() {
329            let (tree, _) = crate::tools::ctx_tree::handle(path, 1, false, true);
330            if tree.starts_with("ERROR:") {
331                return Err(ErrorData::invalid_params(tree, None));
332            }
333            return Ok(PreparedRead {
334                output: ToolOutput::simple(format!(
335                    "{path} is a directory — pass one of its files to ctx_read:\n{tree}"
336                )),
337                delivery: None,
338            });
339        }
340        if crate::core::binary_detect::is_llm_viewable_image(path) {
341            // Text detectors cannot inspect pixels: the gateway says so, and
342            // withholds the image where every detector is mandatory.
343            let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
344            let note = crate::core::context_admission::admit_media(path, bytes)
345                .map_err(|error| ErrorData::invalid_params(error.to_string(), None))?;
346            return read_image_file(path).map(|mut output| {
347                if let (Some(note), Some(blocks)) = (note, output.content_blocks.as_mut()) {
348                    blocks.push(rmcp::model::ContentBlock::text(note));
349                }
350                PreparedRead {
351                    output,
352                    delivery: None,
353                }
354            });
355        }
356        if !engine_interface_v1 && crate::core::binary_detect::is_binary_file(path) {
357            let msg = crate::core::binary_detect::binary_file_message(path);
358            return Err(ErrorData::invalid_params(msg, None));
359        }
360        if !engine_interface_v1 {
361            let cap = crate::core::limits::max_read_bytes() as u64;
362            if let Ok(meta) = std::fs::metadata(path)
363                && meta.len() > cap
364            {
365                let msg = format!(
366                    "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
367                     Use mode=\"lines:1-100\" or start_line+limit for partial reads, \
368                     mode=\"anchored\" with start_line+limit for edit-ready windows, \
369                     or increase the limit.",
370                    meta.len(),
371                    cap
372                );
373                return Err(ErrorData::invalid_params(msg, None));
374            }
375        }
376
377        // Compaction-aware: if host compacted since last check, reset delivery flags
378        // so post-compaction reads deliver full content instead of stubs.
379        if !fresh
380            && let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir()
381            && let Ok(mut cache) = cache_lock.try_write()
382        {
383            crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
384        }
385
386        // Fast path: if both per-file lock and cache write-lock are immediately
387        // available, execute inline without spawning a thread. This avoids thread +
388        // channel overhead for the ~90% of calls that are cache hits.
389        let read_timeout = std::time::Duration::from_secs(30);
390        let cancelled = Arc::new(AtomicBool::new(false));
391        let engine_snapshot = engine::SourceSnapshot::default();
392        let pending_cache = Arc::new(Mutex::new(PendingCacheDelivery::default()));
393        // Hash once for cross-agent delivery (avoids re-reading on record).
394        let delivery_metadata = (!engine_interface_v1
395            && crate::core::config::Config::load().ocla.delivery_enabled())
396        .then(|| crate::tools::ctx_read::file_blake3_prefix(path))
397        .flatten();
398        let (output, resolved_mode, original, is_cache_hit, file_ref, _cache_stats, reuse_outcome) = {
399            let crp_mode = ctx.crp_mode;
400            let fast_result = 'fast: {
401                let file_lock = per_file_lock(path);
402                let Some(_file_guard) = file_lock.try_lock().ok() else {
403                    break 'fast None;
404                };
405
406                // Phase 1 (shared lock): the dominant case is re-reading an
407                // unchanged file. Serve the `[unchanged]` stub under a *read* lock
408                // so parallel reads of distinct files run concurrently instead of
409                // serializing on the global write lock. `auto` is included because
410                // a warm `auto` re-read of a fully-delivered file resolves to a
411                // full cache-hit; `try_stub_hit_readonly` self-guards (returns None
412                // unless full content was delivered and the file is unchanged), so a
413                // first or compressed-only `auto` read still falls through to
414                // Phase 2. When aggressiveness is set `mode` was already rewritten
415                // to `density:` upstream, so it never reaches this `auto` branch.
416                if !fresh
417                    && (mode == "full" || mode == "full-compact" || mode == "auto")
418                    && let Ok(cache) = cache_lock.try_read()
419                    && let Some(read_output) =
420                        crate::tools::ctx_read::try_stub_hit_readonly(&cache, path)
421                {
422                    let hit = read_output.is_cache_hit;
423                    let content = read_output.content;
424                    let rmode = read_output.resolved_mode;
425                    let orig = cache.get(path).map_or(0, |e| e.original_tokens);
426                    let fref = cache.file_ref_map().get(path).cloned();
427                    let stats = cache.get_stats();
428                    let stats_snapshot = (stats.total_reads(), stats.cache_hits());
429                    break 'fast Some((
430                        content,
431                        rmode,
432                        orig,
433                        hit,
434                        fref,
435                        stats_snapshot,
436                        ReuseOutcome::UnchangedStub,
437                    ));
438                }
439
440                // Misses use the slow path's double-check sequence: it does a
441                // second cache check, computes without the global lock, then
442                // briefly takes a write lock to store the result.
443                None
444            };
445
446            if let Some(result) = fast_result {
447                result
448            } else {
449                let cache_lock = cache_lock.clone();
450                let mode = mode.clone();
451                let task_owned = current_task.clone();
452                let protect_owned = protect.clone();
453                let path_owned = path.to_string();
454                let project_root_owned = ctx.project_root.clone();
455                let cancel_flag = cancelled.clone();
456                let snapshot_worker = engine_snapshot.clone();
457                let pending_cache_worker = pending_cache.clone();
458                let (tx, rx) = std::sync::mpsc::sync_channel(1);
459                crate::core::task_spine::TaskSpine::spawn_thread(move || {
460                    let file_lock = per_file_lock(&path_owned);
461
462                    // The per-file lock only deduplicates concurrent reads of
463                    // one file. When an earlier read holds it past the
464                    // deadline (an abandoned read of a huge file, a slow
465                    // mount), this read proceeds without it: duplicate work
466                    // beats failing the call — the cache store below has its
467                    // own lock, and "retry in a moment" met the same holder.
468                    let _file_guard = {
469                        let deadline =
470                            std::time::Instant::now() + std::time::Duration::from_secs(10);
471                        loop {
472                            if cancel_flag.load(Ordering::Relaxed) {
473                                return;
474                            }
475                            if let Ok(guard) = file_lock.try_lock() {
476                                break Some(guard);
477                            }
478                            if std::time::Instant::now() >= deadline {
479                                tracing::warn!(
480                                    "ctx_read: per-file lock still held after 10s for \
481                                     {path_owned}, reading without it"
482                                );
483                                break None;
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                            // A file that cannot be read is this read's typed
728                            // failure (`"error"`, answered as a tool error
729                            // below) with the same text — never a `diff` reply.
730                            let (out, baseline, diff_mode) = if fresh {
731                                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.";
732                                (warning.to_string(), None, "diff")
733                            } else {
734                                match crate::tools::ctx_read::prepare_diff(
735                                    &cache,
736                                    &path_owned,
737                                    &file_ref,
738                                ) {
739                                    Ok((out, _sent, baseline)) => (out, baseline, "diff"),
740                                    Err(failure) => (failure, None, "error"),
741                                }
742                            };
743                            let out = crate::core::redaction::redact_text_if_enabled(&out);
744                            let orig = baseline.as_deref().map_or_else(
745                                || cache.get(&path_owned).map_or(0, |e| e.original_tokens),
746                                crate::core::tokens::count_tokens,
747                            );
748                            pending_cache_worker
749                                .lock()
750                                .unwrap_or_else(std::sync::PoisonError::into_inner)
751                                .diff_baseline = baseline;
752                            let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
753                            let s = cache.get_stats();
754                            PrepareOutcome::Hit(
755                                out,
756                                diff_mode.to_string(),
757                                orig,
758                                false,
759                                fref,
760                                (s.total_reads(), s.cache_hits()),
761                                reuse_outcome,
762                            )
763                        } else if let Some((orig_tok, content_opt)) = snap {
764                            let resolved = if mode_eff == "auto" {
765                                tuning.auto_density_mode().unwrap_or_else(|| {
766                                    crate::tools::ctx_read::resolve_auto_mode(
767                                        Some(&cache),
768                                        &path_owned,
769                                        orig_tok,
770                                        None,
771                                        task_ref,
772                                    )
773                                })
774                            } else {
775                                mode_eff
776                            };
777
778                            if (resolved == "full" || resolved == "full-compact")
779                                && let Some(out) = crate::tools::ctx_read::try_stub_hit_readonly(
780                                    &cache,
781                                    &path_owned,
782                                )
783                            {
784                                let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
785                                let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
786                                let s = cache.get_stats();
787                                PrepareOutcome::Hit(
788                                    out.content,
789                                    out.resolved_mode,
790                                    orig,
791                                    true,
792                                    fref,
793                                    (s.total_reads(), s.cache_hits()),
794                                    ReuseOutcome::UnchangedStub,
795                                )
796                            } else if crate::tools::ctx_read::is_cacheable_mode(&resolved) {
797                                let ck = crate::tools::ctx_read::request_scoped_key(
798                                    crate::tools::ctx_read::compressed_cache_key(
799                                        &resolved,
800                                        crp_mode,
801                                        task_ref,
802                                        tuning.aggressiveness,
803                                        tuning.protect,
804                                    ),
805                                    mode == "auto",
806                                );
807                                if let Some(hit) = cache.get_compressed(&path_owned, &ck).cloned() {
808                                    crate::core::auto_mode_resolver::count_source(
809                                        "compressed_cache_hit",
810                                    );
811                                    let hit = crate::core::redaction::redact_text_if_enabled(&hit);
812                                    let orig =
813                                        cache.get(&path_owned).map_or(0, |e| e.original_tokens);
814                                    let fref =
815                                        cache.file_ref_map().get(path_owned.as_str()).cloned();
816                                    let s = cache.get_stats();
817                                    PrepareOutcome::Hit(
818                                        hit,
819                                        resolved,
820                                        orig,
821                                        true,
822                                        fref,
823                                        (s.total_reads(), s.cache_hits()),
824                                        ReuseOutcome::RenderCacheHit,
825                                    )
826                                } else {
827                                    if reuse_outcome == ReuseOutcome::Cold
828                                        && cache.was_compressed_variant_evicted(&path_owned, &ck)
829                                    {
830                                        reuse_outcome = ReuseOutcome::VariantEvicted;
831                                    }
832                                    let c = content_opt
833                                        .or_else(|| preread.as_deref().map(String::from));
834                                    PrepareOutcome::Compute {
835                                        file_ref,
836                                        resolved_mode: resolved,
837                                        content: c.unwrap_or_default(),
838                                        original_tokens: orig_tok,
839                                        reuse_outcome,
840                                        cacheable: true,
841                                    }
842                                }
843                            } else {
844                                let c =
845                                    content_opt.or_else(|| preread.as_deref().map(String::from));
846                                PrepareOutcome::Compute {
847                                    file_ref,
848                                    resolved_mode: resolved,
849                                    content: c.unwrap_or_default(),
850                                    original_tokens: orig_tok,
851                                    reuse_outcome,
852                                    cacheable: true,
853                                }
854                            }
855                        } else {
856                            let raw = match preread {
857                                Some(c) if !c.is_empty() => c,
858                                _ => match crate::tools::ctx_read::read_file_lossy(&path_owned) {
859                                    Ok(c) if !c.is_empty() => c,
860                                    Ok(_) => {
861                                        tracing::debug!(
862                                            "ctx_read: skipping cache for empty content: {path_owned}"
863                                        );
864                                        let _ = tx.send((
865                                            empty_file_notice(&path_owned),
866                                            "full".into(),
867                                            0,
868                                            false,
869                                            None,
870                                            (0, 0),
871                                            ReuseOutcome::Cold,
872                                        ));
873                                        return;
874                                    }
875                                    Err(e) => {
876                                        tracing::debug!(
877                                            "ctx_read: skipping cache for empty content: {path_owned}"
878                                        );
879                                        let _ = tx.send((
880                                            format!("Cannot read file: {path_owned}: {e}"),
881                                            "error".into(),
882                                            0,
883                                            false,
884                                            None,
885                                            (0, 0),
886                                            ReuseOutcome::Cold,
887                                        ));
888                                        return;
889                                    }
890                                },
891                            };
892                            let sr = cache.store(&path_owned, &raw);
893                            let resolved = if mode_eff == "auto" {
894                                tuning.auto_density_mode().unwrap_or_else(|| {
895                                    crate::tools::ctx_read::resolve_auto_mode(
896                                        None,
897                                        &path_owned,
898                                        sr.original_tokens,
899                                        Some(sr.line_count),
900                                        task_ref,
901                                    )
902                                })
903                            } else {
904                                mode_eff
905                            };
906                            PrepareOutcome::Compute {
907                                file_ref,
908                                resolved_mode: resolved,
909                                content: raw,
910                                original_tokens: sr.original_tokens,
911                                reuse_outcome,
912                                cacheable: true,
913                            }
914                        };
915                        let identity = cache.get(&path_owned).map(CacheSourceIdentity::from_entry);
916                        (outcome, identity)
917                    }; // write lock released
918
919                    if let PrepareOutcome::Hit(c, rm, orig, hit, fref, ss, reuse_outcome) = outcome
920                    {
921                        // Update last_mode for compressed-cache hits so the auto-mode
922                        // resolver can reuse this mode on future re-reads (#E26).
923                        let mut pending = pending_cache_worker
924                            .lock()
925                            .unwrap_or_else(std::sync::PoisonError::into_inner);
926                        let diff_baseline = pending.diff_baseline.take();
927                        *pending = PendingCacheDelivery {
928                            identity: source_identity,
929                            last_mode: Some(rm.clone()),
930                            diff_baseline,
931                            ..PendingCacheDelivery::default()
932                        };
933                        let _ = tx.send((c, rm, orig, hit, fref, ss, reuse_outcome));
934                        return;
935                    }
936                    let PrepareOutcome::Compute {
937                        file_ref,
938                        resolved_mode,
939                        content: compute_content,
940                        original_tokens,
941                        reuse_outcome,
942                        cacheable,
943                    } = outcome
944                    else {
945                        unreachable!()
946                    };
947
948                    if cancel_flag.load(Ordering::Relaxed) {
949                        return;
950                    }
951
952                    // 2b-ii: Heavy computation WITHOUT cache lock.
953                    // Tree-sitter, entropy compression, mode rendering all
954                    // run under the per-file mutex only (serializes same-file
955                    // reads, but does not block other files or tool calls).
956                    let short = crate::core::protocol::shorten_path(&path_owned);
957                    let ext_s = std::path::Path::new(&*path_owned)
958                        .extension()
959                        .and_then(|e| e.to_str())
960                        .unwrap_or("");
961
962                    let source_hash = blake3::hash(compute_content.as_bytes());
963                    let mut source_fingerprint = [0u8; 12];
964                    source_fingerprint.copy_from_slice(&source_hash.as_bytes()[..12]);
965                    let (mut computed, rmode) = if resolved_mode == "full"
966                        || resolved_mode == "full-compact"
967                    {
968                        if resolved_mode == "full-compact" {
969                            let (out, _) = crate::tools::ctx_read::format_full_compact_output(
970                                &compute_content,
971                            );
972                            (out, "full-compact".to_string())
973                        } else {
974                            let lc = compute_content.lines().count();
975                            let (out, _) = crate::tools::ctx_read::format_full_output(
976                                &file_ref,
977                                &short,
978                                ext_s,
979                                &compute_content,
980                                original_tokens,
981                                lc,
982                                task_ref,
983                            );
984                            let ft = crate::core::tokens::count_tokens(&out);
985                            let out = crate::tools::ctx_read::cap_to_raw(
986                                out,
987                                ft,
988                                &compute_content,
989                                original_tokens,
990                                "full",
991                            );
992                            (out, "full".to_string())
993                        }
994                    } else {
995                        // #1910: a fallback inside an `auto` read returns the
996                        // bare file, bannerless.
997                        let _auto_guard = (mode == "auto")
998                            .then(crate::tools::ctx_read::render::AutoRequestGuard::new);
999                        let (out, _) = crate::tools::ctx_read::process_mode_tuned(
1000                            &compute_content,
1001                            &resolved_mode,
1002                            &file_ref,
1003                            &short,
1004                            ext_s,
1005                            original_tokens,
1006                            crp_mode,
1007                            &path_owned,
1008                            task_ref,
1009                            tuning,
1010                        );
1011                        let out = if crate::tools::ctx_read::mode_allows_raw_cap(&resolved_mode) {
1012                            let ft = crate::core::tokens::count_tokens(&out);
1013                            crate::tools::ctx_read::cap_to_raw(
1014                                out,
1015                                ft,
1016                                &compute_content,
1017                                original_tokens,
1018                                &resolved_mode,
1019                            )
1020                        } else {
1021                            out
1022                        };
1023                        (out, resolved_mode)
1024                    };
1025
1026                    computed = crate::core::redaction::redact_text_if_enabled(&computed);
1027                    if let Some(note) =
1028                        crate::core::context_admission::note_for(&compute_content, &computed)
1029                    {
1030                        computed.push('\n');
1031                        computed.push_str(&note);
1032                    }
1033
1034                    if cancel_flag.load(Ordering::Relaxed) {
1035                        return;
1036                    }
1037
1038                    // Warming source bytes is acquisition; variants/full flags imply
1039                    // delivery and are committed only if this result is included.
1040                    // An uncached fallback (`F?` ref, #1925) never feeds the cache.
1041                    let compressed_variant = (cacheable
1042                        && crate::tools::ctx_read::is_cacheable_mode(&rmode))
1043                    .then(|| {
1044                        // #1910: an `auto` request's fallback is bannerless, an
1045                        // explicit one is not — they must never share a variant.
1046                        let key = crate::tools::ctx_read::request_scoped_key(
1047                            crate::tools::ctx_read::compressed_cache_key(
1048                                &rmode,
1049                                crp_mode,
1050                                task_ref,
1051                                tuning.aggressiveness,
1052                                tuning.protect,
1053                            ),
1054                            mode == "auto",
1055                        );
1056                        (key, computed.clone())
1057                    });
1058                    *pending_cache_worker
1059                        .lock()
1060                        .unwrap_or_else(std::sync::PoisonError::into_inner) =
1061                        PendingCacheDelivery {
1062                            identity: source_identity,
1063                            compressed_variant,
1064                            full_content: cacheable
1065                                && matches!(rmode.as_str(), "full" | "full-compact"),
1066                            source_fingerprint: Some(source_fingerprint),
1067                            last_mode: cacheable.then(|| rmode.clone()),
1068                            record_bounce_read: true,
1069                            diff_baseline: None,
1070                        };
1071                    let _ = tx.send((
1072                        computed,
1073                        rmode,
1074                        original_tokens,
1075                        false,
1076                        Some(file_ref),
1077                        (0, 0),
1078                        reuse_outcome,
1079                    ));
1080                });
1081                if let Ok(result) = rx.recv_timeout(read_timeout) {
1082                    result
1083                } else {
1084                    cancelled.store(true, Ordering::Relaxed);
1085                    tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
1086                    let msg = format!(
1087                        "ERROR: ctx_read timed out after {}s reading {path}. \
1088                     The file may be very large or a blocking I/O issue occurred. \
1089                     Try mode=\"lines:1-100\" for a partial read.",
1090                        read_timeout.as_secs()
1091                    );
1092                    return Err(ErrorData::internal_error(msg, None));
1093                }
1094            } // end else (slow path)
1095        };
1096
1097        engine::reject_read_failure_if_enabled(
1098            engine_interface_v1,
1099            &resolved_mode,
1100            &ctx.project_root,
1101            path,
1102            &mut engine_policy_admission,
1103        )?;
1104        engine::require_aggressive(
1105            engine_interface_v1,
1106            &resolved_mode,
1107            &ctx.project_root,
1108            path,
1109            &mut engine_policy_admission,
1110        )?;
1111        if resolved_mode == "error" {
1112            return Err(ErrorData::invalid_params(output, None));
1113        }
1114
1115        let mut output = output;
1116        // Raw and receipt-backed contracts retain their exact payload. Only a
1117        // newly acquired source can produce a current optional Pro hint.
1118        let code_hint = if !engine_interface_v1 && resolved_mode != "raw" && !is_cache_hit {
1119            engine_snapshot.code_hint(path)
1120        } else {
1121            None
1122        };
1123        let engine_warning = engine_snapshot.record_if_enabled(
1124            &ctx.project_root,
1125            engine_policy_admission,
1126            &mut output,
1127        );
1128        let output_tokens = crate::core::tokens::count_tokens(&output);
1129
1130        let cache_delivery = std::mem::take(
1131            &mut *pending_cache
1132                .lock()
1133                .unwrap_or_else(std::sync::PoisonError::into_inner),
1134        );
1135        // A pre-read disk hash may describe older bytes. Relay only when it
1136        // agrees with the source that actually supplied this rendered result.
1137        let cross_agent = if is_cache_hit {
1138            None
1139        } else {
1140            delivery_metadata
1141                .filter(|fp| cache_delivery.source_fingerprint.as_ref() == Some(&fp.hash))
1142                .map(|fp| {
1143                    let relay_key = (matches!(resolved_mode.as_str(), "map" | "signatures")
1144                        && output.len() <= 8192)
1145                        .then(|| {
1146                            crate::tools::ctx_read::compressed_cache_key(
1147                                &resolved_mode,
1148                                ctx.crp_mode,
1149                                None,
1150                                aggressiveness,
1151                                &protect,
1152                            )
1153                        });
1154                    PendingCrossAgentDelivery {
1155                        hash: fp.hash,
1156                        mtime: fp.mtime,
1157                        line_count: fp.line_count,
1158                        output_tokens,
1159                        output: output.clone(),
1160                        relay_key,
1161                    }
1162                })
1163        };
1164
1165        // #1098: graph-related hints (callers/callees) are now computed AFTER the
1166        // cache lock is released. They involve SQLite queries (~50-200ms) that
1167        // previously blocked all parallel reads while holding the write lock.
1168        let graph_hint = if !is_cache_hit
1169            && !resolved_mode.starts_with("lines:")
1170            && crate::core::profiles::active_profile()
1171                .output_hints
1172                .related_hint()
1173        {
1174            crate::tools::ctx_read::graph_related_hint(path)
1175        } else {
1176            None
1177        };
1178
1179        // Cross-source hints: gated by profile `cross_source_hint` (default off).
1180        // When enabled, appends issue/PR/schema references from the property
1181        // graph. Skipped when graph.db doesn't exist (#682).
1182        // Legacy graph edges carry no source authority for protected reuse.
1183        let hints_suffix = if crate::core::profiles::active_profile()
1184            .output_hints
1185            .cross_source_hint()
1186            && !crate::core::policy::runtime::is_active()
1187        {
1188            let graph_db =
1189                crate::core::property_graph::graph_dir(&ctx.project_root).join("graph.db");
1190            let graph = graph_db
1191                .exists()
1192                .then(|| crate::core::property_graph::CodeGraph::open(&ctx.project_root))
1193                .transpose()
1194                .ok()
1195                .flatten();
1196            graph.map_or_else(String::new, |graph| {
1197                let edges = graph.all_cross_source_edges();
1198                if edges.is_empty() {
1199                    String::new()
1200                } else {
1201                    let ranges = scoped_read_ranges(&resolved_mode);
1202                    let relative_path =
1203                        crate::core::graph_index::graph_relative_key(path, &ctx.project_root);
1204                    let hints = crate::core::cross_source_hints::hints_for_file_matching(
1205                        path,
1206                        &edges,
1207                        &ctx.project_root,
1208                        |hint| {
1209                            // The far end of the edge is asked again (G04);
1210                            // the near end is the file this call just read.
1211                            graph.serves_file(&hint.source_uri)
1212                                && ranges.as_ref().is_none_or(|ranges| {
1213                                    hint_intersects_ranges(hint, ranges, &graph, &relative_path)
1214                                })
1215                        },
1216                    );
1217                    crate::core::cross_source_hints::format_hints(&hints)
1218                }
1219            })
1220        } else {
1221            String::new()
1222        };
1223
1224        // Rule injection (#1325): discover and append rules scoped to this file
1225        // path (CLAUDE.md, AGENTS.md, .cursor/rules, .claude/rules) so the agent
1226        // receives the same context it would get from the native Read tool.
1227        let rules_suffix = {
1228            let client_id = ctx
1229                .client_name
1230                .as_ref()
1231                .map(|c| c.blocking_read().clone())
1232                .unwrap_or_default();
1233            crate::core::rule_discovery::rules_suffix_for_read(path, &ctx.project_root, &client_id)
1234        };
1235        let mut warnings: Vec<&str> = engine_warning.as_deref().into_iter().collect();
1236        if let Some(ref w) = budget_warning {
1237            warnings.push(w.as_str());
1238        }
1239        if let Some(ref w) = delta_explicit_note {
1240            warnings.push(w.as_str());
1241        }
1242        if let Some(ref w) = mode_override_note {
1243            warnings.push(w.as_str());
1244        }
1245        if let Some(ref w) = instruction_mode_note {
1246            warnings.push(w.as_str());
1247        }
1248        let file_summary = extract_file_summary(&output, path);
1249        let graph_suffix = graph_hint.map(|h| format!("\n{h}")).unwrap_or_default();
1250        // #977: notices (mode override, budget, delta) go BEFORE the
1251        // payload so client-side truncation of large outputs cannot hide them.
1252        let final_output = if !warnings.is_empty() {
1253            format!(
1254                "{}\n\n{output}{hints_suffix}{graph_suffix}{rules_suffix}",
1255                warnings.join("\n")
1256            )
1257        } else if hints_suffix.is_empty() && graph_suffix.is_empty() && rules_suffix.is_empty() {
1258            output
1259        } else {
1260            format!("{output}{hints_suffix}{graph_suffix}{rules_suffix}")
1261        };
1262        // Source lineage of this reply (G04). The requested file is published
1263        // even when the answer came from a cache or a stub. Everything the
1264        // reply carries from somewhere ELSE — graph neighbours, cross-source
1265        // hints, proactively expanded content — comes from stores whose
1266        // sources are not bound here: the call's source set is then not
1267        // complete and is recorded as such, never as "this file only".
1268        // Rule files are not in that list: `rule_discovery` appends a rule
1269        // only as the admitted rooted reader delivers it, and that reader
1270        // publishes the rule file into this call's source set (or marks the
1271        // set unbound itself when it cannot bind the file).
1272        crate::tools::ctx_read::publish_requested_source(path, &ctx.project_root, "ctx_read");
1273        let assembled_len = final_output.len();
1274        let foreign_content = !hints_suffix.is_empty() || !graph_suffix.is_empty();
1275
1276        // Proactive context: gated by profile `proactive_context` (default off).
1277        // When enabled, auto-expands previously compressed content that is
1278        // keyword-relevant to the current read (up to 2000 tokens).
1279        let final_output = if crate::core::profiles::active_profile()
1280            .output_hints
1281            .proactive_context()
1282        {
1283            let proactive_query = format!(
1284                "ctx_read path={path} mode={resolved_mode} task={}",
1285                task_ref.unwrap_or_default()
1286            );
1287            if let Some(block) =
1288                crate::core::relevance_tracker::proactive_context_for_path(&proactive_query, path)
1289            {
1290                format!("{final_output}{block}")
1291            } else {
1292                final_output
1293            }
1294        } else {
1295            final_output
1296        };
1297        if foreign_content || final_output.len() != assembled_len {
1298            crate::core::archive::authority::mark_unbound();
1299        }
1300
1301        // Keep paid annotations outside the pending source/relay cache payload;
1302        // an expired license must never recover an old paid analysis as fresh.
1303        let final_output = match code_hint {
1304            Some(note) => format!("{final_output}\n\n{note}"),
1305            None => final_output,
1306        };
1307
1308        // Monotonic guard (#1326): re-count tokens on the fully assembled output
1309        // (including hints, warnings, proactive context) and verify the compressed
1310        // result is actually smaller than the original. If annotations inflated the
1311        // output beyond the raw baseline, report zero savings so the ledger stays
1312        // honest. We keep the compressed form (it may still be more useful than raw)
1313        // but correct the accounting.
1314        let final_tokens = crate::core::tokens::count_tokens(&final_output);
1315        let verified_saved = original.saturating_sub(final_tokens);
1316
1317        let delivery = PendingReadDelivery {
1318            path: path.to_owned(),
1319            cache_delivery,
1320            cross_agent,
1321            file_ref,
1322            file_summary,
1323            resolved_mode: resolved_mode.clone(),
1324            original_tokens: original,
1325            reuse_outcome,
1326            is_cache_hit,
1327            agent_id: resolved_agent_id,
1328        };
1329        Ok(PreparedRead {
1330            delivery: Some(delivery),
1331            output: ToolOutput {
1332                text: final_output,
1333                original_tokens: original,
1334                saved_tokens: verified_saved,
1335                mode: Some(resolved_mode),
1336                path: Some(path.to_string()),
1337                changed: false,
1338                shell_outcome: None,
1339                content_blocks: None,
1340            },
1341        })
1342    }
1343}
1344
1345#[path = "ctx_read_engine.rs"]
1346mod engine;
1347// #660 LOC gate: the MCP tool definition lives in its own module.
1348#[path = "ctx_read_image.rs"]
1349mod image;
1350#[path = "ctx_read_schema.rs"]
1351mod schema;
1352use image::read_image_file;
1353// #660 LOC gate: leaf helpers live in their own module.
1354#[path = "ctx_read_helpers.rs"]
1355mod helpers;
1356pub(crate) use helpers::task_intent_steers_read;
1357use helpers::{extract_file_summary, record_attribution_result};
1358
1359// #660 LOC gate: cache-lock deadline and the uncached fallback (#1925).
1360#[path = "ctx_read_uncached.rs"]
1361mod uncached;
1362use uncached::{PrepareOutcome, cache_lock_deadline, empty_file_notice, prepare_uncached};
1363
1364#[path = "ctx_read_window.rs"]
1365mod window;
1366// #1993: the batch read resolves `raw=true` the same way.
1367pub(super) use window::resolve_explicit_mode;
1368#[allow(unused_imports)]
1369// lines_mode + resolve_line_window used in #[cfg(test)] ctx_read_inline_tests
1370use window::{
1371    apply_line_window, hint_intersects_ranges, lines_mode, resolve_instruction_file_mode,
1372    resolve_line_window, resolve_raw_alias, scoped_read_ranges,
1373};
1374
1375// #660 LOC gate: inline tests split out to keep this file under the line cap.
1376#[cfg(test)]
1377#[path = "ctx_read_inline_tests.rs"]
1378mod tests;
1379
1380#[cfg(test)]
1381#[path = "ctx_read_security_tests.rs"]
1382mod security_tests;
1383
1384#[cfg(test)]
1385#[path = "ctx_read_gateway_tests.rs"]
1386mod gateway_tests;
1387
1388// #660 LOC gate: repo-param tests split out to keep this file under the line
1389// cap — see `ctx_read_repo_param_tests.rs`.
1390
1391#[cfg(test)]
1392#[path = "ctx_read_repo_param_tests.rs"]
1393mod repo_param_tests;
1394
1395#[cfg(test)]
1396#[path = "ctx_read_override_tests.rs"]
1397mod override_tests;