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