Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::{Arc, Mutex};
3
4use rmcp::ErrorData;
5use rmcp::model::Tool;
6use serde_json::{Map, Value, json};
7
8use crate::server::tool_trait::{
9    McpTool, ToolContext, ToolOutput, get_bool, get_f64, get_int, get_str, get_str_array,
10    require_resolved_path,
11};
12use crate::tool_defs::tool_def;
13
14/// Per-file lock that serializes concurrent reads of the same path.
15///
16/// When multiple subagents read sequentially through a shared set of files,
17/// they tend to hit the same path at the same time. Without per-file locking
18/// they all contend on the global cache write lock while doing redundant I/O.
19/// This lock ensures only one thread reads a given file from disk; the others
20/// wait cheaply on the per-file mutex, then hit the warm cache.
21///
22/// Backed by the shared `core::path_locks` registry so reads and edits of the
23/// same path coordinate through a single mutex (see issue #320).
24fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
25    crate::core::path_locks::per_file_lock(path)
26}
27
28pub struct CtxReadTool;
29
30impl McpTool for CtxReadTool {
31    fn name(&self) -> &'static str {
32        "ctx_read"
33    }
34
35    fn tool_def(&self) -> Tool {
36        tool_def(
37            "ctx_read",
38            "Read source files. mode REQUIRED — choose by intent (see `mode` below).\n\
39             To UNDERSTAND code run ctx_compose FIRST; ctx_read after it identified files.\n\
40             anchored → edit by reference via ctx_patch (no exact-recall).",
41            json!({
42                "type": "object",
43                "properties": {
44                    "path": { "type": "string", "description": "Absolute path" },
45                    "paths": { "type": "array", "items": { "type": "string" }, "description": "Batch read" },
46                    "mode": {
47                        "type": "string",
48                        "description": "REQUIRED. full=verbatim(edit-ready) anchored=full+N:hh|anchors(edit via ctx_patch) raw=exact-bytes signatures=API map=structure auto=smart diff=git-delta lines:N-M=window (comma multi-selects: lines:5,10-20) reference=quotes task=focus"
49                    },
50                    "raw": { "type": "boolean", "description": "Verbatim (= mode=raw + fresh)" },
51                    "start_line": { "type": "integer", "description": "1-based" },
52                    "offset": { "type": "integer", "description": "start_line alias" },
53                    "limit": { "type": "integer", "description": "Max lines" },
54                    "fresh": { "type": "boolean", "description": "Bypass cache" },
55                    "aggressiveness": { "type": "number", "description": "0.0–1.0 density (entropy/task)" },
56                    "protect": { "type": "array", "items": { "type": "string" }, "description": "Symbols kept verbatim" }
57                },
58                "required": []
59            }),
60        )
61    }
62
63    fn handle(
64        &self,
65        args: &Map<String, Value>,
66        ctx: &ToolContext,
67    ) -> Result<ToolOutput, ErrorData> {
68        // #509: ctx_read absorbs multi-file batch reads (supersedes ctx_multi_read).
69        // A non-empty `paths` array routes to the one shared batch implementation.
70        if args
71            .get("paths")
72            .and_then(|v| v.as_array())
73            .is_some_and(|a| !a.is_empty())
74        {
75            return super::ctx_multi_read::batch_read(args, ctx);
76        }
77
78        let path = if let Some(repo) = get_str(args, "repo") {
79            let root = crate::core::multi_repo::resolve_repo_root(&repo).ok_or_else(|| {
80                let known = crate::core::multi_repo::known_aliases().join(", ");
81                let known = if known.is_empty() {
82                    "none registered — use ctx_multi_repo add_root".to_string()
83                } else {
84                    known
85                };
86                ErrorData::invalid_params(
87                    format!("unknown repo alias: {repo} (known: {known})"),
88                    None,
89                )
90            })?;
91            let rel = get_str(args, "path").unwrap_or_else(|| ".".to_string());
92            crate::core::path_resolve::resolve_tool_path(Some(&root), None, &rel)
93                .map_err(|e| ErrorData::invalid_params(e, None))?
94        } else {
95            require_resolved_path(ctx, args, "path")?
96        };
97
98        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
99            self.handle_inner(args, ctx, &path)
100        })) {
101            Ok(result) => result,
102            Err(_) => Err(ErrorData::internal_error(
103                format!(
104                    "ctx_read panicked while processing '{path}'. This is a bug — please report it."
105                ),
106                None,
107            )),
108        }
109    }
110}
111
112impl CtxReadTool {
113    #[allow(clippy::unused_self)]
114    fn handle_inner(
115        &self,
116        args: &Map<String, Value>,
117        ctx: &ToolContext,
118        path: &str,
119    ) -> Result<ToolOutput, ErrorData> {
120        let session_lock = ctx
121            .session
122            .as_ref()
123            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
124        let cache_lock = ctx
125            .cache
126            .as_ref()
127            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
128
129        let current_task = {
130            let rt = tokio::runtime::Handle::current();
131            let mut attempt = 0u32;
132            loop {
133                if let Ok(session) = rt.block_on(tokio::time::timeout(
134                    std::time::Duration::from_secs(5),
135                    session_lock.read(),
136                )) {
137                    break session.task.as_ref().map(|t| t.description.clone());
138                }
139                attempt += 1;
140                if attempt >= 3 {
141                    tracing::warn!(
142                        "session read-lock timeout after {attempt} attempts in ctx_read for {path}"
143                    );
144                    return Err(ErrorData::internal_error(
145                        "session lock timeout — another tool may be holding it. Retry in a moment.",
146                        None,
147                    ));
148                }
149                tracing::debug!(
150                    "session read-lock attempt {attempt}/3 timed out for {path}, retrying"
151                );
152                std::thread::sleep(std::time::Duration::from_millis(100 * u64::from(attempt)));
153            }
154        };
155        let task_ref = current_task.as_deref();
156
157        let profile = crate::core::profiles::active_profile();
158        // #513: `raw=true` is the intuitive "give me the exact bytes" escape an
159        // agent reaches for. Alias it to mode="raw" (verbatim, unframed) and
160        // force a fresh disk read below so a re-read never collapses to an
161        // `[unchanged]`/auto-delta stub. An explicit raw flag wins over `mode`.
162        let arg_raw = get_bool(args, "raw").unwrap_or(false);
163        let explicit_mode_arg = resolve_raw_alias(arg_raw, get_str(args, "mode"));
164        let explicit_mode = explicit_mode_arg.is_some();
165        // #673 — when the caller omits `mode`, a context policy pack's
166        // `default_read_mode` (if set) takes precedence over the profile/auto
167        // selection. An explicit `mode` arg always wins; line windows below may
168        // still narrow it (it is a default, not a pin).
169        let policy_default_mode = if explicit_mode {
170            None
171        } else {
172            crate::core::policy::runtime::active()
173                .and_then(|p| p.resolved.default_read_mode.clone())
174        };
175        // persona-spec-v1 — the active persona's `default_read_mode` is the
176        // domain default: after an explicit arg and the org policy pack,
177        // before the profile/auto selection. The `coding` default declares
178        // "auto" → no override, so existing installs are unaffected.
179        let persona_default_mode = if explicit_mode || policy_default_mode.is_some() {
180            None
181        } else {
182            crate::core::persona::active().read_mode_override()
183        };
184        let mut mode = if let Some(m) = explicit_mode_arg {
185            m
186        } else if let Some(pd) = policy_default_mode {
187            pd
188        } else if let Some(pm) = persona_default_mode {
189            pm
190        } else if profile.read.default_mode_effective() == "auto" {
191            if let Ok(cache) = cache_lock.try_read() {
192                crate::tools::ctx_smart_read::select_mode_with_task(&cache, path, task_ref)
193            } else {
194                tracing::debug!(
195                    "cache lock contested during auto-mode selection for {path}; \
196                     falling back to full"
197                );
198                "full".to_string()
199            }
200        } else {
201            profile.read.default_mode_effective().to_string()
202        };
203        let mut fresh = get_bool(args, "fresh").unwrap_or(false);
204        // #513: a raw/verbatim request always reads from disk — the whole point
205        // is exact current bytes, never a cached stub or delta.
206        if arg_raw {
207            fresh = true;
208        }
209        let cache_policy = crate::server::compaction_sync::effective_cache_policy();
210        if cache_policy == "off" {
211            fresh = true;
212        }
213        let aggressiveness =
214            crate::core::aggressiveness::effective(get_f64(args, "aggressiveness"));
215        let protect = get_str_array(args, "protect").unwrap_or_default();
216        // One-knob UX: when the caller sets aggressiveness without pinning a mode,
217        // route through the proven density path at the mapped target. An explicit
218        // mode (incl. entropy/task) instead has the knob tune it via ReadTuning.
219        if !explicit_mode && let Some(a) = aggressiveness {
220            // SSOT mode construction via the typed `ReadMode` (#528): the typed
221            // `Density` Display emits the same `density:0.NN` the pipeline parses.
222            mode = crate::tools::ctx_read::ReadMode::Density(
223                crate::core::aggressiveness::AggressivenessProfile::from_level(a).density_target,
224            )
225            .to_string();
226        }
227        // `start_line` (and its `offset`/`limit` aliases) can pin a line window.
228        // The resolution lives in `apply_line_window`/`resolve_line_window` so
229        // the runtime path and the unit tests share one implementation and can
230        // never drift (GitHub #432 aliases, #259 explicit-mode, #253 line-1).
231        apply_line_window(
232            &mut mode,
233            &mut fresh,
234            explicit_mode,
235            get_int(args, "start_line"),
236            get_int(args, "offset"),
237            get_int(args, "limit"),
238        );
239
240        let pressure_action = ctx.pressure_snapshot.as_ref().map(|p| &p.recommendation);
241        let resolved_agent_id = ctx.agent_id.as_ref().and_then(|a| match a.try_read() {
242            Ok(guard) => guard.clone(),
243            Err(_) => None,
244        });
245        let gate_result = crate::server::context_gate::pre_dispatch_read_for_agent(
246            path,
247            &mode,
248            task_ref,
249            Some(&ctx.project_root),
250            pressure_action,
251            resolved_agent_id.as_deref(),
252        );
253        if gate_result.budget_blocked {
254            let msg = gate_result
255                .budget_warning
256                .unwrap_or_else(|| "Agent token budget exceeded".to_string());
257            return Err(ErrorData::invalid_params(msg, None));
258        }
259        let budget_warning = gate_result.budget_warning.clone();
260        // #513: an explicit raw/verbatim request is never silently downgraded by
261        // the budget gate — the caller asked for exact bytes.
262        if mode != "raw"
263            && let Some(overridden) = gate_result.overridden_mode
264        {
265            mode = overridden;
266        }
267
268        let (mut mode, degrade_warning) = if crate::tools::ctx_read::is_instruction_file(path) {
269            ("full".to_string(), None)
270        } else if mode == "raw" {
271            // #513: raw bypasses context-pressure degradation (which would
272            // otherwise downgrade to signatures under Block), exactly like
273            // instruction files — verbatim means verbatim.
274            ("raw".to_string(), None)
275        } else {
276            auto_degrade_read_mode(&mode)
277        };
278
279        // Delta-aware explicit re-reads (opt-in: config `delta_explicit`, env
280        // LCTX_DELTA_EXPLICIT). Re-requesting full/lines:N-M content for a file
281        // this session already read re-emits content the model already holds;
282        // when the file changed on disk, a diff carries the same information in
283        // a fraction of the tokens, and an unchanged lines: request of a
284        // fully-delivered file collapses to the full-mode stub. The decision is
285        // a pure function of (cache, path, mode) — see
286        // `ctx_read::resolve_explicit_delta_mode`. First reads are unaffected;
287        // fresh=true always bypasses. Runs BEFORE the lines:→fresh guard below
288        // so a changed-file lines: re-read can still be diverted to a diff.
289        let mut delta_explicit_note: Option<String> = None;
290        if !fresh
291            && explicit_mode
292            && (mode == "full" || mode.starts_with("lines:"))
293            && crate::core::config::Config::load().delta_explicit_effective()
294            && let Ok(cache) = cache_lock.try_read()
295        {
296            let decision = crate::tools::ctx_read::resolve_explicit_delta_mode(
297                &cache,
298                path,
299                &mode,
300                explicit_mode,
301                fresh,
302                true,
303            );
304            mode = decision.mode;
305            delta_explicit_note = decision.note;
306        }
307
308        if mode.starts_with("lines:") {
309            fresh = true;
310        }
311
312        if crate::core::binary_detect::is_binary_file(path) {
313            let msg = crate::core::binary_detect::binary_file_message(path);
314            return Err(ErrorData::invalid_params(msg, None));
315        }
316        {
317            let cap = crate::core::limits::max_read_bytes() as u64;
318            if let Ok(meta) = std::fs::metadata(path)
319                && meta.len() > cap
320            {
321                let msg = format!(
322                    "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
323                         Use mode=\"lines:1-100\" for partial reads or increase the limit.",
324                    meta.len(),
325                    cap
326                );
327                return Err(ErrorData::invalid_params(msg, None));
328            }
329        }
330
331        // Compaction-aware: if host compacted since last check, reset delivery flags
332        // so post-compaction reads deliver full content instead of stubs.
333        if !fresh
334            && let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir()
335            && let Ok(mut cache) = cache_lock.try_write()
336        {
337            crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
338        }
339
340        // Fast path: if both per-file lock and cache write-lock are immediately
341        // available, execute inline without spawning a thread. This avoids thread +
342        // channel overhead for the ~90% of calls that are cache hits.
343        let read_timeout = std::time::Duration::from_secs(30);
344        let cancelled = Arc::new(AtomicBool::new(false));
345        let (output, resolved_mode, original, is_cache_hit, file_ref, cache_stats) = {
346            let crp_mode = ctx.crp_mode;
347            let task_ref = current_task.as_deref();
348
349            let fast_result = 'fast: {
350                let file_lock = per_file_lock(path);
351                let Some(_file_guard) = file_lock.try_lock().ok() else {
352                    break 'fast None;
353                };
354
355                // Phase 1 (shared lock): the dominant case is re-reading an
356                // unchanged file. Serve the `[unchanged]` stub under a *read* lock
357                // so parallel reads of distinct files run concurrently instead of
358                // serializing on the global write lock. `auto` is included because
359                // a warm `auto` re-read of a fully-delivered file resolves to a
360                // full cache-hit; `try_stub_hit_readonly` self-guards (returns None
361                // unless full content was delivered and the file is unchanged), so a
362                // first or compressed-only `auto` read still falls through to
363                // Phase 2. When aggressiveness is set `mode` was already rewritten
364                // to `density:` upstream, so it never reaches this `auto` branch.
365                if !fresh
366                    && (mode == "full" || mode == "auto")
367                    && let Ok(cache) = cache_lock.try_read()
368                    && let Some(read_output) =
369                        crate::tools::ctx_read::try_stub_hit_readonly(&cache, path)
370                {
371                    let content = read_output.content;
372                    let rmode = read_output.resolved_mode;
373                    let orig = cache.get(path).map_or(0, |e| e.original_tokens);
374                    let hit = content.contains(" cached ")
375                        || content.contains("[unchanged")
376                        || content.contains("[delta:");
377                    let fref = cache.file_ref_map().get(path).cloned();
378                    let stats = cache.get_stats();
379                    let stats_snapshot = (stats.total_reads(), stats.cache_hits());
380                    break 'fast Some((content, rmode, orig, hit, fref, stats_snapshot));
381                }
382
383                // Phase 2 (write lock): cache miss, changed file, or non-stub
384                // modes (map/signatures/diff/lines) that mutate cache state.
385                let Some(mut cache) = cache_lock.try_write().ok() else {
386                    break 'fast None;
387                };
388                let read_output = if fresh {
389                    crate::tools::ctx_read::handle_fresh_with_task_resolved_tuned(
390                        &mut cache,
391                        path,
392                        &mode,
393                        crp_mode,
394                        task_ref,
395                        aggressiveness,
396                        &protect,
397                    )
398                } else {
399                    crate::tools::ctx_read::handle_with_task_resolved_tuned(
400                        &mut cache,
401                        path,
402                        &mode,
403                        crp_mode,
404                        task_ref,
405                        aggressiveness,
406                        &protect,
407                    )
408                };
409                let content = read_output.content;
410                let rmode = read_output.resolved_mode;
411                let orig = cache.get(path).map_or(0, |e| e.original_tokens);
412                let hit = content.contains(" cached ")
413                    || content.contains("[unchanged")
414                    || content.contains("[delta:");
415                let fref = cache.file_ref_map().get(path).cloned();
416                let stats = cache.get_stats();
417                let stats_snapshot = (stats.total_reads(), stats.cache_hits());
418                Some((content, rmode, orig, hit, fref, stats_snapshot))
419            };
420
421            if let Some(result) = fast_result {
422                result
423            } else {
424                let cache_lock = cache_lock.clone();
425                let mode = mode.clone();
426                let task_owned = current_task.clone();
427                let protect_owned = protect.clone();
428                let path_owned = path.to_string();
429                let cancel_flag = cancelled.clone();
430                let (tx, rx) = std::sync::mpsc::sync_channel(1);
431                std::thread::spawn(move || {
432                    let file_lock = per_file_lock(&path_owned);
433
434                    // Bounded per-file lock: if a zombie thread still holds it, don't
435                    // wait forever. 25s keeps us inside the 30s recv_timeout.
436                    let _file_guard = {
437                        let deadline =
438                            std::time::Instant::now() + std::time::Duration::from_secs(25);
439                        loop {
440                            if cancel_flag.load(Ordering::Relaxed) {
441                                return;
442                            }
443                            if let Ok(guard) = file_lock.try_lock() {
444                                break guard;
445                            }
446                            if std::time::Instant::now() >= deadline {
447                                tracing::error!(
448                                    "ctx_read: per-file lock timeout after 25s for {path_owned}"
449                                );
450                                let _ = tx.send((
451                                    format!("per-file lock contention for {path_owned} — retry in a moment"),
452                                    "error".to_string(), 0, false, None, (0, 0),
453                                ));
454                                return;
455                            }
456                            std::thread::sleep(std::time::Duration::from_millis(50));
457                        }
458                    };
459
460                    if cancel_flag.load(Ordering::Relaxed) {
461                        return;
462                    }
463
464                    // Bounded cache write-lock: avoids indefinite block when a zombie
465                    // thread from a previous timed-out call still holds the lock.
466                    let mut cache = {
467                        let deadline =
468                            std::time::Instant::now() + std::time::Duration::from_secs(25);
469                        loop {
470                            if cancel_flag.load(Ordering::Relaxed) {
471                                return;
472                            }
473                            if let Ok(guard) = cache_lock.try_write() {
474                                break guard;
475                            }
476                            if std::time::Instant::now() >= deadline {
477                                tracing::error!(
478                                    "ctx_read: cache write-lock timeout after 25s for {path_owned}"
479                                );
480                                let _ = tx.send((
481                                    format!(
482                                        "cache lock contention for {path_owned} — retry in a moment"
483                                    ),
484                                    "error".to_string(),
485                                    0,
486                                    false,
487                                    None,
488                                    (0, 0),
489                                ));
490                                return;
491                            }
492                            std::thread::sleep(std::time::Duration::from_millis(50));
493                        }
494                    };
495
496                    let task_ref = task_owned.as_deref();
497                    let read_output = if fresh {
498                        crate::tools::ctx_read::handle_fresh_with_task_resolved_tuned(
499                            &mut cache,
500                            &path_owned,
501                            &mode,
502                            crp_mode,
503                            task_ref,
504                            aggressiveness,
505                            &protect_owned,
506                        )
507                    } else {
508                        crate::tools::ctx_read::handle_with_task_resolved_tuned(
509                            &mut cache,
510                            &path_owned,
511                            &mode,
512                            crp_mode,
513                            task_ref,
514                            aggressiveness,
515                            &protect_owned,
516                        )
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 = content.contains(" cached ");
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((content, rmode, orig, hit, fref, stats_snapshot));
526                });
527                if let Ok(result) = rx.recv_timeout(read_timeout) {
528                    result
529                } else {
530                    cancelled.store(true, Ordering::Relaxed);
531                    tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
532                    let msg = format!(
533                        "ERROR: ctx_read timed out after {}s reading {path}. \
534                     The file may be very large or a blocking I/O issue occurred. \
535                     Try mode=\"lines:1-100\" for a partial read.",
536                        read_timeout.as_secs()
537                    );
538                    return Err(ErrorData::internal_error(msg, None));
539                }
540            } // end else (slow path)
541        };
542
543        if resolved_mode == "error" {
544            return Err(ErrorData::invalid_params(output, None));
545        }
546
547        let output_tokens = crate::core::tokens::count_tokens(&output);
548        let saved = original.saturating_sub(output_tokens);
549
550        // Session updates (bounded lock — 10s timeout, read already succeeded)
551        let mut ensured_root: Option<String> = None;
552        let mut traversal_working_set: Vec<String> = Vec::new();
553        let project_root_snapshot;
554        {
555            let rt = tokio::runtime::Handle::current();
556            let session_guard = rt.block_on(tokio::time::timeout(
557                std::time::Duration::from_secs(10),
558                session_lock.write(),
559            ));
560            if let Ok(mut session) = session_guard {
561                session.touch_file(path, file_ref.as_deref(), &resolved_mode, original);
562                // Capture the recent working set (under the lock) so the
563                // background thread can record a traversal/co-access edge (#289).
564                traversal_working_set =
565                    crate::core::tool_lifecycle::recent_working_set(&session, path);
566                let file_summary = extract_file_summary(&output, path);
567                if !file_summary.is_empty() {
568                    session.set_file_summary(path, &file_summary);
569                }
570                if is_cache_hit {
571                    session.record_cache_hit();
572                }
573                if session.active_structured_intent.is_none() && session.files_touched.len() >= 2 {
574                    let touched: Vec<String> = session
575                        .files_touched
576                        .iter()
577                        .map(|f| f.path.clone())
578                        .collect();
579                    let inferred =
580                        crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
581                    if inferred.confidence >= 0.4 {
582                        session.active_structured_intent = Some(inferred);
583                    }
584                }
585                if session.task.is_none() && session.stats.files_read % 5 == 0 {
586                    session.auto_infer_task();
587                }
588                let root_missing = session
589                    .project_root
590                    .as_deref()
591                    .is_none_or(|r| r.trim().is_empty());
592                if root_missing && let Some(root) = crate::core::protocol::detect_project_root(path)
593                {
594                    session.project_root = Some(root.clone());
595                    ensured_root = Some(root);
596                }
597                project_root_snapshot = session
598                    .project_root
599                    .clone()
600                    .unwrap_or_else(|| ".".to_string());
601            } else {
602                tracing::warn!(
603                    "session write-lock timeout (5s) in ctx_read post-update for {path}"
604                );
605                project_root_snapshot = ctx.project_root.clone();
606            }
607        }
608
609        if let Some(root) = ensured_root.as_deref() {
610            crate::core::index_orchestrator::ensure_all_background(root);
611        }
612
613        // Telemetry + learning are pure side-effects that never influence this
614        // response, yet they did synchronous disk I/O on every read (heatmap
615        // append, ModePredictor load+save, FeedbackStore load). Push them off
616        // the hot path so reads — especially cache-hit stubs — return without
617        // waiting on disk (#149).
618        {
619            let path_bg = path.to_string();
620            let resolved_mode_bg = resolved_mode.clone();
621            let project_root_bg = project_root_snapshot.clone();
622            let (turns, hits) = cache_stats;
623            // #685: model-correct verified-ledger inputs, computed off the hot path.
624            // The default O200kBase model reuses the o200k `original`/`saved` below
625            // (byte-identical, no clone). Only a resolved Claude/Gemini/Llama model
626            // carries the cache handle + output so the bg thread can re-tokenize the
627            // raw source and the sent output in the family the provider actually bills.
628            let ledger_cache = (crate::core::savings_ledger::ledger_family()
629                != crate::core::tokens::TokenizerFamily::O200kBase)
630                .then(|| cache_lock.clone());
631            let ledger_output = ledger_cache.as_ref().map(|_| output.clone());
632            std::thread::spawn(move || {
633                // A panic in telemetry must not poison locks or leave a zombie thread;
634                // it never affects the already-returned read response.
635                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
636                    crate::core::heatmap::record_file_access(&path_bg, original, saved);
637
638                    // #685: verified savings ledger, decoupled from the heatmap so it
639                    // can denominate in the active model's tokenizer family. O200kBase
640                    // reuses the o200k counts; other families re-tokenize raw (cache)
641                    // + output. A cache miss falls back to o200k (conservative).
642                    {
643                        use crate::core::savings_ledger as ledger;
644                        let (lbase, lsaved) = match (&ledger_cache, &ledger_output) {
645                            (Some(cl), Some(out)) => match cl.try_read().ok().and_then(|c| {
646                                c.get(&path_bg)
647                                    .and_then(crate::core::cache::CacheEntry::content)
648                            }) {
649                                Some(raw) => {
650                                    let lo = ledger::count_for_ledger(&raw);
651                                    (lo, lo.saturating_sub(ledger::count_for_ledger(out)))
652                                }
653                                None => (original, saved),
654                            },
655                            _ => (original, saved),
656                        };
657                        ledger::record_read_event(lbase, lsaved);
658                    }
659
660                    // Traversal/co-access edge: this read fired together with the
661                    // recent working set captured under the session lock (#289).
662                    if let Some(root) =
663                        crate::core::tool_lifecycle::usable_root(Some(project_root_bg.as_str()))
664                    {
665                        crate::core::cooccurrence::record_focus_access(
666                            root,
667                            &path_bg,
668                            &traversal_working_set,
669                        );
670                    }
671
672                    let sig =
673                        crate::core::mode_predictor::FileSignature::from_path(&path_bg, original);
674                    let density = if output_tokens > 0 {
675                        original as f64 / output_tokens as f64
676                    } else {
677                        1.0
678                    };
679                    let outcome = crate::core::mode_predictor::ModeOutcome {
680                        mode: resolved_mode_bg,
681                        tokens_in: original,
682                        tokens_out: output_tokens,
683                        density: density.min(1.0),
684                    };
685                    let mut predictor = crate::core::mode_predictor::ModePredictor::new();
686                    predictor.set_project_root(&project_root_bg);
687                    predictor.record(sig, outcome);
688                    predictor.save();
689
690                    let ext = std::path::Path::new(&path_bg)
691                        .extension()
692                        .and_then(|e| e.to_str())
693                        .unwrap_or("")
694                        .to_string();
695                    let thresholds =
696                        crate::core::adaptive_thresholds::thresholds_for_path(&path_bg);
697                    let feedback_outcome = crate::core::feedback::CompressionOutcome {
698                        session_id: format!("{}", std::process::id()),
699                        language: ext,
700                        entropy_threshold: thresholds.bpe_entropy,
701                        jaccard_threshold: thresholds.jaccard,
702                        total_turns: turns as u32,
703                        tokens_saved: saved as u64,
704                        tokens_original: original as u64,
705                        cache_hits: hits as u32,
706                        total_reads: turns as u32,
707                        // Real behavioral signal instead of a hardcoded success
708                        // (#593): a compressed read only counts as task-completing
709                        // when this extension is not in a high-bounce state —
710                        // compression that keeps forcing full re-reads is not
711                        // "completing" anything. Unknown (too few reads) stays
712                        // optimistic so the cold start is unchanged. 0.30 mirrors
713                        // bounce_tracker::BOUNCE_RATE_THRESHOLD.
714                        task_completed: crate::core::bounce_tracker::global()
715                            .lock()
716                            .ok()
717                            .and_then(|bt| bt.bounce_rate_for_extension(&path_bg))
718                            .is_none_or(|rate| rate < 0.30),
719                        timestamp: chrono::Local::now().to_rfc3339(),
720                    };
721                    let mut store = crate::core::feedback::FeedbackStore::load();
722                    store.project_root = Some(project_root_bg);
723                    store.record_outcome(feedback_outcome);
724                }));
725            });
726        }
727
728        if let Some(aid) = resolved_agent_id.as_deref() {
729            crate::core::agent_budget::record_consumption(aid, output_tokens);
730        }
731
732        // Cross-source hints: if the property graph has cross-source edges
733        // pointing to this file, append compact hints so the agent knows about
734        // related issues/PRs/schemas without a separate tool call (#682). Only
735        // touch the DB when it already exists — never create graph.db on a read.
736        let hints_suffix = {
737            let graph_db =
738                crate::core::property_graph::graph_dir(&ctx.project_root).join("graph.db");
739            let edges = if graph_db.exists() {
740                crate::core::property_graph::CodeGraph::open(&ctx.project_root)
741                    .map(|g| g.all_cross_source_edges())
742                    .unwrap_or_default()
743            } else {
744                Vec::new()
745            };
746            if edges.is_empty() {
747                String::new()
748            } else {
749                let hints = crate::core::cross_source_hints::hints_for_file(
750                    path,
751                    &edges,
752                    &ctx.project_root,
753                );
754                crate::core::cross_source_hints::format_hints(&hints)
755            }
756        };
757
758        let mut warnings = Vec::new();
759        if let Some(ref w) = budget_warning {
760            warnings.push(w.as_str());
761        }
762        if let Some(ref w) = degrade_warning {
763            warnings.push(w.as_str());
764        }
765        if let Some(ref w) = delta_explicit_note {
766            warnings.push(w.as_str());
767        }
768        let final_output = if !warnings.is_empty() {
769            format!("{output}{hints_suffix}\n\n{}", warnings.join("\n"))
770        } else if hints_suffix.is_empty() {
771            output
772        } else {
773            format!("{output}{hints_suffix}")
774        };
775
776        Ok(ToolOutput {
777            text: final_output,
778            original_tokens: original,
779            saved_tokens: saved,
780            mode: Some(resolved_mode),
781            path: Some(path.to_string()),
782            changed: false,
783            shell_outcome: None,
784        })
785    }
786}
787
788/// Resolve the `start_line`/`offset`/`limit` arguments into `(start, limit)`.
789///
790/// `offset` is an alias for `start_line` (1-based first line); `start_line`
791/// wins if a caller passes both. `limit` (when > 0) bounds the number of lines;
792/// a bare `limit` reads from line 1. Returns `None` when no windowing argument
793/// is present, so the caller leaves the mode untouched (GitHub #432).
794fn resolve_line_window(
795    start_line: Option<i64>,
796    offset: Option<i64>,
797    limit: Option<i64>,
798) -> Option<(i64, Option<i64>)> {
799    let start = start_line.or(offset).map(|v| v.max(1));
800    let limit = limit.filter(|&l| l > 0);
801    match (start, limit) {
802        (Some(s), l) => Some((s, l)),
803        (None, Some(_)) => Some((1, limit)),
804        (None, None) => None,
805    }
806}
807
808/// Build the `lines:N-M` mode string for a resolved window. An unbounded window
809/// (no `limit`) reads to EOF via the historical `999999` sentinel.
810fn lines_mode(start: i64, limit: Option<i64>) -> String {
811    match limit {
812        Some(l) => format!("lines:{start}-{}", start + l - 1),
813        None => format!("lines:{start}-999999"),
814    }
815}
816
817/// Apply a resolved line window to `mode`/`fresh`. An explicit non-lines mode
818/// (map/signatures/…) is never clobbered (#259), and `start_line=1` with no
819/// limit is a no-op so it cannot disturb an auto/explicit read (#253).
820fn apply_line_window(
821    mode: &mut String,
822    fresh: &mut bool,
823    explicit_mode: bool,
824    start_line: Option<i64>,
825    offset: Option<i64>,
826    limit: Option<i64>,
827) {
828    let Some((start, limit)) = resolve_line_window(start_line, offset, limit) else {
829        return;
830    };
831    if start <= 1 && limit.is_none() {
832        return;
833    }
834    *fresh = true;
835    if !explicit_mode || mode.starts_with("lines") {
836        *mode = lines_mode(start, limit);
837    }
838}
839
840/// #513: resolve the `raw=true` convenience flag into the effective explicit
841/// `mode` argument. Agents reach for `raw:true` to get exact bytes; it aliases
842/// to `mode="raw"` (verbatim, unframed) and wins over any caller-supplied
843/// `mode`. When `raw` is unset, the caller's `mode` (if any) passes through
844/// unchanged. The caller separately forces `fresh=true` for raw so a re-read
845/// never collapses to an `[unchanged]`/auto-delta stub.
846fn resolve_raw_alias(arg_raw: bool, mode_arg: Option<String>) -> Option<String> {
847    if arg_raw {
848        Some("raw".to_string())
849    } else {
850        mode_arg
851    }
852}
853
854fn apply_verdict(
855    mode: &str,
856    verdict: crate::core::degradation_policy::DegradationVerdictV1,
857) -> (String, bool) {
858    use crate::core::degradation_policy::DegradationVerdictV1;
859    match verdict {
860        DegradationVerdictV1::Ok => (mode.to_string(), false),
861        DegradationVerdictV1::Warn => match mode {
862            "full" => ("map".to_string(), true),
863            other => (other.to_string(), false),
864        },
865        DegradationVerdictV1::Throttle => match mode {
866            "full" | "map" => ("signatures".to_string(), true),
867            other => (other.to_string(), false),
868        },
869        DegradationVerdictV1::Block => {
870            if mode == "signatures" {
871                ("signatures".to_string(), false)
872            } else {
873                ("signatures".to_string(), true)
874            }
875        }
876    }
877}
878
879fn auto_degrade_read_mode(mode: &str) -> (String, Option<String>) {
880    if crate::core::config::Config::load().no_degrade_effective() {
881        return (mode.to_string(), None);
882    }
883    let profile = crate::core::profiles::active_profile();
884    if !profile.degradation.enforce_effective() {
885        return (mode.to_string(), None);
886    }
887    let policy = crate::core::degradation_policy::evaluate_v1_for_tool("ctx_read", None);
888    let (new_mode, degraded) = apply_verdict(mode, policy.decision.verdict);
889    let warning = if degraded {
890        Some(format!(
891            "⚠ Context pressure: mode={mode} was downgraded to mode={new_mode} \
892             (verdict: {:?}). Use start_line=1 to bypass, or run ctx_compress to free budget.",
893            policy.decision.verdict
894        ))
895    } else {
896        None
897    };
898    (new_mode, warning)
899}
900
901fn extract_file_summary(output: &str, path: &str) -> String {
902    let hint = crate::core::auto_findings::extract_content_hint(output);
903    if !hint.is_empty() {
904        return hint;
905    }
906    let ext = std::path::Path::new(path)
907        .extension()
908        .and_then(|e| e.to_str())
909        .unwrap_or("");
910    let line_count = output.lines().count();
911    if line_count > 5 {
912        format!("{ext} file, {line_count} lines")
913    } else {
914        String::new()
915    }
916}
917
918#[cfg(test)]
919mod tests {
920    use super::*;
921    use std::sync::atomic::{AtomicUsize, Ordering};
922
923    #[test]
924    fn raw_alias_forces_raw_mode_over_explicit_mode() {
925        // #513: raw=true is the verbatim escape hatch and must win over any
926        // mode arg an agent also happened to pass.
927        assert_eq!(
928            resolve_raw_alias(true, Some("signatures".to_string())),
929            Some("raw".to_string())
930        );
931        assert_eq!(resolve_raw_alias(true, None), Some("raw".to_string()));
932    }
933
934    #[test]
935    fn raw_alias_absent_passes_mode_through() {
936        // Without raw=true the caller's mode is untouched (including None, which
937        // lets the auto/policy/profile resolution downstream pick the mode).
938        assert_eq!(
939            resolve_raw_alias(false, Some("full".to_string())),
940            Some("full".to_string())
941        );
942        assert_eq!(resolve_raw_alias(false, None), None);
943    }
944
945    #[test]
946    fn per_file_lock_same_path_returns_same_mutex() {
947        let lock_a1 = per_file_lock("/tmp/test_same_path.txt");
948        let lock_a2 = per_file_lock("/tmp/test_same_path.txt");
949        assert!(Arc::ptr_eq(&lock_a1, &lock_a2));
950    }
951
952    #[test]
953    fn per_file_lock_different_paths_return_different_mutexes() {
954        let lock_a = per_file_lock("/tmp/test_path_a.txt");
955        let lock_b = per_file_lock("/tmp/test_path_b.txt");
956        assert!(!Arc::ptr_eq(&lock_a, &lock_b));
957    }
958
959    #[test]
960    fn per_file_lock_serializes_concurrent_access() {
961        let counter = Arc::new(AtomicUsize::new(0));
962        let max_concurrent = Arc::new(AtomicUsize::new(0));
963        let path = "/tmp/test_concurrent_serialization.txt";
964        let mut handles = Vec::new();
965
966        for _ in 0..5 {
967            let counter = counter.clone();
968            let max_concurrent = max_concurrent.clone();
969            let path = path.to_string();
970            handles.push(std::thread::spawn(move || {
971                let lock = per_file_lock(&path);
972                let _guard = lock.lock().unwrap();
973                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
974                max_concurrent.fetch_max(active, Ordering::SeqCst);
975                std::thread::sleep(std::time::Duration::from_millis(10));
976                counter.fetch_sub(1, Ordering::SeqCst);
977            }));
978        }
979
980        for h in handles {
981            h.join().unwrap();
982        }
983
984        assert_eq!(max_concurrent.load(Ordering::SeqCst), 1);
985    }
986
987    #[test]
988    fn per_file_lock_allows_parallel_different_paths() {
989        let counter = Arc::new(AtomicUsize::new(0));
990        let max_concurrent = Arc::new(AtomicUsize::new(0));
991        let mut handles = Vec::new();
992
993        for i in 0..4 {
994            let counter = counter.clone();
995            let max_concurrent = max_concurrent.clone();
996            let path = format!("/tmp/test_parallel_{i}.txt");
997            handles.push(std::thread::spawn(move || {
998                let lock = per_file_lock(&path);
999                let _guard = lock.lock().unwrap();
1000                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
1001                max_concurrent.fetch_max(active, Ordering::SeqCst);
1002                std::thread::sleep(std::time::Duration::from_millis(50));
1003                counter.fetch_sub(1, Ordering::SeqCst);
1004            }));
1005        }
1006
1007        for h in handles {
1008            h.join().unwrap();
1009        }
1010
1011        assert!(max_concurrent.load(Ordering::SeqCst) > 1);
1012    }
1013
1014    /// Regression test for Issue #229: a zombie thread holding the cache write-lock
1015    /// must not block subsequent reads indefinitely. The try_write() loop inside
1016    /// the spawned thread should respect its 25s deadline and the cancellation flag.
1017    #[test]
1018    fn zombie_thread_does_not_block_subsequent_cache_access() {
1019        let cache: Arc<tokio::sync::RwLock<u32>> = Arc::new(tokio::sync::RwLock::new(0));
1020
1021        // Simulate a zombie: hold the write-lock on a background thread for 2s.
1022        let zombie_lock = cache.clone();
1023        let _zombie = std::thread::spawn(move || {
1024            let _guard = zombie_lock.blocking_write();
1025            std::thread::sleep(std::time::Duration::from_secs(2));
1026        });
1027        std::thread::sleep(std::time::Duration::from_millis(50));
1028
1029        // A try_read() must fail immediately (zombie holds write-lock).
1030        assert!(cache.try_read().is_err());
1031
1032        // A try_write() loop with cancellation must exit promptly.
1033        let cancel = Arc::new(AtomicBool::new(false));
1034        let cancel2 = cancel.clone();
1035        let lock2 = cache.clone();
1036        let waiter = std::thread::spawn(move || {
1037            let start = std::time::Instant::now();
1038            loop {
1039                if cancel2.load(Ordering::Relaxed) {
1040                    return (false, start.elapsed());
1041                }
1042                if let Ok(_guard) = lock2.try_write() {
1043                    return (true, start.elapsed());
1044                }
1045                std::thread::sleep(std::time::Duration::from_millis(50));
1046            }
1047        });
1048
1049        // Set cancellation after 200ms — the loop should exit quickly.
1050        std::thread::sleep(std::time::Duration::from_millis(200));
1051        cancel.store(true, Ordering::Relaxed);
1052
1053        let (acquired, elapsed) = waiter.join().unwrap();
1054        assert!(
1055            !acquired,
1056            "should not have acquired lock while zombie holds it"
1057        );
1058        assert!(
1059            elapsed < std::time::Duration::from_secs(1),
1060            "cancellation should have stopped the loop promptly"
1061        );
1062    }
1063
1064    // -- Regression: GitHub Issue #253 + #259 --
1065    // Delegates to the real runtime helper so this test can never drift from
1066    // production behaviour.
1067    fn apply_start_line(
1068        mode: &mut String,
1069        fresh: &mut bool,
1070        explicit_mode: bool,
1071        start_line: Option<i64>,
1072    ) {
1073        super::apply_line_window(mode, fresh, explicit_mode, start_line, None, None);
1074    }
1075
1076    #[test]
1077    fn start_line_1_does_not_override_mode() {
1078        let mut mode = "auto".to_string();
1079        let mut fresh = false;
1080        apply_start_line(&mut mode, &mut fresh, false, Some(1));
1081        assert_eq!(mode, "auto", "start_line=1 should not change mode");
1082        assert!(!fresh, "start_line=1 should not force fresh=true");
1083    }
1084
1085    #[test]
1086    fn start_line_gt1_overrides_implicit_mode() {
1087        let mut mode = "auto".to_string();
1088        let mut fresh = false;
1089        apply_start_line(&mut mode, &mut fresh, false, Some(50));
1090        assert_eq!(mode, "lines:50-999999");
1091        assert!(fresh);
1092    }
1093
1094    #[test]
1095    fn start_line_gt1_does_not_override_explicit_map() {
1096        // GitHub #259: mode=map + start_line=50 → mode stays map
1097        let mut mode = "map".to_string();
1098        let mut fresh = false;
1099        apply_start_line(&mut mode, &mut fresh, true, Some(50));
1100        assert_eq!(
1101            mode, "map",
1102            "explicit mode=map must not be clobbered by start_line"
1103        );
1104        assert!(fresh, "start_line>1 should still force fresh");
1105    }
1106
1107    #[test]
1108    fn start_line_gt1_does_not_override_explicit_signatures() {
1109        let mut mode = "signatures".to_string();
1110        let mut fresh = false;
1111        apply_start_line(&mut mode, &mut fresh, true, Some(100));
1112        assert_eq!(mode, "signatures");
1113        assert!(fresh);
1114    }
1115
1116    #[test]
1117    fn start_line_gt1_honors_explicit_lines_mode() {
1118        let mut mode = "lines:1-50".to_string();
1119        let mut fresh = false;
1120        apply_start_line(&mut mode, &mut fresh, true, Some(30));
1121        assert_eq!(
1122            mode, "lines:30-999999",
1123            "explicit lines mode should accept start_line override"
1124        );
1125        assert!(fresh);
1126    }
1127
1128    #[test]
1129    fn start_line_none_does_nothing() {
1130        let mut mode = "map".to_string();
1131        let mut fresh = false;
1132        apply_start_line(&mut mode, &mut fresh, true, None);
1133        assert_eq!(mode, "map");
1134        assert!(!fresh);
1135    }
1136
1137    #[test]
1138    fn start_line_1_with_explicit_mode_preserves_it() {
1139        // OpenCode sends start_line=1 + mode=map — both should be preserved
1140        let mut mode = "map".to_string();
1141        let mut fresh = false;
1142        apply_start_line(&mut mode, &mut fresh, true, Some(1));
1143        assert_eq!(mode, "map");
1144        assert!(!fresh);
1145    }
1146
1147    // -- Regression: GitHub Issue #432 — `offset`/`limit` aliases --
1148
1149    #[test]
1150    fn offset_is_alias_for_start_line() {
1151        let mut mode = "auto".to_string();
1152        let mut fresh = false;
1153        super::apply_line_window(&mut mode, &mut fresh, false, None, Some(40), None);
1154        assert_eq!(mode, "lines:40-999999");
1155        assert!(fresh);
1156    }
1157
1158    #[test]
1159    fn offset_and_limit_make_bounded_window() {
1160        let mut mode = "auto".to_string();
1161        let mut fresh = false;
1162        super::apply_line_window(&mut mode, &mut fresh, false, None, Some(40), Some(20));
1163        assert_eq!(mode, "lines:40-59", "20 inclusive lines starting at 40");
1164        assert!(fresh);
1165    }
1166
1167    #[test]
1168    fn limit_alone_reads_from_first_line() {
1169        let mut mode = "auto".to_string();
1170        let mut fresh = false;
1171        super::apply_line_window(&mut mode, &mut fresh, false, None, None, Some(25));
1172        assert_eq!(mode, "lines:1-25");
1173        assert!(fresh);
1174    }
1175
1176    #[test]
1177    fn start_line_wins_over_offset_when_both_present() {
1178        assert_eq!(
1179            super::resolve_line_window(Some(10), Some(99), None),
1180            Some((10, None))
1181        );
1182    }
1183
1184    #[test]
1185    fn resolve_clamps_start_and_drops_nonpositive_limit() {
1186        // Negative/zero start clamps to 1; non-positive limit is ignored.
1187        assert_eq!(
1188            super::resolve_line_window(Some(-5), None, Some(0)),
1189            Some((1, None))
1190        );
1191        // A bare non-positive limit yields no window at all.
1192        assert_eq!(super::resolve_line_window(None, None, Some(-3)), None);
1193        assert_eq!(super::resolve_line_window(None, None, None), None);
1194    }
1195
1196    #[test]
1197    fn lines_mode_bounds_are_inclusive() {
1198        assert_eq!(super::lines_mode(40, Some(20)), "lines:40-59");
1199        assert_eq!(super::lines_mode(5, None), "lines:5-999999");
1200    }
1201
1202    #[test]
1203    fn explicit_map_not_clobbered_by_offset_limit() {
1204        // #259 must also hold for the new aliases.
1205        let mut mode = "map".to_string();
1206        let mut fresh = false;
1207        super::apply_line_window(&mut mode, &mut fresh, true, None, Some(40), Some(20));
1208        assert_eq!(mode, "map", "explicit mode wins over offset/limit");
1209        assert!(fresh);
1210    }
1211
1212    /// Schema/handler consistency (GitHub #432): the handler reads
1213    /// start_line/offset/limit, so the advertised schema must document them —
1214    /// otherwise agents (and the generated docs/manifest) can't discover the
1215    /// aliases and the divergence that caused this bug returns.
1216    #[test]
1217    fn schema_advertises_line_window_aliases() {
1218        let tool = CtxReadTool.tool_def();
1219        let props = tool
1220            .input_schema
1221            .get("properties")
1222            .and_then(|p| p.as_object())
1223            .expect("ctx_read schema has a properties object");
1224        for key in ["path", "mode", "start_line", "offset", "limit", "fresh"] {
1225            assert!(props.contains_key(key), "ctx_read schema missing '{key}'");
1226        }
1227    }
1228
1229    // -- Regression: GitHub Issue #262 --
1230    // auto_degrade_read_mode must produce a warning when mode is downgraded.
1231
1232    use crate::core::degradation_policy::DegradationVerdictV1;
1233
1234    #[test]
1235    fn verdict_ok_does_not_degrade() {
1236        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Ok);
1237        assert_eq!(mode, "full");
1238        assert!(!degraded);
1239    }
1240
1241    #[test]
1242    fn verdict_warn_degrades_full_to_map() {
1243        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Warn);
1244        assert_eq!(mode, "map");
1245        assert!(degraded, "full→map must be flagged as degraded");
1246    }
1247
1248    #[test]
1249    fn verdict_warn_keeps_map() {
1250        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Warn);
1251        assert_eq!(mode, "map");
1252        assert!(!degraded, "map is not degraded under Warn");
1253    }
1254
1255    #[test]
1256    fn verdict_warn_keeps_signatures() {
1257        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Warn);
1258        assert_eq!(mode, "signatures");
1259        assert!(!degraded);
1260    }
1261
1262    #[test]
1263    fn verdict_throttle_degrades_full_to_signatures() {
1264        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Throttle);
1265        assert_eq!(mode, "signatures");
1266        assert!(degraded);
1267    }
1268
1269    #[test]
1270    fn verdict_throttle_degrades_map_to_signatures() {
1271        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Throttle);
1272        assert_eq!(mode, "signatures");
1273        assert!(degraded);
1274    }
1275
1276    #[test]
1277    fn verdict_throttle_keeps_lines() {
1278        let (mode, degraded) = super::apply_verdict("lines:1-50", DegradationVerdictV1::Throttle);
1279        assert_eq!(mode, "lines:1-50");
1280        assert!(!degraded, "lines mode bypasses degradation");
1281    }
1282
1283    #[test]
1284    fn verdict_block_degrades_full_to_signatures() {
1285        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Block);
1286        assert_eq!(mode, "signatures");
1287        assert!(degraded);
1288    }
1289
1290    #[test]
1291    fn verdict_block_does_not_degrade_signatures() {
1292        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Block);
1293        assert_eq!(mode, "signatures");
1294        assert!(!degraded, "already at signatures — no degradation needed");
1295    }
1296
1297    #[test]
1298    fn degrade_warning_message_contains_mode_info() {
1299        let (new_mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Warn);
1300        assert!(degraded);
1301        let warning = format!(
1302            "⚠ Context pressure: mode=full was downgraded to mode={new_mode} (verdict: {:?}).",
1303            DegradationVerdictV1::Warn
1304        );
1305        assert!(warning.contains("mode=full"));
1306        assert!(warning.contains("mode=map"));
1307        assert!(warning.contains("Warn"));
1308    }
1309
1310    // --- auto_degrade_read_mode: no_degrade integration ---
1311    // With default config (no LCTX_NO_DEGRADE), the profile's degradation.enforce
1312    // is also off by default, so auto_degrade_read_mode returns mode unchanged.
1313
1314    #[test]
1315    fn auto_degrade_preserves_full_when_default_config() {
1316        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1317            return;
1318        }
1319        let (mode, warning) = super::auto_degrade_read_mode("full");
1320        assert_eq!(mode, "full");
1321        assert!(warning.is_none());
1322    }
1323
1324    #[test]
1325    fn auto_degrade_preserves_map_when_default_config() {
1326        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1327            return;
1328        }
1329        let (mode, warning) = super::auto_degrade_read_mode("map");
1330        assert_eq!(mode, "map");
1331        assert!(warning.is_none());
1332    }
1333
1334    #[test]
1335    fn auto_degrade_preserves_signatures_when_default_config() {
1336        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1337            return;
1338        }
1339        let (mode, warning) = super::auto_degrade_read_mode("signatures");
1340        assert_eq!(mode, "signatures");
1341        assert!(warning.is_none());
1342    }
1343
1344    #[test]
1345    fn auto_degrade_preserves_diff_always() {
1346        let (mode, warning) = super::auto_degrade_read_mode("diff");
1347        assert_eq!(mode, "diff");
1348        assert!(warning.is_none());
1349    }
1350
1351    #[test]
1352    fn auto_degrade_preserves_lines_mode_always() {
1353        let (mode, warning) = super::auto_degrade_read_mode("lines:10-50");
1354        assert_eq!(mode, "lines:10-50");
1355        assert!(warning.is_none());
1356    }
1357
1358    #[test]
1359    fn auto_degrade_preserves_aggressive_when_default_config() {
1360        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1361            return;
1362        }
1363        let (mode, warning) = super::auto_degrade_read_mode("aggressive");
1364        assert_eq!(mode, "aggressive");
1365        assert!(warning.is_none());
1366    }
1367
1368    #[test]
1369    fn auto_degrade_preserves_entropy_when_default_config() {
1370        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1371            return;
1372        }
1373        let (mode, warning) = super::auto_degrade_read_mode("entropy");
1374        assert_eq!(mode, "entropy");
1375        assert!(warning.is_none());
1376    }
1377
1378    #[test]
1379    fn auto_degrade_preserves_auto_when_default_config() {
1380        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1381            return;
1382        }
1383        let (mode, warning) = super::auto_degrade_read_mode("auto");
1384        assert_eq!(mode, "auto");
1385        assert!(warning.is_none());
1386    }
1387
1388    // --- apply_verdict: exhaustive mode × verdict matrix ---
1389
1390    #[test]
1391    fn verdict_warn_does_not_degrade_diff() {
1392        let (mode, degraded) = super::apply_verdict("diff", DegradationVerdictV1::Warn);
1393        assert_eq!(mode, "diff");
1394        assert!(!degraded);
1395    }
1396
1397    #[test]
1398    fn verdict_throttle_does_not_degrade_signatures() {
1399        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Throttle);
1400        assert_eq!(mode, "signatures");
1401        assert!(!degraded);
1402    }
1403
1404    #[test]
1405    fn verdict_ok_preserves_map() {
1406        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Ok);
1407        assert_eq!(mode, "map");
1408        assert!(!degraded);
1409    }
1410
1411    #[test]
1412    fn verdict_ok_preserves_signatures() {
1413        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Ok);
1414        assert_eq!(mode, "signatures");
1415        assert!(!degraded);
1416    }
1417
1418    #[test]
1419    fn verdict_ok_preserves_lines() {
1420        let (mode, degraded) = super::apply_verdict("lines:1-100", DegradationVerdictV1::Ok);
1421        assert_eq!(mode, "lines:1-100");
1422        assert!(!degraded);
1423    }
1424
1425    #[test]
1426    fn verdict_block_degrades_map_to_signatures() {
1427        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Block);
1428        assert_eq!(mode, "signatures");
1429        assert!(degraded);
1430    }
1431}
1432
1433// #660 LOC gate: repo-param tests split out to keep this file under the line
1434// cap — see `ctx_read_repo_param_tests.rs`.
1435#[cfg(test)]
1436#[path = "ctx_read_repo_param_tests.rs"]
1437mod repo_param_tests;