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