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