Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

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