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