lean_ctx_server/tools/registered/ctx_read.rs
1// SPDX-License-Identifier: Apache-2.0
2
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5
6use rmcp::ErrorData;
7use rmcp::model::Tool;
8use serde_json::{Map, Value};
9
10use crate::server::tool_trait::{
11 McpTool, ToolContext, ToolOutput, get_bool, get_f64, get_int, get_str, get_str_array,
12 require_resolved_path,
13};
14use lean_ctx::core::cache::ReuseOutcome;
15
16/// Per-file lock that serializes concurrent reads of the same path.
17///
18/// When multiple subagents read sequentially through a shared set of files,
19/// they tend to hit the same path at the same time. Without per-file locking
20/// they all contend on the global cache write lock while doing redundant I/O.
21/// This lock ensures only one thread reads a given file from disk; the others
22/// wait cheaply on the per-file mutex, then hit the warm cache.
23///
24/// Backed by the shared `core::path_locks` registry so reads and edits of the
25/// same path coordinate through a single mutex (see issue #320).
26fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
27 lean_ctx_ext::core::path_locks::per_file_lock(path)
28}
29
30pub struct CtxReadTool;
31
32#[path = "ctx_read_delivery.rs"]
33mod delivery;
34use delivery::{
35 CacheSourceIdentity, PendingCacheDelivery, PendingCrossAgentDelivery, PendingReadDelivery,
36};
37
38pub(super) struct PreparedRead {
39 pub(super) output: ToolOutput,
40 delivery: Option<PendingReadDelivery>,
41}
42
43impl PreparedRead {
44 pub(super) fn commit(self, ctx: &ToolContext, record_agent_budget: bool) -> ToolOutput {
45 if let Some(delivery) = self.delivery {
46 delivery.commit(ctx, &self.output, record_agent_budget);
47 }
48 self.output
49 }
50}
51
52#[path = "ctx_read_dispatch.rs"]
53pub mod dispatch;
54
55impl CtxReadTool {
56 #[allow(clippy::unused_self)]
57 pub(super) fn handle_inner(
58 &self,
59 args: &Map<String, Value>,
60 ctx: &ToolContext,
61 path: &str,
62 engine_interface_v1: bool,
63 ) -> Result<ToolOutput, ErrorData> {
64 self.handle_inner_prepared(args, ctx, path, engine_interface_v1)
65 .map(|prepared| prepared.commit(ctx, true))
66 }
67
68 #[allow(clippy::unused_self)]
69 pub(super) fn handle_inner_prepared(
70 &self,
71 args: &Map<String, Value>,
72 ctx: &ToolContext,
73 path: &str,
74 engine_interface_v1: bool,
75 ) -> Result<PreparedRead, ErrorData> {
76 let session_lock = ctx
77 .session
78 .as_ref()
79 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
80 let cache_lock = ctx
81 .cache
82 .as_ref()
83 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
84
85 let current_task = {
86 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
87 let mut attempt = 0u32;
88 loop {
89 // #1018: use try_read_owned instead of Handle::block_on to avoid
90 // the async-runtime-saturation anti-pattern on Windows.
91 if let Ok(guard) = session_lock.clone().try_read_owned() {
92 break guard
93 .task
94 .as_ref()
95 .map(|t| (t.description.clone(), t.intent.clone()));
96 }
97 attempt += 1;
98 if std::time::Instant::now() >= deadline {
99 tracing::warn!(
100 "session read-lock timeout after {attempt} attempts in ctx_read for {path}"
101 );
102 break None;
103 }
104 std::thread::sleep(std::time::Duration::from_millis(25));
105 }
106 };
107 // #1590: `auto_infer_task` fabricates descriptions like
108 // "Working on /repo/src/printer (explore)" from touched-file patterns.
109 // That is fine as a telemetry hint, but its "keywords" (Working,
110 // explore, a directory path) carry no signal about a file's contents —
111 // filtering a file down to a quarter of its lines on that basis, or
112 // pinning it to `full` as an intent target, invents a task the caller
113 // never stated. Only an explicitly set task steers a read.
114 let task_is_inferred = current_task
115 .as_ref()
116 .is_some_and(|(_, intent)| !task_intent_steers_read(intent.as_deref()));
117 let current_task = current_task.map(|(description, _)| description);
118 let task_ref = if task_is_inferred {
119 None
120 } else {
121 current_task.as_deref()
122 };
123 // #513: `raw=true` is the intuitive "give me the exact bytes" escape an
124 // agent reaches for. Alias it to mode="raw" (verbatim, unframed) and
125 // force a fresh disk read below so a re-read never collapses to an
126 // `[unchanged]`/auto-delta stub. An explicit raw flag wins over `mode`.
127 let arg_raw = get_bool(args, "raw").unwrap_or(false);
128 let explicit_mode_arg = resolve_explicit_mode(arg_raw, get_str(args, "mode"));
129 let explicit_mode = explicit_mode_arg.is_some();
130 // #1209: a malformed line-range payload (e.g. `lines:44:48` with a colon
131 // instead of a dash) must fail loudly, not silently return an empty
132 // window on small files or bounce to a full-file dump on large ones.
133 // `lines:` and `anchored:` share `parse_line_range`, so validating both
134 // line-range modes at the boundary catches the typo for either. Other
135 // modes are left untouched: bare `density:` is a valid fallback and
136 // unknown keywords keep the historical warn-and-fall-back behaviour.
137 if let Some(ref requested) = explicit_mode_arg
138 && (requested.starts_with("lines:") || requested.starts_with("anchored:"))
139 && let Err(e) = requested.parse::<crate::tools::ctx_read::ReadMode>()
140 {
141 return Err(ErrorData::invalid_params(e.user_message(), None));
142 }
143 let configured_mode = (!explicit_mode)
144 .then(lean_ctx::core::auto_mode_resolver::configured_default_mode)
145 .flatten();
146 // No range requested: the outline rule decides between the outline of
147 // a large file and the whole small file (owner decision 2026-10-30).
148 let learned_mode = if !explicit_mode && configured_mode.is_none() {
149 if let Ok(cache) = cache_lock.try_read() {
150 Some(crate::tools::ctx_smart_read::select_unranged_mode(
151 &cache, path, task_ref,
152 ))
153 } else {
154 tracing::debug!(
155 "cache lock contested during auto-mode selection for {path}; \
156 resolving cold"
157 );
158 Some(crate::tools::ctx_smart_read::select_unranged_mode(
159 &lean_ctx::core::cache::SessionCache::new(),
160 path,
161 task_ref,
162 ))
163 }
164 } else {
165 None
166 };
167 let auto_or_no_mode =
168 explicit_mode_arg.as_deref().is_none_or(|m| m == "auto") && configured_mode.is_none();
169 let mut mode = lean_ctx::core::auto_mode_resolver::resolve_mode_precedence(
170 explicit_mode_arg,
171 configured_mode,
172 learned_mode,
173 "full",
174 );
175 let mut fresh = get_bool(args, "fresh").unwrap_or(false);
176 // Reacquire original bytes under current rules; an older compressed
177 // view can have omitted the classification marker that now blocks it.
178 if lean_ctx::core::policy::runtime::is_active() {
179 fresh = true;
180 }
181 // #513: a raw/verbatim request always reads from disk — the whole point
182 // is exact current bytes, never a cached stub or delta.
183 if arg_raw || engine_interface_v1 {
184 fresh = true;
185 }
186 let cache_policy = crate::server::compaction_sync::effective_cache_policy();
187 let cache_policy_bypassed = cache_policy == "off";
188 if cache_policy_bypassed {
189 fresh = true;
190 }
191 let aggressiveness =
192 lean_ctx_ext::core::aggressiveness::effective(get_f64(args, "aggressiveness"));
193 let protect = get_str_array(args, "protect").unwrap_or_default();
194 // One-knob UX: when the caller sets aggressiveness without pinning a mode,
195 // route through the proven density path at the mapped target. An explicit
196 // mode (incl. entropy/task) instead has the knob tune it via ReadTuning.
197 if !explicit_mode && let Some(a) = aggressiveness {
198 // SSOT mode construction via the typed `ReadMode` (#528): the typed
199 // `Density` Display emits the same `density:0.NN` the pipeline parses.
200 mode = crate::tools::ctx_read::ReadMode::Density(
201 lean_ctx_ext::core::aggressiveness::AggressivenessProfile::from_level(a)
202 .density_target,
203 )
204 .to_string();
205 }
206 // `start_line` (and its `offset`/`limit` aliases) can pin a line window.
207 // The resolution lives in `apply_line_window`/`resolve_line_window` so
208 // the runtime path and the unit tests share one implementation and can
209 // never drift (GitHub #432 aliases, #259 explicit-mode, #253 line-1).
210 apply_line_window(
211 &mut mode,
212 &mut fresh,
213 explicit_mode,
214 get_int(args, "start_line"),
215 get_int(args, "offset"),
216 get_int(args, "limit"),
217 );
218
219 // A concrete per-call request outranks saved views and adaptive heuristics.
220 // `auto` explicitly delegates the choice; mandatory admission still runs.
221 let pinned_mode = explicit_mode && mode != "auto";
222 if pinned_mode
223 && (matches!(mode.as_str(), "raw" | "full" | "full-compact")
224 || mode.starts_with("lines:")
225 || mode.starts_with("anchored"))
226 {
227 // Exact/full requests must not collapse to a cache stub or a delta,
228 // including when the older delta_explicit preference is enabled.
229 fresh = true;
230 }
231
232 let resolved_agent_id = ctx.agent_id.as_ref().and_then(|a| match a.try_read() {
233 Ok(guard) => guard.clone(),
234 Err(_) => None,
235 });
236 let gate_result = if pinned_mode {
237 crate::server::context_gate::pre_dispatch_pinned_read_for_agent(
238 path,
239 &mode,
240 resolved_agent_id.as_deref(),
241 )
242 } else {
243 crate::server::context_gate::pre_dispatch_read_for_agent(
244 path,
245 &mode,
246 task_ref,
247 Some(&ctx.project_root),
248 resolved_agent_id.as_deref(),
249 fresh,
250 )
251 };
252 let mut engine_policy_admission = engine::admission_or_reject(
253 engine_interface_v1,
254 &gate_result,
255 &mode,
256 &ctx.project_root,
257 path,
258 )?;
259 let budget_warning = gate_result.budget_warning.clone();
260 // A read without a range (no mode, or `auto`, no window, no density
261 // knob) is answered by the outline rule; only a view the user saved
262 // for this file (overlay) still replaces it, the gate's heuristics do not.
263 let unranged = aggressiveness.is_none()
264 && auto_or_no_mode
265 && !mode.starts_with("lines:")
266 && !mode.starts_with("anchored");
267 let user_view = matches!(
268 gate_result.reason,
269 Some("overlay-set-view" | "pinned" | "excluded")
270 );
271 // #513: an explicit raw/verbatim request is never silently downgraded by
272 // the budget gate — the caller asked for exact bytes.
273 let mut mode_override_note: Option<String> = None;
274 if mode != "raw"
275 && (!unranged || user_view)
276 && let Some(overridden) = gate_result.overridden_mode
277 {
278 if explicit_mode {
279 let reason = gate_result.reason.unwrap_or("context-gate");
280 // #1588: an override the caller cannot escape is a dead end.
281 // Name the escape hatch for the two heuristics that honour it.
282 let escape = if matches!(
283 reason,
284 "bounce-prevention" | "intent-target" | "learned-full"
285 ) {
286 ", pass fresh=true to keep the requested mode"
287 } else {
288 ""
289 };
290 mode_override_note = Some(format!(
291 "[mode overridden: {mode} -> {overridden}, reason={reason}{escape}]"
292 ));
293 }
294 mode = overridden;
295 }
296
297 let (instruction_mode, instruction_mode_note) = resolve_instruction_file_mode(path, &mode);
298 let mut mode = instruction_mode;
299 engine::require_aggressive(
300 engine_interface_v1,
301 &mode,
302 &ctx.project_root,
303 path,
304 &mut engine_policy_admission,
305 )?;
306
307 // Delta-aware explicit re-reads (opt-in: config `delta_explicit`, env
308 // LCTX_DELTA_EXPLICIT). Re-requesting full/lines:N-M content for a file
309 // this session already read re-emits content the model already holds;
310 // when the file changed on disk, a diff carries the same information in
311 // a fraction of the tokens, and an unchanged lines: request of a
312 // fully-delivered file collapses to the full-mode stub. The decision is
313 // a pure function of (cache, path, mode) — see
314 // `ctx_read::resolve_explicit_delta_mode`. First reads are unaffected;
315 // fresh=true always bypasses. Runs BEFORE the lines:→fresh guard below
316 // so a changed-file lines: re-read can still be diverted to a diff.
317 let mut delta_explicit_note: Option<String> = None;
318 if !fresh
319 && explicit_mode
320 && (mode == "full" || mode == "full-compact" || mode.starts_with("lines:"))
321 && lean_ctx::core::config::Config::load().delta_explicit_effective()
322 && let Ok(cache) = cache_lock.try_read()
323 {
324 let decision = crate::tools::ctx_read::resolve_explicit_delta_mode(
325 &cache,
326 path,
327 &mode,
328 explicit_mode,
329 fresh,
330 true,
331 );
332 mode = decision.mode;
333 delta_explicit_note = decision.note;
334 }
335
336 if mode.starts_with("lines:") {
337 fresh = true;
338 }
339
340 engine::reject_non_text_extension(
341 engine_interface_v1,
342 &ctx.project_root,
343 path,
344 &mut engine_policy_admission,
345 )?;
346 // A directory has no text to read; failing with the OS error ("Is a
347 // directory") left the agent guessing. Answer with its entries, as
348 // ctx_tree would, so the next call can name a file.
349 if !engine_interface_v1 && std::path::Path::new(path).is_dir() {
350 let (tree, _) = crate::tools::ctx_tree::handle(path, 1, false, true);
351 if tree.starts_with("ERROR:") {
352 return Err(ErrorData::invalid_params(tree, None));
353 }
354 return Ok(PreparedRead {
355 output: ToolOutput::simple(format!(
356 "{path} is a directory — pass one of its files to ctx_read:\n{tree}"
357 )),
358 delivery: None,
359 });
360 }
361 if lean_ctx::core::binary_detect::is_llm_viewable_image(path) {
362 // Text detectors cannot inspect pixels: the gateway says so, and
363 // withholds the image where every detector is mandatory.
364 let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
365 let note = lean_ctx::core::context_admission::admit_media(path, bytes)
366 .map_err(|error| ErrorData::invalid_params(error.to_string(), None))?;
367 return read_image_file(path).map(|mut output| {
368 if let (Some(note), Some(blocks)) = (note, output.content_blocks.as_mut()) {
369 blocks.push(rmcp::model::ContentBlock::text(note));
370 }
371 PreparedRead {
372 output,
373 delivery: None,
374 }
375 });
376 }
377 if !engine_interface_v1 && lean_ctx::core::binary_detect::is_binary_file(path) {
378 let msg = lean_ctx::core::binary_detect::binary_file_message(path);
379 return Err(ErrorData::invalid_params(msg, None));
380 }
381 if !engine_interface_v1 {
382 let cap = lean_ctx::core::limits::max_read_bytes() as u64;
383 if let Ok(meta) = std::fs::metadata(path)
384 && meta.len() > cap
385 {
386 let msg = format!(
387 "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
388 Use mode=\"lines:1-100\" or start_line+limit for partial reads, \
389 mode=\"anchored\" with start_line+limit for edit-ready windows, \
390 or increase the limit.",
391 meta.len(),
392 cap
393 );
394 return Err(ErrorData::invalid_params(msg, None));
395 }
396 }
397
398 // Compaction-aware: if host compacted since last check, reset delivery flags
399 // so post-compaction reads deliver full content instead of stubs.
400 if !fresh
401 && let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir()
402 && let Ok(mut cache) = cache_lock.try_write()
403 {
404 crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
405 }
406
407 // Fast path: if both per-file lock and cache write-lock are immediately
408 // available, execute inline without spawning a thread. This avoids thread +
409 // channel overhead for the ~90% of calls that are cache hits.
410 let read_timeout = std::time::Duration::from_secs(30);
411 let cancelled = Arc::new(AtomicBool::new(false));
412 let engine_snapshot = engine::SourceSnapshot::default();
413 let pending_cache = Arc::new(Mutex::new(PendingCacheDelivery::default()));
414 // Hash once for cross-agent delivery (avoids re-reading on record).
415 let delivery_metadata = (!engine_interface_v1
416 && lean_ctx::core::config::Config::load()
417 .ocla
418 .delivery_enabled())
419 .then(|| crate::tools::ctx_read::file_blake3_prefix(path))
420 .flatten();
421 let (output, resolved_mode, original, is_cache_hit, file_ref, _cache_stats, reuse_outcome) = {
422 let crp_mode = ctx.crp_mode;
423 let fast_result = 'fast: {
424 let file_lock = per_file_lock(path);
425 let Some(_file_guard) = file_lock.try_lock().ok() else {
426 break 'fast None;
427 };
428
429 // Phase 1 (shared lock): the dominant case is re-reading an
430 // unchanged file. Serve the `[unchanged]` stub under a *read* lock
431 // so parallel reads of distinct files run concurrently instead of
432 // serializing on the global write lock. `auto` is included because
433 // a warm `auto` re-read of a fully-delivered file resolves to a
434 // full cache-hit; `try_stub_hit_readonly` self-guards (returns None
435 // unless full content was delivered and the file is unchanged), so a
436 // first or compressed-only `auto` read still falls through to
437 // Phase 2. When aggressiveness is set `mode` was already rewritten
438 // to `density:` upstream, so it never reaches this `auto` branch.
439 if !fresh
440 && (mode == "full" || mode == "full-compact" || mode == "auto")
441 && let Ok(cache) = cache_lock.try_read()
442 && let Some(read_output) =
443 crate::tools::ctx_read::try_stub_hit_readonly(&cache, path)
444 {
445 let hit = read_output.is_cache_hit;
446 let content = read_output.content;
447 let rmode = read_output.resolved_mode;
448 let orig = cache.get(path).map_or(0, |e| e.original_tokens);
449 let fref = cache.file_ref_map().get(path).cloned();
450 let stats = cache.get_stats();
451 let stats_snapshot = (stats.total_reads(), stats.cache_hits());
452 break 'fast Some((
453 content,
454 rmode,
455 orig,
456 hit,
457 fref,
458 stats_snapshot,
459 ReuseOutcome::UnchangedStub,
460 ));
461 }
462
463 // Misses use the slow path's double-check sequence: it does a
464 // second cache check, computes without the global lock, then
465 // briefly takes a write lock to store the result.
466 None
467 };
468
469 if let Some(result) = fast_result {
470 result
471 } else {
472 let cache_lock = cache_lock.clone();
473 let mode = mode.clone();
474 let task_owned = current_task.clone();
475 let protect_owned = protect.clone();
476 let path_owned = path.to_string();
477 let project_root_owned = ctx.project_root.clone();
478 let cancel_flag = cancelled.clone();
479 let snapshot_worker = engine_snapshot.clone();
480 let pending_cache_worker = pending_cache.clone();
481 let (tx, rx) = std::sync::mpsc::sync_channel(1);
482 lean_ctx::core::task_spine::TaskSpine::spawn_thread(move || {
483 let file_lock = per_file_lock(&path_owned);
484
485 // The per-file lock only deduplicates concurrent reads of
486 // one file. When an earlier read holds it past the
487 // deadline (an abandoned read of a huge file, a slow
488 // mount), this read proceeds without it: duplicate work
489 // beats failing the call — the cache store below has its
490 // own lock, and "retry in a moment" met the same holder.
491 let _file_guard = {
492 let deadline =
493 std::time::Instant::now() + std::time::Duration::from_secs(10);
494 loop {
495 if cancel_flag.load(Ordering::Relaxed) {
496 return;
497 }
498 if let Ok(guard) = file_lock.try_lock() {
499 break Some(guard);
500 }
501 if std::time::Instant::now() >= deadline {
502 tracing::warn!(
503 "ctx_read: per-file lock still held after 10s for \
504 {path_owned}, reading without it"
505 );
506 break None;
507 }
508 std::thread::sleep(std::time::Duration::from_millis(50));
509 }
510 };
511
512 if cancel_flag.load(Ordering::Relaxed) {
513 return;
514 }
515
516 // ── Two-Phase Read (#1098) ──────────────────────────
517 //
518 // Phase 1 (read lock): try the [unchanged] stub — this is the
519 // ~70% case (repeated reads of unchanged files). Previously
520 // missing in the slow path, forcing every slow-path call into
521 // the expensive write-lock branch.
522 if !fresh
523 && (mode == "full" || mode == "full-compact" || mode == "auto")
524 && let Ok(cache) = cache_lock.try_read()
525 && let Some(read_output) =
526 crate::tools::ctx_read::try_stub_hit_readonly(&cache, &path_owned)
527 {
528 let content = read_output.content;
529 let rmode = read_output.resolved_mode;
530 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
531 let hit = true;
532 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
533 let stats = cache.get_stats();
534 let stats_snapshot = (stats.total_reads(), stats.cache_hits());
535 let _ = tx.send((
536 content,
537 rmode,
538 orig,
539 hit,
540 fref,
541 stats_snapshot,
542 ReuseOutcome::UnchangedStub,
543 ));
544 return;
545 }
546
547 // The session-local stub is checked first so the current
548 // agent's own delivery always wins. On a miss, a verified
549 // cross-agent delivery can avoid the disk read below.
550 if !crate::tools::ctx_read::effective_fresh_for_delivery(fresh)
551 && let Some(fp) = delivery_metadata
552 && let Some(read_output) = crate::tools::ctx_read::try_cross_agent_stub(
553 &path_owned,
554 &mode,
555 fp.hash,
556 fp.mtime,
557 crp_mode,
558 crate::tools::ctx_read::ReadTuning::resolve(
559 aggressiveness,
560 &protect_owned,
561 ),
562 )
563 {
564 let _ = tx.send((
565 read_output.content,
566 read_output.resolved_mode,
567 0,
568 read_output.is_cache_hit,
569 None,
570 (0, 0),
571 ReuseOutcome::CrossFileRef,
572 ));
573 return;
574 }
575
576 // Phase 2a: disk I/O under per-file lock but WITHOUT cache lock.
577 let preread = match engine::read_source(
578 engine_interface_v1,
579 &path_owned,
580 &project_root_owned,
581 &snapshot_worker,
582 ) {
583 Ok(c) => Some(c),
584 Err(e) => {
585 tracing::warn!("ctx_read: cannot read {path_owned}: {e}");
586 if engine_interface_v1 {
587 let _ = tx.send((
588 "Engine v1 source read failed".to_owned(),
589 "error".into(),
590 0,
591 false,
592 None,
593 (0, 0),
594 ReuseOutcome::Cold,
595 ));
596 return;
597 }
598 None
599 }
600 };
601
602 if cancel_flag.load(Ordering::Relaxed) {
603 return;
604 }
605
606 // ── Phase 2b: Three-sub-phase read (#807) ──────────
607 //
608 // Previously held the global cache write-lock for the
609 // entire computation (tree-sitter, entropy compression).
610 // For large files this caused 30+ second lock holds and
611 // cascading timeouts for all concurrent tool calls.
612 //
613 // New: prepare (brief lock) → compute (no lock) → store (brief lock).
614
615 // #1590: an inferred task never steers a lossy view.
616 let task_ref = if task_is_inferred {
617 None
618 } else {
619 task_owned.as_deref()
620 };
621 let tuning =
622 crate::tools::ctx_read::ReadTuning::resolve(aggressiveness, &protect_owned);
623
624 // Helper: acquire write lock with deadline. `None` means the
625 // lock stayed contended past the deadline; callers degrade
626 // to an uncached read instead of failing it (#1925).
627 macro_rules! acquire_write {
628 ($deadline_secs:expr, $label:expr) => {{
629 let deadline =
630 std::time::Instant::now() + cache_lock_deadline($deadline_secs);
631 loop {
632 if cancel_flag.load(Ordering::Relaxed) {
633 return;
634 }
635 if let Ok(guard) = cache_lock.try_write() {
636 break Some(guard);
637 }
638 if std::time::Instant::now() >= deadline {
639 tracing::warn!(
640 "ctx_read: cache write-lock timeout ({}) for {path_owned}, \
641 serving uncached",
642 $label,
643 );
644 break None;
645 }
646 std::thread::sleep(std::time::Duration::from_millis(50));
647 }
648 }};
649 }
650
651 // Work that needs no cache state runs before the write lock
652 // (#1925). The first `count_tokens` call builds the BPE tables
653 // (seconds in debug builds); done under the lock it starved
654 // every concurrent read into the deadline. Counting the
655 // preread here also turns the count inside `cache.store()`
656 // into a token-cache hit.
657 let preread_tokens =
658 preread.as_deref().map(lean_ctx::core::tokens::count_tokens);
659 let mode_eff = if mode != "raw"
660 && !mode.starts_with("lines:")
661 && lean_ctx::core::config::Config::load()
662 .proxy
663 .is_path_compress_protected(&path_owned)
664 {
665 "full".to_string()
666 } else {
667 mode.clone()
668 };
669
670 // 2b-i: Brief write lock — prepare cache state, resolve
671 // mode, check for hits. Sub-millisecond: HashMap lookups,
672 // staleness checks, raw-content storage for new files.
673 let (outcome, source_identity) = 'prepare: {
674 let Some(mut cache) = acquire_write!(10, "prepare 10s") else {
675 match prepare_uncached(
676 preread,
677 preread_tokens,
678 &path_owned,
679 &mode_eff,
680 &tuning,
681 task_ref,
682 ) {
683 Ok(uncached) => break 'prepare (uncached, None),
684 Err(msg) => {
685 let _ = tx.send((
686 msg,
687 "error".into(),
688 0,
689 false,
690 None,
691 (0, 0),
692 ReuseOutcome::Cold,
693 ));
694 return;
695 }
696 }
697 };
698 let mut reuse_outcome = if cache_policy_bypassed {
699 ReuseOutcome::PolicyBypass
700 } else if fresh {
701 ReuseOutcome::FreshBypass
702 } else {
703 ReuseOutcome::Cold
704 };
705
706 let file_ref = cache.get_file_ref(&path_owned);
707
708 let effective_fresh = fresh
709 || crate::tools::ctx_read::force_fresh_env()
710 || (crate::tools::ctx_read::is_subagent_context()
711 && !lean_ctx::core::conversation::scope_enabled());
712
713 if effective_fresh {
714 cache.invalidate(&path_owned);
715 }
716
717 if !effective_fresh {
718 // #1584: `diff` is the one mode for which a stale
719 // entry is the *point* — it holds the baseline the
720 // delta is computed against. Dropping it here left
721 // `handle_diff` with nothing to compare and made
722 // every post-edit diff answer "no cached version".
723 // Every other mode still refuses to serve content
724 // that no longer matches the file on disk.
725 let stale = mode_eff != "diff"
726 && cache.get(&path_owned).is_some_and(|e| {
727 lean_ctx::core::cache::is_cache_entry_stale_verified(
728 &path_owned,
729 e.stored_mtime,
730 &e.hash,
731 )
732 });
733 if stale {
734 cache.invalidate(&path_owned);
735 reuse_outcome = ReuseOutcome::Stale;
736 }
737 }
738
739 let snap = cache
740 .get(&path_owned)
741 .map(|e| (e.original_tokens, e.content()));
742
743 // #1584: `diff` is a delta view, not a whole-file
744 // render. It needs the cached baseline and has no arm in
745 // `process_mode_tuned`, so letting it fall through to the
746 // generic compute path made the MCP handler answer
747 // "[WARNING: unknown mode 'diff']" and return the entire
748 // file — while the CLI path handled it correctly. Both
749 // paths now share `handle_diff`.
750 let outcome = if mode_eff == "diff" {
751 // A file that cannot be read is this read's typed
752 // failure (`"error"`, answered as a tool error
753 // below) with the same text — never a `diff` reply.
754 let (out, baseline, diff_mode) = if fresh {
755 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.";
756 (warning.to_string(), None, "diff")
757 } else {
758 match crate::tools::ctx_read::prepare_diff(
759 &cache,
760 &path_owned,
761 &file_ref,
762 ) {
763 Ok((out, _sent, baseline)) => (out, baseline, "diff"),
764 Err(failure) => (failure, None, "error"),
765 }
766 };
767 let out = lean_ctx::core::redaction::redact_text_if_enabled(&out);
768 let orig = baseline.as_deref().map_or_else(
769 || cache.get(&path_owned).map_or(0, |e| e.original_tokens),
770 lean_ctx::core::tokens::count_tokens,
771 );
772 pending_cache_worker
773 .lock()
774 .unwrap_or_else(std::sync::PoisonError::into_inner)
775 .diff_baseline = baseline;
776 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
777 let s = cache.get_stats();
778 PrepareOutcome::Hit(
779 out,
780 diff_mode.to_string(),
781 orig,
782 false,
783 fref,
784 (s.total_reads(), s.cache_hits()),
785 reuse_outcome,
786 )
787 } else if let Some((orig_tok, content_opt)) = snap {
788 let resolved = if mode_eff == "auto" {
789 tuning.auto_density_mode().unwrap_or_else(|| {
790 crate::tools::ctx_read::resolve_unranged_auto_mode(
791 Some(&cache),
792 &path_owned,
793 orig_tok,
794 cache.get(&path_owned).map_or(0, |e| e.line_count),
795 task_ref,
796 )
797 })
798 } else {
799 mode_eff
800 };
801
802 if (resolved == "full" || resolved == "full-compact")
803 && let Some(out) = crate::tools::ctx_read::try_stub_hit_readonly(
804 &cache,
805 &path_owned,
806 )
807 {
808 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
809 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
810 let s = cache.get_stats();
811 PrepareOutcome::Hit(
812 out.content,
813 out.resolved_mode,
814 orig,
815 true,
816 fref,
817 (s.total_reads(), s.cache_hits()),
818 ReuseOutcome::UnchangedStub,
819 )
820 } else if crate::tools::ctx_read::is_cacheable_mode(&resolved) {
821 let ck = crate::tools::ctx_read::request_scoped_key(
822 crate::tools::ctx_read::compressed_cache_key(
823 &resolved,
824 crp_mode,
825 task_ref,
826 tuning.aggressiveness,
827 tuning.protect,
828 ),
829 mode == "auto",
830 );
831 if let Some(hit) = cache.get_compressed(&path_owned, &ck).cloned() {
832 lean_ctx::core::auto_mode_resolver::count_source(
833 "compressed_cache_hit",
834 );
835 let hit =
836 lean_ctx::core::redaction::redact_text_if_enabled(&hit);
837 let orig =
838 cache.get(&path_owned).map_or(0, |e| e.original_tokens);
839 let fref =
840 cache.file_ref_map().get(path_owned.as_str()).cloned();
841 let s = cache.get_stats();
842 PrepareOutcome::Hit(
843 hit,
844 resolved,
845 orig,
846 true,
847 fref,
848 (s.total_reads(), s.cache_hits()),
849 ReuseOutcome::RenderCacheHit,
850 )
851 } else {
852 if reuse_outcome == ReuseOutcome::Cold
853 && cache.was_compressed_variant_evicted(&path_owned, &ck)
854 {
855 reuse_outcome = ReuseOutcome::VariantEvicted;
856 }
857 let c = content_opt
858 .or_else(|| preread.as_deref().map(String::from));
859 PrepareOutcome::Compute {
860 file_ref,
861 resolved_mode: resolved,
862 content: c.unwrap_or_default(),
863 original_tokens: orig_tok,
864 reuse_outcome,
865 cacheable: true,
866 }
867 }
868 } else {
869 let c =
870 content_opt.or_else(|| preread.as_deref().map(String::from));
871 PrepareOutcome::Compute {
872 file_ref,
873 resolved_mode: resolved,
874 content: c.unwrap_or_default(),
875 original_tokens: orig_tok,
876 reuse_outcome,
877 cacheable: true,
878 }
879 }
880 } else {
881 let raw = match preread {
882 Some(c) if !c.is_empty() => c,
883 _ => match crate::tools::ctx_read::read_file_lossy(&path_owned) {
884 Ok(c) if !c.is_empty() => c,
885 Ok(_) => {
886 tracing::debug!(
887 "ctx_read: skipping cache for empty content: {path_owned}"
888 );
889 let _ = tx.send((
890 empty_file_notice(&path_owned),
891 "full".into(),
892 0,
893 false,
894 None,
895 (0, 0),
896 ReuseOutcome::Cold,
897 ));
898 return;
899 }
900 Err(e) => {
901 tracing::debug!(
902 "ctx_read: skipping cache for empty content: {path_owned}"
903 );
904 let _ = tx.send((
905 format!("Cannot read file: {path_owned}: {e}"),
906 "error".into(),
907 0,
908 false,
909 None,
910 (0, 0),
911 ReuseOutcome::Cold,
912 ));
913 return;
914 }
915 },
916 };
917 let sr = cache.store(&path_owned, &raw);
918 let resolved = if mode_eff == "auto" {
919 tuning.auto_density_mode().unwrap_or_else(|| {
920 crate::tools::ctx_read::resolve_unranged_auto_mode(
921 None,
922 &path_owned,
923 sr.original_tokens,
924 sr.line_count,
925 task_ref,
926 )
927 })
928 } else {
929 mode_eff
930 };
931 PrepareOutcome::Compute {
932 file_ref,
933 resolved_mode: resolved,
934 content: raw,
935 original_tokens: sr.original_tokens,
936 reuse_outcome,
937 cacheable: true,
938 }
939 };
940 let identity = cache.get(&path_owned).map(CacheSourceIdentity::from_entry);
941 (outcome, identity)
942 }; // write lock released
943
944 if let PrepareOutcome::Hit(c, rm, orig, hit, fref, ss, reuse_outcome) = outcome
945 {
946 // Update last_mode for compressed-cache hits so the auto-mode
947 // resolver can reuse this mode on future re-reads (#E26).
948 let mut pending = pending_cache_worker
949 .lock()
950 .unwrap_or_else(std::sync::PoisonError::into_inner);
951 let diff_baseline = pending.diff_baseline.take();
952 *pending = PendingCacheDelivery {
953 identity: source_identity,
954 last_mode: Some(rm.clone()),
955 diff_baseline,
956 ..PendingCacheDelivery::default()
957 };
958 let _ = tx.send((c, rm, orig, hit, fref, ss, reuse_outcome));
959 return;
960 }
961 let PrepareOutcome::Compute {
962 file_ref,
963 resolved_mode,
964 content: compute_content,
965 original_tokens,
966 reuse_outcome,
967 cacheable,
968 } = outcome
969 else {
970 unreachable!()
971 };
972
973 if cancel_flag.load(Ordering::Relaxed) {
974 return;
975 }
976
977 // 2b-ii: Heavy computation WITHOUT cache lock.
978 // Tree-sitter, entropy compression, mode rendering all
979 // run under the per-file mutex only (serializes same-file
980 // reads, but does not block other files or tool calls).
981 let short = lean_ctx::core::protocol::shorten_path(&path_owned);
982 let ext_s = std::path::Path::new(&*path_owned)
983 .extension()
984 .and_then(|e| e.to_str())
985 .unwrap_or("");
986
987 let source_hash = blake3::hash(compute_content.as_bytes());
988 let mut source_fingerprint = [0u8; 12];
989 source_fingerprint.copy_from_slice(&source_hash.as_bytes()[..12]);
990 let (mut computed, rmode) = if resolved_mode == "full"
991 || resolved_mode == "full-compact"
992 {
993 if resolved_mode == "full-compact" {
994 let (out, _) = crate::tools::ctx_read::format_full_compact_output(
995 &compute_content,
996 );
997 (out, "full-compact".to_string())
998 } else {
999 let lc = compute_content.lines().count();
1000 let (out, _) = crate::tools::ctx_read::format_full_output(
1001 &file_ref,
1002 &short,
1003 ext_s,
1004 &compute_content,
1005 original_tokens,
1006 lc,
1007 task_ref,
1008 );
1009 let ft = lean_ctx::core::tokens::count_tokens(&out);
1010 let out = crate::tools::ctx_read::cap_to_raw(
1011 out,
1012 ft,
1013 &compute_content,
1014 original_tokens,
1015 "full",
1016 );
1017 (out, "full".to_string())
1018 }
1019 } else {
1020 // #1910: a fallback inside an `auto` read returns the
1021 // bare file, bannerless.
1022 let _auto_guard = (mode == "auto")
1023 .then(crate::tools::ctx_read::render::AutoRequestGuard::new);
1024 let (out, _) = crate::tools::ctx_read::process_mode_tuned(
1025 &compute_content,
1026 &resolved_mode,
1027 &file_ref,
1028 &short,
1029 ext_s,
1030 original_tokens,
1031 crp_mode,
1032 &path_owned,
1033 task_ref,
1034 tuning,
1035 );
1036 let out = if crate::tools::ctx_read::mode_allows_raw_cap(&resolved_mode) {
1037 let ft = lean_ctx::core::tokens::count_tokens(&out);
1038 crate::tools::ctx_read::cap_to_raw(
1039 out,
1040 ft,
1041 &compute_content,
1042 original_tokens,
1043 &resolved_mode,
1044 )
1045 } else {
1046 out
1047 };
1048 (out, resolved_mode)
1049 };
1050
1051 computed = lean_ctx::core::redaction::redact_text_if_enabled(&computed);
1052 if let Some(note) =
1053 lean_ctx::core::context_admission::note_for(&compute_content, &computed)
1054 {
1055 computed.push('\n');
1056 computed.push_str(¬e);
1057 }
1058
1059 if cancel_flag.load(Ordering::Relaxed) {
1060 return;
1061 }
1062
1063 // Warming source bytes is acquisition; variants/full flags imply
1064 // delivery and are committed only if this result is included.
1065 // An uncached fallback (`F?` ref, #1925) never feeds the cache.
1066 let compressed_variant = (cacheable
1067 && crate::tools::ctx_read::is_cacheable_mode(&rmode))
1068 .then(|| {
1069 // #1910: an `auto` request's fallback is bannerless, an
1070 // explicit one is not — they must never share a variant.
1071 let key = crate::tools::ctx_read::request_scoped_key(
1072 crate::tools::ctx_read::compressed_cache_key(
1073 &rmode,
1074 crp_mode,
1075 task_ref,
1076 tuning.aggressiveness,
1077 tuning.protect,
1078 ),
1079 mode == "auto",
1080 );
1081 (key, computed.clone())
1082 });
1083 *pending_cache_worker
1084 .lock()
1085 .unwrap_or_else(std::sync::PoisonError::into_inner) =
1086 PendingCacheDelivery {
1087 identity: source_identity,
1088 compressed_variant,
1089 // A read the turn budget cuts is not a full delivery (#2172).
1090 full_content: cacheable
1091 && matches!(rmode.as_str(), "full" | "full-compact")
1092 && !crate::tools::ctx_read::dedup_hook::exceeds_turn_budget(
1093 &computed,
1094 ),
1095 source_fingerprint: Some(source_fingerprint),
1096 last_mode: cacheable.then(|| rmode.clone()),
1097 record_bounce_read: true,
1098 diff_baseline: None,
1099 };
1100 let _ = tx.send((
1101 computed,
1102 rmode,
1103 original_tokens,
1104 false,
1105 Some(file_ref),
1106 (0, 0),
1107 reuse_outcome,
1108 ));
1109 });
1110 if let Ok(result) = rx.recv_timeout(read_timeout) {
1111 result
1112 } else {
1113 cancelled.store(true, Ordering::Relaxed);
1114 tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
1115 let msg = format!(
1116 "ERROR: ctx_read timed out after {}s reading {path}. \
1117 The file may be very large or a blocking I/O issue occurred. \
1118 Try mode=\"lines:1-100\" for a partial read.",
1119 read_timeout.as_secs()
1120 );
1121 return Err(ErrorData::internal_error(msg, None));
1122 }
1123 } // end else (slow path)
1124 };
1125
1126 engine::reject_read_failure_if_enabled(
1127 engine_interface_v1,
1128 &resolved_mode,
1129 &ctx.project_root,
1130 path,
1131 &mut engine_policy_admission,
1132 )?;
1133 engine::require_aggressive(
1134 engine_interface_v1,
1135 &resolved_mode,
1136 &ctx.project_root,
1137 path,
1138 &mut engine_policy_admission,
1139 )?;
1140 if resolved_mode == "error" {
1141 return Err(ErrorData::invalid_params(output, None));
1142 }
1143
1144 let mut output = output;
1145 // Raw and receipt-backed contracts retain their exact payload. Only a
1146 // newly acquired source can produce a current optional Pro hint.
1147 let code_hint = if !engine_interface_v1 && resolved_mode != "raw" && !is_cache_hit {
1148 engine_snapshot.code_hint(path)
1149 } else {
1150 None
1151 };
1152 let engine_warning = engine_snapshot.record_if_enabled(
1153 &ctx.project_root,
1154 engine_policy_admission,
1155 &mut output,
1156 );
1157 let output_tokens = lean_ctx::core::tokens::count_tokens(&output);
1158
1159 let cache_delivery = std::mem::take(
1160 &mut *pending_cache
1161 .lock()
1162 .unwrap_or_else(std::sync::PoisonError::into_inner),
1163 );
1164 // A pre-read disk hash may describe older bytes. Relay only when it
1165 // agrees with the source that actually supplied this rendered result.
1166 let cross_agent = if is_cache_hit {
1167 None
1168 } else {
1169 delivery_metadata
1170 .filter(|fp| cache_delivery.source_fingerprint.as_ref() == Some(&fp.hash))
1171 .map(|fp| {
1172 let relay_key = (matches!(resolved_mode.as_str(), "map" | "signatures")
1173 && output.len() <= 8192)
1174 .then(|| {
1175 crate::tools::ctx_read::compressed_cache_key(
1176 &resolved_mode,
1177 ctx.crp_mode,
1178 None,
1179 aggressiveness,
1180 &protect,
1181 )
1182 });
1183 PendingCrossAgentDelivery {
1184 hash: fp.hash,
1185 mtime: fp.mtime,
1186 line_count: fp.line_count,
1187 output_tokens,
1188 output: output.clone(),
1189 relay_key,
1190 }
1191 })
1192 };
1193
1194 // #1098: graph-related hints (callers/callees) are now computed AFTER the
1195 // cache lock is released. They involve SQLite queries (~50-200ms) that
1196 // previously blocked all parallel reads while holding the write lock.
1197 let graph_hint = if !is_cache_hit
1198 && !resolved_mode.starts_with("lines:")
1199 && lean_ctx::core::profiles::active_profile()
1200 .output_hints
1201 .related_hint()
1202 {
1203 crate::tools::ctx_read::graph_related_hint(path)
1204 } else {
1205 None
1206 };
1207
1208 // Cross-source hints: gated by profile `cross_source_hint` (default on).
1209 // When enabled, appends issue/PR/schema references from the property
1210 // graph. Skipped when graph.db doesn't exist (#682).
1211 // Legacy graph edges carry no source authority for protected reuse.
1212 // A project linked to an emspace space is indexed in the background
1213 // (detached, never waited for), so its page hints need no provider call.
1214 let hints_on = lean_ctx::core::profiles::active_profile()
1215 .output_hints
1216 .cross_source_hint()
1217 && !lean_ctx::core::policy::runtime::is_active();
1218 if hints_on && lean_ctx::core::providers::emspace::is_linked(&ctx.project_root) {
1219 lean_ctx::core::providers::emspace::refresh_index_if_due(&ctx.project_root);
1220 }
1221 let hints_suffix = if hints_on {
1222 let graph_db =
1223 lean_ctx::core::property_graph::graph_dir(&ctx.project_root).join("graph.db");
1224 let graph = graph_db
1225 .exists()
1226 .then(|| lean_ctx::core::property_graph::CodeGraph::open(&ctx.project_root))
1227 .transpose()
1228 .ok()
1229 .flatten();
1230 graph.map_or_else(String::new, |graph| {
1231 let edges = graph.all_cross_source_edges();
1232 if edges.is_empty() {
1233 String::new()
1234 } else {
1235 let ranges = scoped_read_ranges(&resolved_mode);
1236 let relative_path =
1237 lean_ctx::core::graph_index::graph_relative_key(path, &ctx.project_root);
1238 let hints = lean_ctx::core::cross_source_hints::hints_for_file_matching(
1239 path,
1240 &edges,
1241 &ctx.project_root,
1242 |hint| {
1243 // The far end of the edge is asked again (G04);
1244 // the near end is the file this call just read.
1245 graph.serves_file(&hint.source_uri)
1246 && ranges.as_ref().is_none_or(|ranges| {
1247 hint_intersects_ranges(hint, ranges, &graph, &relative_path)
1248 })
1249 },
1250 );
1251 admitted_hints(&hints)
1252 }
1253 })
1254 } else {
1255 String::new()
1256 };
1257 // pz21 §1.8: a file this session downloaded through a matched
1258 // command is outside text, whatever its path.
1259 note_downloaded_read(path, &ctx.project_root);
1260
1261 // Rule injection (#1325): discover and append rules scoped to this file
1262 // path (CLAUDE.md, AGENTS.md, .cursor/rules, .claude/rules) so the agent
1263 // receives the same context it would get from the native Read tool.
1264 let rules_suffix = {
1265 let client_id = ctx
1266 .client_name
1267 .as_ref()
1268 .map(|c| c.blocking_read().clone())
1269 .unwrap_or_default();
1270 lean_ctx_ext::core::rule_discovery::rules_suffix_for_read(
1271 path,
1272 &ctx.project_root,
1273 &client_id,
1274 )
1275 };
1276 let mut warnings: Vec<&str> = engine_warning.as_deref().into_iter().collect();
1277 if let Some(ref w) = budget_warning {
1278 warnings.push(w.as_str());
1279 }
1280 if let Some(ref w) = delta_explicit_note {
1281 warnings.push(w.as_str());
1282 }
1283 if let Some(ref w) = mode_override_note {
1284 warnings.push(w.as_str());
1285 }
1286 if let Some(ref w) = instruction_mode_note {
1287 warnings.push(w.as_str());
1288 }
1289 let file_summary = extract_file_summary(&output, path);
1290 // Decisions in scope (`.leanctx/decisions`) and hotspot hints (§39):
1291 // foreign content like graph hints.
1292 let graph_suffix = graph_hint.map(|h| format!("\n{h}")).unwrap_or_default()
1293 + &lean_ctx_ext::core::decisions::suffix_for_read(path)
1294 + &lean_ctx_ext::core::hotspots::suffix_for_read(path);
1295 // #977: notices (mode override, budget, delta) go BEFORE the
1296 // payload so client-side truncation of large outputs cannot hide them.
1297 let final_output = if !warnings.is_empty() {
1298 format!(
1299 "{}\n\n{output}{hints_suffix}{graph_suffix}{rules_suffix}",
1300 warnings.join("\n")
1301 )
1302 } else if hints_suffix.is_empty() && graph_suffix.is_empty() && rules_suffix.is_empty() {
1303 output
1304 } else {
1305 format!("{output}{hints_suffix}{graph_suffix}{rules_suffix}")
1306 };
1307 // Source lineage of this reply (G04). The requested file is published
1308 // even when the answer came from a cache or a stub. Everything the
1309 // reply carries from somewhere ELSE — graph neighbours, cross-source
1310 // hints, proactively expanded content — comes from stores whose
1311 // sources are not bound here: the call's source set is then not
1312 // complete and is recorded as such, never as "this file only".
1313 // Rule files are not in that list: `rule_discovery` appends a rule
1314 // only as the admitted rooted reader delivers it, and that reader
1315 // publishes the rule file into this call's source set (or marks the
1316 // set unbound itself when it cannot bind the file).
1317 crate::tools::ctx_read::publish_requested_source(path, &ctx.project_root, "ctx_read");
1318 let assembled_len = final_output.len();
1319 let foreign_content = !hints_suffix.is_empty() || !graph_suffix.is_empty();
1320
1321 // Proactive context: gated by profile `proactive_context` (default off).
1322 // When enabled, auto-expands previously compressed content that is
1323 // keyword-relevant to the current read (up to 2000 tokens).
1324 let final_output = if lean_ctx::core::profiles::active_profile()
1325 .output_hints
1326 .proactive_context()
1327 {
1328 let proactive_query = format!(
1329 "ctx_read path={path} mode={resolved_mode} task={}",
1330 task_ref.unwrap_or_default()
1331 );
1332 if let Some(block) = lean_ctx::core::relevance_tracker::proactive_context_for_path(
1333 &proactive_query,
1334 path,
1335 ) {
1336 format!("{final_output}{block}")
1337 } else {
1338 final_output
1339 }
1340 } else {
1341 final_output
1342 };
1343 if foreign_content || final_output.len() != assembled_len {
1344 lean_ctx::core::archive::authority::mark_unbound();
1345 }
1346
1347 // Keep paid annotations outside the pending source/relay cache payload;
1348 // an expired license must never recover an old paid analysis as fresh.
1349 let final_output = match code_hint {
1350 Some(note) => format!("{final_output}\n\n{note}"),
1351 None => final_output,
1352 };
1353
1354 // Monotonic guard (#1326): re-count tokens on the fully assembled output
1355 // (including hints, warnings, proactive context) and verify the compressed
1356 // result is actually smaller than the original. If annotations inflated the
1357 // output beyond the raw baseline, report zero savings so the ledger stays
1358 // honest. We keep the compressed form (it may still be more useful than raw)
1359 // but correct the accounting.
1360 let final_tokens = lean_ctx::core::tokens::count_tokens(&final_output);
1361 let verified_saved = original.saturating_sub(final_tokens);
1362
1363 let delivery = PendingReadDelivery {
1364 path: path.to_owned(),
1365 cache_delivery,
1366 cross_agent,
1367 file_ref,
1368 file_summary,
1369 resolved_mode: resolved_mode.clone(),
1370 original_tokens: original,
1371 reuse_outcome,
1372 is_cache_hit,
1373 agent_id: resolved_agent_id,
1374 };
1375 Ok(PreparedRead {
1376 delivery: Some(delivery),
1377 output: ToolOutput {
1378 text: final_output,
1379 original_tokens: original,
1380 saved_tokens: verified_saved,
1381 mode: Some(resolved_mode),
1382 path: Some(path.to_string()),
1383 changed: false,
1384 shell_outcome: None,
1385 content_blocks: None,
1386 },
1387 })
1388 }
1389}
1390
1391#[path = "ctx_read_engine.rs"]
1392mod engine;
1393// #660 LOC gate: the MCP tool definition lives in its own module.
1394#[path = "ctx_read_image.rs"]
1395mod image;
1396#[path = "ctx_read_schema.rs"]
1397mod schema;
1398#[path = "ctx_read_symbol.rs"]
1399mod symbol;
1400use image::read_image_file;
1401// #660 LOC gate: leaf helpers live in their own module.
1402#[path = "ctx_read_helpers.rs"]
1403mod helpers;
1404pub(crate) use helpers::task_intent_steers_read;
1405use helpers::{extract_file_summary, record_attribution_result};
1406
1407// #660 LOC gate: cache-lock deadline and the uncached fallback (#1925).
1408#[path = "ctx_read_uncached.rs"]
1409mod uncached;
1410use uncached::{PrepareOutcome, cache_lock_deadline, empty_file_notice, prepare_uncached};
1411
1412#[path = "ctx_read_window.rs"]
1413mod window;
1414// #1993: the batch read resolves `raw=true` the same way.
1415pub(super) use window::resolve_explicit_mode;
1416#[allow(unused_imports)]
1417// lines_mode + resolve_line_window used in #[cfg(test)] ctx_read_inline_tests
1418use window::{
1419 apply_line_window, hint_intersects_ranges, lines_mode, resolve_instruction_file_mode,
1420 resolve_line_window, resolve_raw_alias, scoped_read_ranges,
1421};
1422
1423// #660 LOC gate: inline tests split out to keep this file under the line cap.
1424#[cfg(test)]
1425#[path = "ctx_read_inline_tests.rs"]
1426mod tests;
1427
1428#[cfg(test)]
1429#[path = "ctx_read_security_tests.rs"]
1430mod security_tests;
1431
1432#[cfg(test)]
1433#[path = "ctx_read_gateway_tests.rs"]
1434mod gateway_tests;
1435
1436// #660 LOC gate: repo-param tests split out to keep this file under the line
1437// cap — see `ctx_read_repo_param_tests.rs`.
1438
1439#[cfg(test)]
1440#[path = "ctx_read_repo_param_tests.rs"]
1441mod repo_param_tests;
1442
1443#[cfg(test)]
1444#[path = "ctx_read_override_tests.rs"]
1445mod override_tests;
1446
1447#[path = "ctx_read_origin.rs"]
1448mod origin_parts;
1449use origin_parts::{admitted_hints, note_downloaded_read};