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 let _file_guard = {
476 let deadline =
477 std::time::Instant::now() + std::time::Duration::from_secs(25);
478 loop {
479 if cancel_flag.load(Ordering::Relaxed) {
480 return;
481 }
482 if let Ok(guard) = file_lock.try_lock() {
483 break guard;
484 }
485 if std::time::Instant::now() >= deadline {
486 tracing::error!(
487 "ctx_read: per-file lock timeout after 25s for {path_owned}"
488 );
489 let _ = tx.send((
490 format!("per-file lock contention for {path_owned} — retry in a moment"),
491 "error".to_string(),
492 0,
493 false,
494 None,
495 (0, 0),
496 ReuseOutcome::Cold,
497 ));
498 return;
499 }
500 std::thread::sleep(std::time::Duration::from_millis(50));
501 }
502 };
503
504 if cancel_flag.load(Ordering::Relaxed) {
505 return;
506 }
507
508 // ── Two-Phase Read (#1098) ──────────────────────────
509 //
510 // Phase 1 (read lock): try the [unchanged] stub — this is the
511 // ~70% case (repeated reads of unchanged files). Previously
512 // missing in the slow path, forcing every slow-path call into
513 // the expensive write-lock branch.
514 if !fresh
515 && (mode == "full" || mode == "full-compact" || mode == "auto")
516 && let Ok(cache) = cache_lock.try_read()
517 && let Some(read_output) =
518 crate::tools::ctx_read::try_stub_hit_readonly(&cache, &path_owned)
519 {
520 let content = read_output.content;
521 let rmode = read_output.resolved_mode;
522 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
523 let hit = true;
524 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
525 let stats = cache.get_stats();
526 let stats_snapshot = (stats.total_reads(), stats.cache_hits());
527 let _ = tx.send((
528 content,
529 rmode,
530 orig,
531 hit,
532 fref,
533 stats_snapshot,
534 ReuseOutcome::UnchangedStub,
535 ));
536 return;
537 }
538
539 // The session-local stub is checked first so the current
540 // agent's own delivery always wins. On a miss, a verified
541 // cross-agent delivery can avoid the disk read below.
542 if !crate::tools::ctx_read::effective_fresh_for_delivery(fresh)
543 && let Some(fp) = delivery_metadata
544 && let Some(read_output) = crate::tools::ctx_read::try_cross_agent_stub(
545 &path_owned,
546 &mode,
547 fp.hash,
548 fp.mtime,
549 crp_mode,
550 crate::tools::ctx_read::ReadTuning::resolve(
551 aggressiveness,
552 &protect_owned,
553 ),
554 )
555 {
556 let _ = tx.send((
557 read_output.content,
558 read_output.resolved_mode,
559 0,
560 read_output.is_cache_hit,
561 None,
562 (0, 0),
563 ReuseOutcome::CrossFileRef,
564 ));
565 return;
566 }
567
568 // Phase 2a: disk I/O under per-file lock but WITHOUT cache lock.
569 let preread = match engine::read_source(
570 engine_interface_v1,
571 &path_owned,
572 &project_root_owned,
573 &snapshot_worker,
574 ) {
575 Ok(c) => Some(c),
576 Err(e) => {
577 tracing::warn!("ctx_read: cannot read {path_owned}: {e}");
578 if engine_interface_v1 {
579 let _ = tx.send((
580 "Engine v1 source read failed".to_owned(),
581 "error".into(),
582 0,
583 false,
584 None,
585 (0, 0),
586 ReuseOutcome::Cold,
587 ));
588 return;
589 }
590 None
591 }
592 };
593
594 if cancel_flag.load(Ordering::Relaxed) {
595 return;
596 }
597
598 // ── Phase 2b: Three-sub-phase read (#807) ──────────
599 //
600 // Previously held the global cache write-lock for the
601 // entire computation (tree-sitter, entropy compression).
602 // For large files this caused 30+ second lock holds and
603 // cascading timeouts for all concurrent tool calls.
604 //
605 // New: prepare (brief lock) → compute (no lock) → store (brief lock).
606
607 // #1590: an inferred task never steers a lossy view.
608 let task_ref = if task_is_inferred {
609 None
610 } else {
611 task_owned.as_deref()
612 };
613 let tuning =
614 crate::tools::ctx_read::ReadTuning::resolve(aggressiveness, &protect_owned);
615
616 // Helper: acquire write lock with deadline. `None` means the
617 // lock stayed contended past the deadline; callers degrade
618 // to an uncached read instead of failing it (#1925).
619 macro_rules! acquire_write {
620 ($deadline_secs:expr, $label:expr) => {{
621 let deadline =
622 std::time::Instant::now() + cache_lock_deadline($deadline_secs);
623 loop {
624 if cancel_flag.load(Ordering::Relaxed) {
625 return;
626 }
627 if let Ok(guard) = cache_lock.try_write() {
628 break Some(guard);
629 }
630 if std::time::Instant::now() >= deadline {
631 tracing::warn!(
632 "ctx_read: cache write-lock timeout ({}) for {path_owned}, \
633 serving uncached",
634 $label,
635 );
636 break None;
637 }
638 std::thread::sleep(std::time::Duration::from_millis(50));
639 }
640 }};
641 }
642
643 // Work that needs no cache state runs before the write lock
644 // (#1925). The first `count_tokens` call builds the BPE tables
645 // (seconds in debug builds); done under the lock it starved
646 // every concurrent read into the deadline. Counting the
647 // preread here also turns the count inside `cache.store()`
648 // into a token-cache hit.
649 let preread_tokens = preread.as_deref().map(crate::core::tokens::count_tokens);
650 let mode_eff = if mode != "raw"
651 && !mode.starts_with("lines:")
652 && crate::core::config::Config::load()
653 .proxy
654 .is_path_compress_protected(&path_owned)
655 {
656 "full".to_string()
657 } else {
658 mode.clone()
659 };
660
661 // 2b-i: Brief write lock — prepare cache state, resolve
662 // mode, check for hits. Sub-millisecond: HashMap lookups,
663 // staleness checks, raw-content storage for new files.
664 let (outcome, source_identity) = 'prepare: {
665 let Some(mut cache) = acquire_write!(10, "prepare 10s") else {
666 match prepare_uncached(
667 preread,
668 preread_tokens,
669 &path_owned,
670 &mode_eff,
671 &tuning,
672 task_ref,
673 ) {
674 Ok(uncached) => break 'prepare (uncached, None),
675 Err(msg) => {
676 let _ = tx.send((
677 msg,
678 "error".into(),
679 0,
680 false,
681 None,
682 (0, 0),
683 ReuseOutcome::Cold,
684 ));
685 return;
686 }
687 }
688 };
689 let mut reuse_outcome = if cache_policy_bypassed {
690 ReuseOutcome::PolicyBypass
691 } else if fresh {
692 ReuseOutcome::FreshBypass
693 } else {
694 ReuseOutcome::Cold
695 };
696
697 let file_ref = cache.get_file_ref(&path_owned);
698
699 let effective_fresh = fresh
700 || crate::tools::ctx_read::force_fresh_env()
701 || (crate::tools::ctx_read::is_subagent_context()
702 && !crate::core::conversation::scope_enabled());
703
704 if effective_fresh {
705 cache.invalidate(&path_owned);
706 }
707
708 if !effective_fresh {
709 // #1584: `diff` is the one mode for which a stale
710 // entry is the *point* — it holds the baseline the
711 // delta is computed against. Dropping it here left
712 // `handle_diff` with nothing to compare and made
713 // every post-edit diff answer "no cached version".
714 // Every other mode still refuses to serve content
715 // that no longer matches the file on disk.
716 let stale = mode_eff != "diff"
717 && cache.get(&path_owned).is_some_and(|e| {
718 crate::core::cache::is_cache_entry_stale_verified(
719 &path_owned,
720 e.stored_mtime,
721 &e.hash,
722 )
723 });
724 if stale {
725 cache.invalidate(&path_owned);
726 reuse_outcome = ReuseOutcome::Stale;
727 }
728 }
729
730 let snap = cache
731 .get(&path_owned)
732 .map(|e| (e.original_tokens, e.content()));
733
734 // #1584: `diff` is a delta view, not a whole-file
735 // render. It needs the cached baseline and has no arm in
736 // `process_mode_tuned`, so letting it fall through to the
737 // generic compute path made the MCP handler answer
738 // "[WARNING: unknown mode 'diff']" and return the entire
739 // file — while the CLI path handled it correctly. Both
740 // paths now share `handle_diff`.
741 let outcome = if mode_eff == "diff" {
742 let (out, _sent, baseline) = if fresh {
743 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.";
744 (
745 warning.to_string(),
746 crate::core::tokens::count_tokens(warning),
747 None,
748 )
749 } else {
750 crate::tools::ctx_read::prepare_diff(&cache, &path_owned, &file_ref)
751 };
752 let out = crate::core::redaction::redact_text_if_enabled(&out);
753 let orig = baseline.as_deref().map_or_else(
754 || cache.get(&path_owned).map_or(0, |e| e.original_tokens),
755 crate::core::tokens::count_tokens,
756 );
757 pending_cache_worker
758 .lock()
759 .unwrap_or_else(std::sync::PoisonError::into_inner)
760 .diff_baseline = baseline;
761 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
762 let s = cache.get_stats();
763 PrepareOutcome::Hit(
764 out,
765 "diff".to_string(),
766 orig,
767 false,
768 fref,
769 (s.total_reads(), s.cache_hits()),
770 reuse_outcome,
771 )
772 } else if let Some((orig_tok, content_opt)) = snap {
773 let resolved = if mode_eff == "auto" {
774 tuning.auto_density_mode().unwrap_or_else(|| {
775 crate::tools::ctx_read::resolve_auto_mode(
776 Some(&cache),
777 &path_owned,
778 orig_tok,
779 None,
780 task_ref,
781 )
782 })
783 } else {
784 mode_eff
785 };
786
787 if (resolved == "full" || resolved == "full-compact")
788 && let Some(out) = crate::tools::ctx_read::try_stub_hit_readonly(
789 &cache,
790 &path_owned,
791 )
792 {
793 let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
794 let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
795 let s = cache.get_stats();
796 PrepareOutcome::Hit(
797 out.content,
798 out.resolved_mode,
799 orig,
800 true,
801 fref,
802 (s.total_reads(), s.cache_hits()),
803 ReuseOutcome::UnchangedStub,
804 )
805 } else if crate::tools::ctx_read::is_cacheable_mode(&resolved) {
806 let ck = crate::tools::ctx_read::request_scoped_key(
807 crate::tools::ctx_read::compressed_cache_key(
808 &resolved,
809 crp_mode,
810 task_ref,
811 tuning.aggressiveness,
812 tuning.protect,
813 ),
814 mode == "auto",
815 );
816 if let Some(hit) = cache.get_compressed(&path_owned, &ck).cloned() {
817 crate::core::auto_mode_resolver::count_source(
818 "compressed_cache_hit",
819 );
820 let hit = crate::core::redaction::redact_text_if_enabled(&hit);
821 let orig =
822 cache.get(&path_owned).map_or(0, |e| e.original_tokens);
823 let fref =
824 cache.file_ref_map().get(path_owned.as_str()).cloned();
825 let s = cache.get_stats();
826 PrepareOutcome::Hit(
827 hit,
828 resolved,
829 orig,
830 true,
831 fref,
832 (s.total_reads(), s.cache_hits()),
833 ReuseOutcome::RenderCacheHit,
834 )
835 } else {
836 if reuse_outcome == ReuseOutcome::Cold
837 && cache.was_compressed_variant_evicted(&path_owned, &ck)
838 {
839 reuse_outcome = ReuseOutcome::VariantEvicted;
840 }
841 let c = content_opt
842 .or_else(|| preread.as_deref().map(String::from));
843 PrepareOutcome::Compute {
844 file_ref,
845 resolved_mode: resolved,
846 content: c.unwrap_or_default(),
847 original_tokens: orig_tok,
848 reuse_outcome,
849 cacheable: true,
850 }
851 }
852 } else {
853 let c =
854 content_opt.or_else(|| preread.as_deref().map(String::from));
855 PrepareOutcome::Compute {
856 file_ref,
857 resolved_mode: resolved,
858 content: c.unwrap_or_default(),
859 original_tokens: orig_tok,
860 reuse_outcome,
861 cacheable: true,
862 }
863 }
864 } else {
865 let raw = match preread {
866 Some(c) if !c.is_empty() => c,
867 _ => match crate::tools::ctx_read::read_file_lossy(&path_owned) {
868 Ok(c) if !c.is_empty() => c,
869 Ok(_) => {
870 tracing::debug!(
871 "ctx_read: skipping cache for empty content: {path_owned}"
872 );
873 let _ = tx.send((
874 empty_file_notice(&path_owned),
875 "full".into(),
876 0,
877 false,
878 None,
879 (0, 0),
880 ReuseOutcome::Cold,
881 ));
882 return;
883 }
884 Err(e) => {
885 tracing::debug!(
886 "ctx_read: skipping cache for empty content: {path_owned}"
887 );
888 let _ = tx.send((
889 format!("Cannot read file: {path_owned}: {e}"),
890 "error".into(),
891 0,
892 false,
893 None,
894 (0, 0),
895 ReuseOutcome::Cold,
896 ));
897 return;
898 }
899 },
900 };
901 let sr = cache.store(&path_owned, &raw);
902 let resolved = if mode_eff == "auto" {
903 tuning.auto_density_mode().unwrap_or_else(|| {
904 crate::tools::ctx_read::resolve_auto_mode(
905 None,
906 &path_owned,
907 sr.original_tokens,
908 Some(sr.line_count),
909 task_ref,
910 )
911 })
912 } else {
913 mode_eff
914 };
915 PrepareOutcome::Compute {
916 file_ref,
917 resolved_mode: resolved,
918 content: raw,
919 original_tokens: sr.original_tokens,
920 reuse_outcome,
921 cacheable: true,
922 }
923 };
924 let identity = cache.get(&path_owned).map(CacheSourceIdentity::from_entry);
925 (outcome, identity)
926 }; // write lock released
927
928 if let PrepareOutcome::Hit(c, rm, orig, hit, fref, ss, reuse_outcome) = outcome
929 {
930 // Update last_mode for compressed-cache hits so the auto-mode
931 // resolver can reuse this mode on future re-reads (#E26).
932 let mut pending = pending_cache_worker
933 .lock()
934 .unwrap_or_else(std::sync::PoisonError::into_inner);
935 let diff_baseline = pending.diff_baseline.take();
936 *pending = PendingCacheDelivery {
937 identity: source_identity,
938 last_mode: Some(rm.clone()),
939 diff_baseline,
940 ..PendingCacheDelivery::default()
941 };
942 let _ = tx.send((c, rm, orig, hit, fref, ss, reuse_outcome));
943 return;
944 }
945 let PrepareOutcome::Compute {
946 file_ref,
947 resolved_mode,
948 content: compute_content,
949 original_tokens,
950 reuse_outcome,
951 cacheable,
952 } = outcome
953 else {
954 unreachable!()
955 };
956
957 if cancel_flag.load(Ordering::Relaxed) {
958 return;
959 }
960
961 // 2b-ii: Heavy computation WITHOUT cache lock.
962 // Tree-sitter, entropy compression, mode rendering all
963 // run under the per-file mutex only (serializes same-file
964 // reads, but does not block other files or tool calls).
965 let short = crate::core::protocol::shorten_path(&path_owned);
966 let ext_s = std::path::Path::new(&*path_owned)
967 .extension()
968 .and_then(|e| e.to_str())
969 .unwrap_or("");
970
971 let source_hash = blake3::hash(compute_content.as_bytes());
972 let mut source_fingerprint = [0u8; 12];
973 source_fingerprint.copy_from_slice(&source_hash.as_bytes()[..12]);
974 let (mut computed, rmode) = if resolved_mode == "full"
975 || resolved_mode == "full-compact"
976 {
977 if resolved_mode == "full-compact" {
978 let (out, _) = crate::tools::ctx_read::format_full_compact_output(
979 &compute_content,
980 );
981 (out, "full-compact".to_string())
982 } else {
983 let lc = compute_content.lines().count();
984 let (out, _) = crate::tools::ctx_read::format_full_output(
985 &file_ref,
986 &short,
987 ext_s,
988 &compute_content,
989 original_tokens,
990 lc,
991 task_ref,
992 );
993 let ft = crate::core::tokens::count_tokens(&out);
994 let out = crate::tools::ctx_read::cap_to_raw(
995 out,
996 ft,
997 &compute_content,
998 original_tokens,
999 "full",
1000 );
1001 (out, "full".to_string())
1002 }
1003 } else {
1004 // #1910: a fallback inside an `auto` read returns the
1005 // bare file, bannerless.
1006 let _auto_guard = (mode == "auto")
1007 .then(crate::tools::ctx_read::render::AutoRequestGuard::new);
1008 let (out, _) = crate::tools::ctx_read::process_mode_tuned(
1009 &compute_content,
1010 &resolved_mode,
1011 &file_ref,
1012 &short,
1013 ext_s,
1014 original_tokens,
1015 crp_mode,
1016 &path_owned,
1017 task_ref,
1018 tuning,
1019 );
1020 let out = if crate::tools::ctx_read::mode_allows_raw_cap(&resolved_mode) {
1021 let ft = crate::core::tokens::count_tokens(&out);
1022 crate::tools::ctx_read::cap_to_raw(
1023 out,
1024 ft,
1025 &compute_content,
1026 original_tokens,
1027 &resolved_mode,
1028 )
1029 } else {
1030 out
1031 };
1032 (out, resolved_mode)
1033 };
1034
1035 computed = crate::core::redaction::redact_text_if_enabled(&computed);
1036 if let Some(note) = crate::core::context_admission::note_for(&compute_content) {
1037 computed.push('\n');
1038 computed.push_str(¬e);
1039 }
1040
1041 if cancel_flag.load(Ordering::Relaxed) {
1042 return;
1043 }
1044
1045 // Warming source bytes is acquisition; variants/full flags imply
1046 // delivery and are committed only if this result is included.
1047 // An uncached fallback (`F?` ref, #1925) never feeds the cache.
1048 let compressed_variant = (cacheable
1049 && crate::tools::ctx_read::is_cacheable_mode(&rmode))
1050 .then(|| {
1051 // #1910: an `auto` request's fallback is bannerless, an
1052 // explicit one is not — they must never share a variant.
1053 let key = crate::tools::ctx_read::request_scoped_key(
1054 crate::tools::ctx_read::compressed_cache_key(
1055 &rmode,
1056 crp_mode,
1057 task_ref,
1058 tuning.aggressiveness,
1059 tuning.protect,
1060 ),
1061 mode == "auto",
1062 );
1063 (key, computed.clone())
1064 });
1065 *pending_cache_worker
1066 .lock()
1067 .unwrap_or_else(std::sync::PoisonError::into_inner) =
1068 PendingCacheDelivery {
1069 identity: source_identity,
1070 compressed_variant,
1071 full_content: cacheable
1072 && matches!(rmode.as_str(), "full" | "full-compact"),
1073 source_fingerprint: Some(source_fingerprint),
1074 last_mode: cacheable.then(|| rmode.clone()),
1075 record_bounce_read: true,
1076 diff_baseline: None,
1077 };
1078 let _ = tx.send((
1079 computed,
1080 rmode,
1081 original_tokens,
1082 false,
1083 Some(file_ref),
1084 (0, 0),
1085 reuse_outcome,
1086 ));
1087 });
1088 if let Ok(result) = rx.recv_timeout(read_timeout) {
1089 result
1090 } else {
1091 cancelled.store(true, Ordering::Relaxed);
1092 tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
1093 let msg = format!(
1094 "ERROR: ctx_read timed out after {}s reading {path}. \
1095 The file may be very large or a blocking I/O issue occurred. \
1096 Try mode=\"lines:1-100\" for a partial read.",
1097 read_timeout.as_secs()
1098 );
1099 return Err(ErrorData::internal_error(msg, None));
1100 }
1101 } // end else (slow path)
1102 };
1103
1104 engine::reject_read_failure_if_enabled(
1105 engine_interface_v1,
1106 &resolved_mode,
1107 &ctx.project_root,
1108 path,
1109 &mut engine_policy_admission,
1110 )?;
1111 engine::require_aggressive(
1112 engine_interface_v1,
1113 &resolved_mode,
1114 &ctx.project_root,
1115 path,
1116 &mut engine_policy_admission,
1117 )?;
1118 if resolved_mode == "error" {
1119 return Err(ErrorData::invalid_params(output, None));
1120 }
1121
1122 let mut output = output;
1123 // Raw and receipt-backed contracts retain their exact payload. Only a
1124 // newly acquired source can produce a current optional Pro hint.
1125 let code_hint = if !engine_interface_v1 && resolved_mode != "raw" && !is_cache_hit {
1126 engine_snapshot.code_hint(path)
1127 } else {
1128 None
1129 };
1130 let engine_warning = engine_snapshot.record_if_enabled(
1131 &ctx.project_root,
1132 engine_policy_admission,
1133 &mut output,
1134 );
1135 let output_tokens = crate::core::tokens::count_tokens(&output);
1136
1137 let cache_delivery = std::mem::take(
1138 &mut *pending_cache
1139 .lock()
1140 .unwrap_or_else(std::sync::PoisonError::into_inner),
1141 );
1142 // A pre-read disk hash may describe older bytes. Relay only when it
1143 // agrees with the source that actually supplied this rendered result.
1144 let cross_agent = if is_cache_hit {
1145 None
1146 } else {
1147 delivery_metadata
1148 .filter(|fp| cache_delivery.source_fingerprint.as_ref() == Some(&fp.hash))
1149 .map(|fp| {
1150 let relay_key = (matches!(resolved_mode.as_str(), "map" | "signatures")
1151 && output.len() <= 8192)
1152 .then(|| {
1153 crate::tools::ctx_read::compressed_cache_key(
1154 &resolved_mode,
1155 ctx.crp_mode,
1156 None,
1157 aggressiveness,
1158 &protect,
1159 )
1160 });
1161 PendingCrossAgentDelivery {
1162 hash: fp.hash,
1163 mtime: fp.mtime,
1164 line_count: fp.line_count,
1165 output_tokens,
1166 output: output.clone(),
1167 relay_key,
1168 }
1169 })
1170 };
1171
1172 // #1098: graph-related hints (callers/callees) are now computed AFTER the
1173 // cache lock is released. They involve SQLite queries (~50-200ms) that
1174 // previously blocked all parallel reads while holding the write lock.
1175 let graph_hint = if !is_cache_hit
1176 && !resolved_mode.starts_with("lines:")
1177 && crate::core::profiles::active_profile()
1178 .output_hints
1179 .related_hint()
1180 {
1181 crate::tools::ctx_read::graph_related_hint(path)
1182 } else {
1183 None
1184 };
1185
1186 // Cross-source hints: gated by profile `cross_source_hint` (default off).
1187 // When enabled, appends issue/PR/schema references from the property
1188 // graph. Skipped when graph.db doesn't exist (#682).
1189 // Legacy graph edges carry no source authority for protected reuse.
1190 let hints_suffix = if crate::core::profiles::active_profile()
1191 .output_hints
1192 .cross_source_hint()
1193 && !crate::core::policy::runtime::is_active()
1194 {
1195 let graph_db =
1196 crate::core::property_graph::graph_dir(&ctx.project_root).join("graph.db");
1197 let graph = graph_db
1198 .exists()
1199 .then(|| crate::core::property_graph::CodeGraph::open(&ctx.project_root))
1200 .transpose()
1201 .ok()
1202 .flatten();
1203 graph.map_or_else(String::new, |graph| {
1204 let edges = graph.all_cross_source_edges();
1205 if edges.is_empty() {
1206 String::new()
1207 } else {
1208 let ranges = scoped_read_ranges(&resolved_mode);
1209 let relative_path =
1210 crate::core::graph_index::graph_relative_key(path, &ctx.project_root);
1211 let hints = crate::core::cross_source_hints::hints_for_file_matching(
1212 path,
1213 &edges,
1214 &ctx.project_root,
1215 |hint| {
1216 ranges.as_ref().is_none_or(|ranges| {
1217 hint_intersects_ranges(hint, ranges, &graph, &relative_path)
1218 })
1219 },
1220 );
1221 crate::core::cross_source_hints::format_hints(&hints)
1222 }
1223 })
1224 } else {
1225 String::new()
1226 };
1227
1228 // Rule injection (#1325): discover and append rules scoped to this file
1229 // path (CLAUDE.md, AGENTS.md, .cursor/rules, .claude/rules) so the agent
1230 // receives the same context it would get from the native Read tool.
1231 let rules_suffix = {
1232 let client_id = ctx
1233 .client_name
1234 .as_ref()
1235 .map(|c| c.blocking_read().clone())
1236 .unwrap_or_default();
1237 crate::core::rule_discovery::rules_suffix_for_read(path, &ctx.project_root, &client_id)
1238 };
1239 let mut warnings: Vec<&str> = engine_warning.as_deref().into_iter().collect();
1240 if let Some(ref w) = budget_warning {
1241 warnings.push(w.as_str());
1242 }
1243 if let Some(ref w) = degrade_warning {
1244 warnings.push(w.as_str());
1245 }
1246 if let Some(ref w) = delta_explicit_note {
1247 warnings.push(w.as_str());
1248 }
1249 if let Some(ref w) = mode_override_note {
1250 warnings.push(w.as_str());
1251 }
1252 if let Some(ref w) = instruction_mode_note {
1253 warnings.push(w.as_str());
1254 }
1255 let file_summary = extract_file_summary(&output, path);
1256 let graph_suffix = graph_hint.map(|h| format!("\n{h}")).unwrap_or_default();
1257 // #977: notices (mode override, budget, degradation, delta) go BEFORE the
1258 // payload so client-side truncation of large outputs cannot hide them.
1259 let final_output = if !warnings.is_empty() {
1260 format!(
1261 "{}\n\n{output}{hints_suffix}{graph_suffix}{rules_suffix}",
1262 warnings.join("\n")
1263 )
1264 } else if hints_suffix.is_empty() && graph_suffix.is_empty() && rules_suffix.is_empty() {
1265 output
1266 } else {
1267 format!("{output}{hints_suffix}{graph_suffix}{rules_suffix}")
1268 };
1269 // Proactive context: gated by profile `proactive_context` (default off).
1270 // When enabled, auto-expands previously compressed content that is
1271 // keyword-relevant to the current read (up to 2000 tokens).
1272 let final_output = if crate::core::profiles::active_profile()
1273 .output_hints
1274 .proactive_context()
1275 {
1276 let proactive_query = format!(
1277 "ctx_read path={path} mode={resolved_mode} task={}",
1278 task_ref.unwrap_or_default()
1279 );
1280 if let Some(block) =
1281 crate::core::relevance_tracker::proactive_context_for_path(&proactive_query, path)
1282 {
1283 format!("{final_output}{block}")
1284 } else {
1285 final_output
1286 }
1287 } else {
1288 final_output
1289 };
1290
1291 // Keep paid annotations outside the pending source/relay cache payload;
1292 // an expired license must never recover an old paid analysis as fresh.
1293 let final_output = match code_hint {
1294 Some(note) => format!("{final_output}\n\n{note}"),
1295 None => final_output,
1296 };
1297
1298 // Monotonic guard (#1326): re-count tokens on the fully assembled output
1299 // (including hints, warnings, proactive context) and verify the compressed
1300 // result is actually smaller than the original. If annotations inflated the
1301 // output beyond the raw baseline, report zero savings so the ledger stays
1302 // honest. We keep the compressed form (it may still be more useful than raw)
1303 // but correct the accounting.
1304 let final_tokens = crate::core::tokens::count_tokens(&final_output);
1305 let verified_saved = original.saturating_sub(final_tokens);
1306
1307 let delivery = PendingReadDelivery {
1308 path: path.to_owned(),
1309 cache_delivery,
1310 cross_agent,
1311 file_ref,
1312 file_summary,
1313 resolved_mode: resolved_mode.clone(),
1314 original_tokens: original,
1315 reuse_outcome,
1316 is_cache_hit,
1317 agent_id: resolved_agent_id,
1318 };
1319 Ok(PreparedRead {
1320 delivery: Some(delivery),
1321 output: ToolOutput {
1322 text: final_output,
1323 original_tokens: original,
1324 saved_tokens: verified_saved,
1325 mode: Some(resolved_mode),
1326 path: Some(path.to_string()),
1327 changed: false,
1328 shell_outcome: None,
1329 content_blocks: None,
1330 },
1331 })
1332 }
1333}
1334
1335#[path = "ctx_read_engine.rs"]
1336mod engine;
1337// #660 LOC gate: the MCP tool definition lives in its own module.
1338#[path = "ctx_read_image.rs"]
1339mod image;
1340#[path = "ctx_read_schema.rs"]
1341mod schema;
1342use image::read_image_file;
1343// #660 LOC gate: leaf helpers live in their own module.
1344#[path = "ctx_read_helpers.rs"]
1345mod helpers;
1346pub(crate) use helpers::task_intent_steers_read;
1347// `apply_verdict`'s only caller in this module is the inline test file, which
1348// reaches it as `super::apply_verdict` — hence the cfg(test) import.
1349#[cfg(test)]
1350use helpers::apply_verdict;
1351use helpers::{auto_degrade_read_mode, extract_file_summary, record_attribution_result};
1352
1353// #660 LOC gate: cache-lock deadline and the uncached fallback (#1925).
1354#[path = "ctx_read_uncached.rs"]
1355mod uncached;
1356use uncached::{PrepareOutcome, cache_lock_deadline, empty_file_notice, prepare_uncached};
1357
1358#[path = "ctx_read_window.rs"]
1359mod window;
1360// #1993: the batch read resolves `raw=true` the same way.
1361pub(super) use window::resolve_explicit_mode;
1362#[allow(unused_imports)]
1363// lines_mode + resolve_line_window used in #[cfg(test)] ctx_read_inline_tests
1364use window::{
1365 apply_line_window, hint_intersects_ranges, lines_mode, resolve_instruction_file_mode,
1366 resolve_line_window, resolve_raw_alias, scoped_read_ranges,
1367};
1368
1369// #660 LOC gate: inline tests split out to keep this file under the line cap.
1370#[cfg(test)]
1371#[path = "ctx_read_inline_tests.rs"]
1372mod tests;
1373
1374#[cfg(test)]
1375#[path = "ctx_read_security_tests.rs"]
1376mod security_tests;
1377
1378#[cfg(test)]
1379#[path = "ctx_read_gateway_tests.rs"]
1380mod gateway_tests;
1381
1382// #660 LOC gate: repo-param tests split out to keep this file under the line
1383// cap — see `ctx_read_repo_param_tests.rs`.
1384
1385#[cfg(test)]
1386#[path = "ctx_read_repo_param_tests.rs"]
1387mod repo_param_tests;
1388
1389#[cfg(test)]
1390#[path = "ctx_read_override_tests.rs"]
1391mod override_tests;