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