1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::{Arc, Mutex};
3
4use rmcp::ErrorData;
5use rmcp::model::Tool;
6use serde_json::{Map, Value, json};
7
8use crate::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 if mode != "raw"
263 && let Some(overridden) = gate_result.overridden_mode
264 {
265 mode = overridden;
266 }
267
268 let (mut mode, degrade_warning) = if crate::tools::ctx_read::is_instruction_file(path) {
269 ("full".to_string(), None)
270 } else if mode == "raw" {
271 ("raw".to_string(), None)
275 } else {
276 auto_degrade_read_mode(&mode)
277 };
278
279 let mut delta_explicit_note: Option<String> = None;
290 if !fresh
291 && explicit_mode
292 && (mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
293 && crate::core::config::Config::load().delta_explicit_effective()
294 && let Ok(cache) = cache_lock.try_read()
295 {
296 let decision = crate::tools::ctx_read::resolve_explicit_delta_mode(
297 &cache,
298 path,
299 &mode,
300 explicit_mode,
301 fresh,
302 true,
303 );
304 mode = decision.mode;
305 delta_explicit_note = decision.note;
306 }
307
308 if mode.starts_with("lines:") {
309 fresh = true;
310 }
311
312 if crate::core::binary_detect::is_binary_file(path) {
313 let msg = crate::core::binary_detect::binary_file_message(path);
314 return Err(ErrorData::invalid_params(msg, None));
315 }
316 {
317 let cap = crate::core::limits::max_read_bytes() as u64;
318 if let Ok(meta) = std::fs::metadata(path)
319 && meta.len() > cap
320 {
321 let msg = format!(
322 "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
323 Use mode=\"lines:1-100\" or start_line+limit for partial reads, \
324 mode=\"anchored\" with start_line+limit for edit-ready windows, \
325 or increase the limit.",
326 meta.len(),
327 cap
328 );
329 return Err(ErrorData::invalid_params(msg, None));
330 }
331 }
332
333 if !fresh
336 && let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir()
337 && let Ok(mut cache) = cache_lock.try_write()
338 {
339 crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
340 }
341
342 let read_timeout = std::time::Duration::from_secs(30);
346 let cancelled = Arc::new(AtomicBool::new(false));
347 let (output, resolved_mode, original, is_cache_hit, file_ref, cache_stats) = {
348 let crp_mode = ctx.crp_mode;
349 let task_ref = current_task.as_deref();
350
351 let fast_result = 'fast: {
352 let file_lock = per_file_lock(path);
353 let Some(_file_guard) = file_lock.try_lock().ok() else {
354 break 'fast None;
355 };
356
357 if !fresh
368 && (mode == "full" || mode == "full-compact" || mode == "auto")
369 && let Ok(cache) = cache_lock.try_read()
370 && let Some(read_output) =
371 crate::tools::ctx_read::try_stub_hit_readonly(&cache, path)
372 {
373 let content = read_output.content;
374 let rmode = read_output.resolved_mode;
375 let orig = cache.get(path).map_or(0, |e| e.original_tokens);
376 let hit = content.contains(" cached ")
377 || content.contains("[unchanged")
378 || content.contains("[delta:");
379 let fref = cache.file_ref_map().get(path).cloned();
380 let stats = cache.get_stats();
381 let stats_snapshot = (stats.total_reads(), stats.cache_hits());
382 break 'fast Some((content, rmode, orig, hit, fref, stats_snapshot));
383 }
384
385 let Some(mut cache) = cache_lock.try_write().ok() else {
388 break 'fast None;
389 };
390 let read_output = if fresh {
391 crate::tools::ctx_read::handle_fresh_with_task_resolved_tuned(
392 &mut cache,
393 path,
394 &mode,
395 crp_mode,
396 task_ref,
397 aggressiveness,
398 &protect,
399 )
400 } else {
401 crate::tools::ctx_read::handle_with_task_resolved_tuned(
402 &mut cache,
403 path,
404 &mode,
405 crp_mode,
406 task_ref,
407 aggressiveness,
408 &protect,
409 )
410 };
411 let content = read_output.content;
412 let rmode = read_output.resolved_mode;
413 let orig = cache.get(path).map_or(0, |e| e.original_tokens);
414 let hit = content.contains(" cached ")
415 || content.contains("[unchanged")
416 || content.contains("[delta:");
417 let fref = cache.file_ref_map().get(path).cloned();
418 let stats = cache.get_stats();
419 let stats_snapshot = (stats.total_reads(), stats.cache_hits());
420 Some((content, rmode, orig, hit, fref, stats_snapshot))
421 };
422
423 if let Some(result) = fast_result {
424 result
425 } else {
426 let cache_lock = cache_lock.clone();
427 let mode = mode.clone();
428 let task_owned = current_task.clone();
429 let protect_owned = protect.clone();
430 let path_owned = path.to_string();
431 let cancel_flag = cancelled.clone();
432 let (tx, rx) = std::sync::mpsc::sync_channel(1);
433 std::thread::spawn(move || {
434 let file_lock = per_file_lock(&path_owned);
435
436 let _file_guard = {
437 let deadline =
438 std::time::Instant::now() + std::time::Duration::from_secs(25);
439 loop {
440 if cancel_flag.load(Ordering::Relaxed) {
441 return;
442 }
443 if let Ok(guard) = file_lock.try_lock() {
444 break guard;
445 }
446 if std::time::Instant::now() >= deadline {
447 tracing::error!(
448 "ctx_read: per-file lock timeout after 25s for {path_owned}"
449 );
450 let _ = tx.send((
451 format!("per-file lock contention for {path_owned} — retry in a moment"),
452 "error".to_string(), 0, false, None, (0, 0),
453 ));
454 return;
455 }
456 std::thread::sleep(std::time::Duration::from_millis(50));
457 }
458 };
459
460 if cancel_flag.load(Ordering::Relaxed) {
461 return;
462 }
463
464 if !fresh
471 && (mode == "full" || mode == "full-compact" || mode == "auto")
472 && let Ok(cache) = cache_lock.try_read()
473 && let Some(read_output) =
474 crate::tools::ctx_read::try_stub_hit_readonly(&cache, &path_owned)
475 {
476 let content = read_output.content;
477 let rmode = read_output.resolved_mode;
478 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
479 let hit = true;
480 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
481 let stats = cache.get_stats();
482 let stats_snapshot = (stats.total_reads(), stats.cache_hits());
483 let _ = tx.send((content, rmode, orig, hit, fref, stats_snapshot));
484 return;
485 }
486
487 let preread = crate::tools::ctx_read::read_file_lossy(&path_owned).ok();
489
490 if cancel_flag.load(Ordering::Relaxed) {
491 return;
492 }
493
494 let task_ref = task_owned.as_deref();
504 let tuning =
505 crate::tools::ctx_read::ReadTuning::resolve(aggressiveness, &protect_owned);
506
507 macro_rules! acquire_write {
509 ($deadline_secs:expr, $label:expr) => {{
510 let deadline = std::time::Instant::now()
511 + std::time::Duration::from_secs($deadline_secs);
512 loop {
513 if cancel_flag.load(Ordering::Relaxed) {
514 return;
515 }
516 if let Ok(guard) = cache_lock.try_write() {
517 break guard;
518 }
519 if std::time::Instant::now() >= deadline {
520 tracing::error!(
521 "ctx_read: cache write-lock timeout ({}) for {path_owned}",
522 $label,
523 );
524 let _ = tx.send((
525 format!(
526 "cache lock contention for {path_owned} — retry in a moment"
527 ),
528 "error".into(),
529 0,
530 false,
531 None,
532 (0, 0),
533 ));
534 return;
535 }
536 std::thread::sleep(std::time::Duration::from_millis(50));
537 }
538 }};
539 }
540
541 #[allow(clippy::large_enum_variant)]
545 enum PrepareOutcome {
546 Hit(String, String, usize, bool, Option<String>, (u64, u64)),
547 Compute {
548 file_ref: String,
549 resolved_mode: String,
550 content: String,
551 original_tokens: usize,
552 },
553 }
554
555 let outcome = {
556 let mut cache = acquire_write!(10, "prepare 10s");
557
558 if crate::core::plugins::PluginManager::has_listener("pre_read") {
559 crate::core::plugins::PluginManager::fire_hook_background(
560 crate::core::plugins::executor::HookPoint::PreRead {
561 path: path_owned.clone(),
562 },
563 );
564 }
565 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
566 bt.next_seq();
567 }
568
569 let file_ref = cache.get_file_ref(&path_owned);
570
571 let effective_fresh = fresh
572 || crate::tools::ctx_read::force_fresh_env()
573 || (crate::tools::ctx_read::is_subagent_context()
574 && !crate::core::conversation::scope_enabled());
575
576 let mode_eff = if mode != "raw"
577 && !mode.starts_with("lines:")
578 && crate::core::config::Config::load()
579 .proxy
580 .is_path_compress_protected(&path_owned)
581 {
582 "full".to_string()
583 } else {
584 mode.clone()
585 };
586
587 if effective_fresh {
588 cache.invalidate(&path_owned);
589 }
590
591 if !effective_fresh {
592 let stale = cache.get(&path_owned).is_some_and(|e| {
593 crate::core::cache::is_cache_entry_stale_verified(
594 &path_owned,
595 e.stored_mtime,
596 &e.hash,
597 )
598 });
599 if stale {
600 cache.invalidate(&path_owned);
601 }
602 }
603
604 let snap = cache
605 .get(&path_owned)
606 .map(|e| (e.original_tokens, e.content()));
607
608 if let Some((orig_tok, content_opt)) = snap {
609 let resolved = if mode_eff == "auto" {
610 tuning.auto_density_mode().unwrap_or_else(|| {
611 crate::tools::ctx_read::resolve_auto_mode(
612 Some(&cache),
613 &path_owned,
614 orig_tok,
615 task_ref,
616 )
617 })
618 } else {
619 mode_eff
620 };
621
622 if (resolved == "full" || resolved == "full-compact")
623 && let Some(out) = crate::tools::ctx_read::try_stub_hit_readonly(
624 &cache,
625 &path_owned,
626 )
627 {
628 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
629 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
630 let s = cache.get_stats();
631 PrepareOutcome::Hit(
632 out.content,
633 out.resolved_mode,
634 orig,
635 true,
636 fref,
637 (s.total_reads(), s.cache_hits()),
638 )
639 } else if crate::tools::ctx_read::is_cacheable_mode(&resolved) {
640 let ck = crate::tools::ctx_read::compressed_cache_key(
641 &resolved,
642 crp_mode,
643 task_ref,
644 tuning.aggressiveness,
645 tuning.protect,
646 );
647 if let Some(hit) = cache.get_compressed(&path_owned, &ck).cloned() {
648 let hit = crate::core::redaction::redact_text_if_enabled(&hit);
649 let orig =
650 cache.get(&path_owned).map_or(0, |e| e.original_tokens);
651 let fref =
652 cache.file_ref_map().get(path_owned.as_str()).cloned();
653 let s = cache.get_stats();
654 PrepareOutcome::Hit(
655 hit,
656 resolved,
657 orig,
658 true,
659 fref,
660 (s.total_reads(), s.cache_hits()),
661 )
662 } else {
663 let c = content_opt
664 .or_else(|| preread.as_deref().map(String::from));
665 PrepareOutcome::Compute {
666 file_ref,
667 resolved_mode: resolved,
668 content: c.unwrap_or_default(),
669 original_tokens: orig_tok,
670 }
671 }
672 } else {
673 let c =
674 content_opt.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 raw = preread.unwrap_or_else(|| {
684 crate::tools::ctx_read::read_file_lossy(&path_owned)
685 .unwrap_or_default()
686 });
687 let sr = cache.store(&path_owned, &raw);
688 let resolved = if mode_eff == "auto" {
689 tuning.auto_density_mode().unwrap_or_else(|| {
690 crate::tools::ctx_read::resolve_auto_mode(
691 None,
692 &path_owned,
693 sr.original_tokens,
694 task_ref,
695 )
696 })
697 } else {
698 mode_eff
699 };
700 PrepareOutcome::Compute {
701 file_ref,
702 resolved_mode: resolved,
703 content: raw,
704 original_tokens: sr.original_tokens,
705 }
706 }
707 }; if let PrepareOutcome::Hit(c, rm, orig, hit, fref, ss) = outcome {
710 let _ = tx.send((c, rm, orig, hit, fref, ss));
711 return;
712 }
713 let PrepareOutcome::Compute {
714 file_ref,
715 resolved_mode,
716 content: compute_content,
717 original_tokens,
718 } = outcome
719 else {
720 unreachable!()
721 };
722
723 if cancel_flag.load(Ordering::Relaxed) {
724 return;
725 }
726
727 let short = crate::core::protocol::shorten_path(&path_owned);
732 let ext_s = std::path::Path::new(&*path_owned)
733 .extension()
734 .and_then(|e| e.to_str())
735 .unwrap_or("");
736
737 let (mut computed, rmode) = if resolved_mode == "full"
738 || resolved_mode == "full-compact"
739 {
740 if resolved_mode == "full-compact" {
741 let (out, _) = crate::tools::ctx_read::format_full_compact_output(
742 &compute_content,
743 );
744 (out, "full-compact".to_string())
745 } else {
746 let lc = compute_content.lines().count();
747 let (out, _) = crate::tools::ctx_read::format_full_output(
748 &file_ref,
749 &short,
750 ext_s,
751 &compute_content,
752 original_tokens,
753 lc,
754 task_ref,
755 );
756 let ft = crate::core::tokens::count_tokens(&out);
757 let out = crate::tools::ctx_read::cap_to_raw(
758 out,
759 ft,
760 &compute_content,
761 original_tokens,
762 );
763 (out, "full".to_string())
764 }
765 } else {
766 let (out, _) = crate::tools::ctx_read::process_mode_tuned(
767 &compute_content,
768 &resolved_mode,
769 &file_ref,
770 &short,
771 ext_s,
772 original_tokens,
773 crp_mode,
774 &path_owned,
775 task_ref,
776 tuning,
777 );
778 let out = if crate::tools::ctx_read::mode_allows_raw_cap(&resolved_mode) {
779 let ft = crate::core::tokens::count_tokens(&out);
780 crate::tools::ctx_read::cap_to_raw(
781 out,
782 ft,
783 &compute_content,
784 original_tokens,
785 )
786 } else {
787 out
788 };
789 (out, resolved_mode)
790 };
791
792 computed = crate::core::redaction::redact_text_if_enabled(&computed);
793
794 if cancel_flag.load(Ordering::Relaxed) {
795 return;
796 }
797
798 {
803 let deadline =
804 std::time::Instant::now() + std::time::Duration::from_secs(5);
805 let cache_guard = loop {
806 if cancel_flag.load(Ordering::Relaxed) {
807 return;
808 }
809 if let Ok(g) = cache_lock.try_write() {
810 break Some(g);
811 }
812 if std::time::Instant::now() >= deadline {
813 tracing::warn!(
814 "ctx_read: store-lock timeout (5s) for {path_owned}, returning without caching"
815 );
816 break None;
817 }
818 std::thread::sleep(std::time::Duration::from_millis(50));
819 };
820
821 if let Some(mut cache) = cache_guard {
822 if crate::tools::ctx_read::is_cacheable_mode(&rmode) {
823 let ck = crate::tools::ctx_read::compressed_cache_key(
824 &rmode,
825 crp_mode,
826 task_ref,
827 tuning.aggressiveness,
828 tuning.protect,
829 );
830 cache.set_compressed(&path_owned, &ck, computed.clone());
831 }
832 if rmode == "full" || rmode == "full-compact" {
833 cache.mark_full_delivered(&path_owned);
834 }
835 if let Some(entry) = cache.get_mut(&path_owned) {
836 entry.last_mode.clone_from(&rmode);
837 }
838 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
839 bt.record_read(
840 &path_owned,
841 &rmode,
842 crate::core::tokens::count_tokens(&computed),
843 original_tokens,
844 );
845 }
846 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
847 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
848 let s = cache.get_stats();
849 let _ = tx.send((
850 computed,
851 rmode,
852 orig,
853 false,
854 fref,
855 (s.total_reads(), s.cache_hits()),
856 ));
857 } else {
858 let _ =
859 tx.send((computed, rmode, original_tokens, false, None, (0, 0)));
860 }
861 }
862 });
863 if let Ok(result) = rx.recv_timeout(read_timeout) {
864 result
865 } else {
866 cancelled.store(true, Ordering::Relaxed);
867 tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
868 let msg = format!(
869 "ERROR: ctx_read timed out after {}s reading {path}. \
870 The file may be very large or a blocking I/O issue occurred. \
871 Try mode=\"lines:1-100\" for a partial read.",
872 read_timeout.as_secs()
873 );
874 return Err(ErrorData::internal_error(msg, None));
875 }
876 } };
878
879 if resolved_mode == "error" {
880 return Err(ErrorData::invalid_params(output, None));
881 }
882
883 let output_tokens = crate::core::tokens::count_tokens(&output);
884 let saved = original.saturating_sub(output_tokens);
885
886 let mut ensured_root: Option<String> = None;
888 let mut traversal_working_set: Vec<String> = Vec::new();
889 let project_root_snapshot;
890 {
891 let rt = tokio::runtime::Handle::current();
892 let session_guard = rt.block_on(tokio::time::timeout(
893 std::time::Duration::from_secs(10),
894 session_lock.write(),
895 ));
896 if let Ok(mut session) = session_guard {
897 session.touch_file(path, file_ref.as_deref(), &resolved_mode, original);
898 traversal_working_set =
901 crate::core::tool_lifecycle::recent_working_set(&session, path);
902 let file_summary = extract_file_summary(&output, path);
903 if !file_summary.is_empty() {
904 session.set_file_summary(path, &file_summary);
905 }
906 if is_cache_hit {
907 session.record_cache_hit();
908 }
909 if session.active_structured_intent.is_none() && session.files_touched.len() >= 2 {
910 let touched: Vec<String> = session
911 .files_touched
912 .iter()
913 .map(|f| f.path.clone())
914 .collect();
915 let inferred =
916 crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
917 if inferred.confidence >= 0.4 {
918 session.active_structured_intent = Some(inferred);
919 }
920 }
921 if session.task.is_none() && session.stats.files_read % 5 == 0 {
922 session.auto_infer_task();
923 }
924 let root_missing = session
925 .project_root
926 .as_deref()
927 .is_none_or(|r| r.trim().is_empty());
928 if root_missing && let Some(root) = crate::core::protocol::detect_project_root(path)
929 {
930 session.project_root = Some(root.clone());
931 ensured_root = Some(root);
932 }
933 project_root_snapshot = session
934 .project_root
935 .clone()
936 .unwrap_or_else(|| ".".to_string());
937 } else {
938 tracing::warn!(
939 "session write-lock timeout (5s) in ctx_read post-update for {path}"
940 );
941 project_root_snapshot = ctx.project_root.clone();
942 }
943 }
944
945 if let Some(root) = ensured_root.as_deref() {
946 crate::core::index_orchestrator::ensure_all_background(root);
947 }
948
949 {
955 let path_bg = path.to_string();
956 let resolved_mode_bg = resolved_mode.clone();
957 let project_root_bg = project_root_snapshot.clone();
958 let (turns, hits) = cache_stats;
959 let ledger_cache = (crate::core::savings_ledger::ledger_family()
965 != crate::core::tokens::TokenizerFamily::O200kBase)
966 .then(|| cache_lock.clone());
967 let ledger_output = ledger_cache.as_ref().map(|_| output.clone());
968 std::thread::spawn(move || {
969 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
972 crate::core::heatmap::record_file_access(&path_bg, original, saved);
973
974 {
979 use crate::core::savings_ledger as ledger;
980 let (lbase, lsaved) = match (&ledger_cache, &ledger_output) {
981 (Some(cl), Some(out)) => match cl.try_read().ok().and_then(|c| {
982 c.get(&path_bg)
983 .and_then(crate::core::cache::CacheEntry::content)
984 }) {
985 Some(raw) => {
986 let lo = ledger::count_for_ledger(&raw);
987 (lo, lo.saturating_sub(ledger::count_for_ledger(out)))
988 }
989 None => (original, saved),
990 },
991 _ => (original, saved),
992 };
993 ledger::record_read_event(lbase, lsaved);
994 }
995
996 if let Some(root) =
999 crate::core::tool_lifecycle::usable_root(Some(project_root_bg.as_str()))
1000 {
1001 crate::core::cooccurrence::record_focus_access(
1002 root,
1003 &path_bg,
1004 &traversal_working_set,
1005 );
1006 }
1007
1008 let sig =
1009 crate::core::mode_predictor::FileSignature::from_path(&path_bg, original);
1010 let density = if output_tokens > 0 {
1011 original as f64 / output_tokens as f64
1012 } else {
1013 1.0
1014 };
1015 let outcome = crate::core::mode_predictor::ModeOutcome {
1016 mode: resolved_mode_bg,
1017 tokens_in: original,
1018 tokens_out: output_tokens,
1019 density: density.min(1.0),
1020 };
1021 let mut predictor = crate::core::mode_predictor::ModePredictor::new();
1022 predictor.set_project_root(&project_root_bg);
1023 predictor.record(sig, outcome);
1024 predictor.save();
1025
1026 let ext = std::path::Path::new(&path_bg)
1027 .extension()
1028 .and_then(|e| e.to_str())
1029 .unwrap_or("")
1030 .to_string();
1031 let thresholds =
1032 crate::core::adaptive_thresholds::thresholds_for_path(&path_bg);
1033 let feedback_outcome = crate::core::feedback::CompressionOutcome {
1034 session_id: format!("{}", std::process::id()),
1035 language: ext,
1036 entropy_threshold: thresholds.bpe_entropy,
1037 jaccard_threshold: thresholds.jaccard,
1038 total_turns: turns as u32,
1039 tokens_saved: saved as u64,
1040 tokens_original: original as u64,
1041 cache_hits: hits as u32,
1042 total_reads: turns as u32,
1043 task_completed: crate::core::bounce_tracker::global()
1051 .lock()
1052 .ok()
1053 .and_then(|bt| bt.bounce_rate_for_extension(&path_bg))
1054 .is_none_or(|rate| rate < 0.30),
1055 timestamp: chrono::Local::now().to_rfc3339(),
1056 };
1057 let mut store = crate::core::feedback::FeedbackStore::load();
1058 store.project_root = Some(project_root_bg);
1059 store.record_outcome(feedback_outcome);
1060 }));
1061 });
1062 }
1063
1064 if let Some(aid) = resolved_agent_id.as_deref() {
1065 crate::core::agent_budget::record_consumption(aid, output_tokens);
1066 }
1067
1068 let graph_hint = if !is_cache_hit
1072 && !resolved_mode.starts_with("lines:")
1073 && crate::core::profiles::active_profile()
1074 .output_hints
1075 .related_hint()
1076 {
1077 crate::tools::ctx_read::graph_related_hint(path)
1078 } else {
1079 None
1080 };
1081
1082 let hints_suffix = {
1087 let graph_db =
1088 crate::core::property_graph::graph_dir(&ctx.project_root).join("graph.db");
1089 let edges = if graph_db.exists() {
1090 crate::core::property_graph::CodeGraph::open(&ctx.project_root)
1091 .map(|g| g.all_cross_source_edges())
1092 .unwrap_or_default()
1093 } else {
1094 Vec::new()
1095 };
1096 if edges.is_empty() {
1097 String::new()
1098 } else {
1099 let hints = crate::core::cross_source_hints::hints_for_file(
1100 path,
1101 &edges,
1102 &ctx.project_root,
1103 );
1104 crate::core::cross_source_hints::format_hints(&hints)
1105 }
1106 };
1107
1108 let mut warnings = Vec::new();
1109 if let Some(ref w) = budget_warning {
1110 warnings.push(w.as_str());
1111 }
1112 if let Some(ref w) = degrade_warning {
1113 warnings.push(w.as_str());
1114 }
1115 if let Some(ref w) = delta_explicit_note {
1116 warnings.push(w.as_str());
1117 }
1118 let graph_suffix = graph_hint.map(|h| format!("\n{h}")).unwrap_or_default();
1119 let final_output = if !warnings.is_empty() {
1120 format!(
1121 "{output}{hints_suffix}{graph_suffix}\n\n{}",
1122 warnings.join("\n")
1123 )
1124 } else if hints_suffix.is_empty() && graph_suffix.is_empty() {
1125 output
1126 } else {
1127 format!("{output}{hints_suffix}{graph_suffix}")
1128 };
1129
1130 Ok(ToolOutput {
1131 text: final_output,
1132 original_tokens: original,
1133 saved_tokens: saved,
1134 mode: Some(resolved_mode),
1135 path: Some(path.to_string()),
1136 changed: false,
1137 shell_outcome: None,
1138 })
1139 }
1140}
1141
1142fn resolve_line_window(
1149 start_line: Option<i64>,
1150 offset: Option<i64>,
1151 limit: Option<i64>,
1152) -> Option<(i64, Option<i64>)> {
1153 let start = start_line.or(offset).map(|v| v.max(1));
1154 let limit = limit.filter(|&l| l > 0);
1155 match (start, limit) {
1156 (Some(s), l) => Some((s, l)),
1157 (None, Some(_)) => Some((1, limit)),
1158 (None, None) => None,
1159 }
1160}
1161
1162fn lines_mode(start: i64, limit: Option<i64>) -> String {
1165 match limit {
1166 Some(l) => format!("lines:{start}-{}", start + l - 1),
1167 None => format!("lines:{start}-999999"),
1168 }
1169}
1170
1171fn anchored_lines_mode(start: i64, limit: Option<i64>) -> String {
1175 match limit {
1176 Some(l) => format!("anchored:{start}-{}", start + l - 1),
1177 None => format!("anchored:{start}-999999"),
1178 }
1179}
1180
1181fn apply_line_window(
1189 mode: &mut String,
1190 fresh: &mut bool,
1191 _explicit_mode: bool,
1192 start_line: Option<i64>,
1193 offset: Option<i64>,
1194 limit: Option<i64>,
1195) {
1196 let Some((start, limit)) = resolve_line_window(start_line, offset, limit) else {
1197 return;
1198 };
1199 if start <= 1 && limit.is_none() {
1200 return;
1201 }
1202 *fresh = true;
1203 if mode == "anchored" {
1207 *mode = anchored_lines_mode(start, limit);
1208 } else {
1209 *mode = lines_mode(start, limit);
1210 }
1211}
1212
1213fn resolve_raw_alias(arg_raw: bool, mode_arg: Option<String>) -> Option<String> {
1220 if arg_raw {
1221 Some("raw".to_string())
1222 } else {
1223 mode_arg
1224 }
1225}
1226
1227fn apply_verdict(
1228 mode: &str,
1229 verdict: crate::core::degradation_policy::DegradationVerdictV1,
1230) -> (String, bool) {
1231 use crate::core::degradation_policy::DegradationVerdictV1;
1232 match verdict {
1233 DegradationVerdictV1::Ok => (mode.to_string(), false),
1234 DegradationVerdictV1::Warn => match mode {
1235 "full" => ("map".to_string(), true),
1236 other => (other.to_string(), false),
1237 },
1238 DegradationVerdictV1::Throttle => match mode {
1239 "full" | "map" => ("signatures".to_string(), true),
1240 other => (other.to_string(), false),
1241 },
1242 DegradationVerdictV1::Block => {
1243 if mode == "signatures" {
1244 ("signatures".to_string(), false)
1245 } else {
1246 ("signatures".to_string(), true)
1247 }
1248 }
1249 }
1250}
1251
1252fn auto_degrade_read_mode(mode: &str) -> (String, Option<String>) {
1253 if crate::core::config::Config::load().no_degrade_effective() {
1254 return (mode.to_string(), None);
1255 }
1256 let profile = crate::core::profiles::active_profile();
1257 if !profile.degradation.enforce_effective() {
1258 return (mode.to_string(), None);
1259 }
1260 let policy = crate::core::degradation_policy::evaluate_v1_for_tool("ctx_read", None);
1261 let (new_mode, degraded) = apply_verdict(mode, policy.decision.verdict);
1262 let warning = if degraded {
1263 Some(format!(
1264 "⚠ Context pressure: mode={mode} was downgraded to mode={new_mode} \
1265 (verdict: {:?}). Use start_line=1 to bypass, or run ctx_compress to free budget.",
1266 policy.decision.verdict
1267 ))
1268 } else {
1269 None
1270 };
1271 (new_mode, warning)
1272}
1273
1274fn extract_file_summary(output: &str, path: &str) -> String {
1275 let hint = crate::core::auto_findings::extract_content_hint(output);
1276 if !hint.is_empty() {
1277 return hint;
1278 }
1279 let ext = std::path::Path::new(path)
1280 .extension()
1281 .and_then(|e| e.to_str())
1282 .unwrap_or("");
1283 let line_count = output.lines().count();
1284 if line_count > 5 {
1285 format!("{ext} file, {line_count} lines")
1286 } else {
1287 String::new()
1288 }
1289}
1290
1291#[cfg(test)]
1293#[path = "ctx_read_inline_tests.rs"]
1294mod tests;
1295
1296#[cfg(test)]
1299#[path = "ctx_read_repo_param_tests.rs"]
1300mod repo_param_tests;