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