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
14fn 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 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 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 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 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 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 if !explicit_mode && let Some(a) = aggressiveness {
220 mode = crate::tools::ctx_read::ReadMode::Density(
223 crate::core::aggressiveness::AggressivenessProfile::from_level(a).density_target,
224 )
225 .to_string();
226 }
227 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 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 ("raw".to_string(), None)
282 } else {
283 auto_degrade_read_mode(&mode)
284 };
285
286 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 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 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 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 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 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 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 let task_ref = task_owned.as_deref();
514 let tuning =
515 crate::tools::ctx_read::ReadTuning::resolve(aggressiveness, &protect_owned);
516
517 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 #[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 }; 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 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 {
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 } };
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 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 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 {
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 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 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
982 crate::core::heatmap::record_file_access(&path_bg, original, saved);
983
984 {
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 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 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 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 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 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
1158fn 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
1178fn 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
1187fn 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
1197fn 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 if mode == "anchored" {
1223 *mode = anchored_lines_mode(start, limit);
1224 } else {
1225 *mode = lines_mode(start, limit);
1226 }
1227}
1228
1229fn 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#[cfg(test)]
1309#[path = "ctx_read_inline_tests.rs"]
1310mod tests;
1311
1312fn 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;