Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

1use std::collections::HashMap;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Mutex};
4
5use rmcp::model::Tool;
6use rmcp::ErrorData;
7use serde_json::{json, Map, Value};
8
9use crate::server::tool_trait::{
10    get_bool, get_int, get_str, require_resolved_path, McpTool, ToolContext, ToolOutput,
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.
21fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
22    static FILE_LOCKS: std::sync::OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> =
23        std::sync::OnceLock::new();
24    let map = FILE_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
25    let mut map = map.lock().unwrap();
26
27    const MAX_ENTRIES: usize = 500;
28    if map.len() > MAX_ENTRIES {
29        map.retain(|_, v| Arc::strong_count(v) > 1);
30    }
31
32    map.entry(path.to_string())
33        .or_insert_with(|| Arc::new(Mutex::new(())))
34        .clone()
35}
36
37pub struct CtxReadTool;
38
39impl McpTool for CtxReadTool {
40    fn name(&self) -> &'static str {
41        "ctx_read"
42    }
43
44    fn tool_def(&self) -> Tool {
45        tool_def(
46            "ctx_read",
47            "Read file (cached, compressed). Cached re-reads can be ~13 tok when unchanged. Auto-selects optimal mode. \
48Modes: full|map|signatures|diff|aggressive|entropy|task|reference|lines:N-M. fresh=true forces a disk re-read.",
49            json!({
50                "type": "object",
51                "properties": {
52                    "path": { "type": "string", "description": "Absolute file path to read" },
53                    "mode": {
54                        "type": "string",
55                        "description": "Compression mode (default: full). Use 'map' for context-only files. For line ranges: 'lines:N-M' (e.g. 'lines:400-500')."
56                    },
57                    "start_line": {
58                        "type": "integer",
59                        "description": "Start reading from this line (only used when no explicit mode is set, or with mode=lines). Does NOT override explicit modes like map/signatures."
60                    },
61                    "fresh": {
62                        "type": "boolean",
63                        "description": "Bypass cache and force a full re-read. Use when running as a subagent that may not have the parent's context."
64                    }
65                },
66                "required": ["path"]
67            }),
68        )
69    }
70
71    fn handle(
72        &self,
73        args: &Map<String, Value>,
74        ctx: &ToolContext,
75    ) -> Result<ToolOutput, ErrorData> {
76        let path = require_resolved_path(ctx, args, "path")?;
77
78        self.handle_inner(args, ctx, &path)
79    }
80}
81
82impl CtxReadTool {
83    #[allow(clippy::unused_self)]
84    fn handle_inner(
85        &self,
86        args: &Map<String, Value>,
87        ctx: &ToolContext,
88        path: &str,
89    ) -> Result<ToolOutput, ErrorData> {
90        let session_lock = ctx
91            .session
92            .as_ref()
93            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
94        let cache_lock = ctx
95            .cache
96            .as_ref()
97            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
98
99        let current_task = {
100            let mut attempt = 0u32;
101            loop {
102                if let Ok(session) = tokio::task::block_in_place(|| {
103                    let rt = tokio::runtime::Handle::current();
104                    rt.block_on(tokio::time::timeout(
105                        std::time::Duration::from_secs(5),
106                        session_lock.read(),
107                    ))
108                }) {
109                    break session.task.as_ref().map(|t| t.description.clone());
110                }
111                attempt += 1;
112                if attempt >= 3 {
113                    tracing::warn!(
114                        "session read-lock timeout after {attempt} attempts in ctx_read for {path}"
115                    );
116                    return Err(ErrorData::internal_error(
117                        "session lock timeout — another tool may be holding it. Retry in a moment.",
118                        None,
119                    ));
120                }
121                tracing::debug!(
122                    "session read-lock attempt {attempt}/3 timed out for {path}, retrying"
123                );
124                std::thread::sleep(std::time::Duration::from_millis(100 * u64::from(attempt)));
125            }
126        };
127        let task_ref = current_task.as_deref();
128
129        let profile = crate::core::profiles::active_profile();
130        let explicit_mode_arg = get_str(args, "mode");
131        let explicit_mode = explicit_mode_arg.is_some();
132        let mut mode = if let Some(m) = explicit_mode_arg {
133            m
134        } else if profile.read.default_mode_effective() == "auto" {
135            if let Ok(cache) = cache_lock.try_read() {
136                crate::tools::ctx_smart_read::select_mode_with_task(&cache, path, task_ref)
137            } else {
138                tracing::debug!(
139                    "cache lock contested during auto-mode selection for {path}; \
140                     falling back to full"
141                );
142                "full".to_string()
143            }
144        } else {
145            profile.read.default_mode_effective().to_string()
146        };
147        let mut fresh = get_bool(args, "fresh").unwrap_or(false);
148        let cache_policy = crate::server::compaction_sync::effective_cache_policy();
149        if cache_policy == "off" {
150            fresh = true;
151        }
152        let start_line = get_int(args, "start_line");
153        if let Some(sl) = start_line {
154            let sl = sl.max(1_i64);
155            if sl > 1 {
156                fresh = true;
157                // Only override mode when no explicit mode was requested,
158                // or when the explicit mode is already a lines range.
159                // If the caller explicitly set mode=map/signatures/etc.,
160                // start_line must not clobber it (GitHub #259).
161                if !explicit_mode || mode.starts_with("lines") {
162                    mode = format!("lines:{sl}-999999");
163                }
164            }
165        }
166
167        let pressure_action = ctx.pressure_snapshot.as_ref().map(|p| &p.recommendation);
168        let resolved_agent_id = ctx.agent_id.as_ref().and_then(|a| match a.try_read() {
169            Ok(guard) => guard.clone(),
170            Err(_) => None,
171        });
172        let gate_result = crate::server::context_gate::pre_dispatch_read_for_agent(
173            path,
174            &mode,
175            task_ref,
176            Some(&ctx.project_root),
177            pressure_action,
178            resolved_agent_id.as_deref(),
179        );
180        if gate_result.budget_blocked {
181            let msg = gate_result
182                .budget_warning
183                .unwrap_or_else(|| "Agent token budget exceeded".to_string());
184            return Err(ErrorData::invalid_params(msg, None));
185        }
186        let budget_warning = gate_result.budget_warning.clone();
187        if let Some(overridden) = gate_result.overridden_mode {
188            mode = overridden;
189        }
190
191        let (mode, degrade_warning) = if crate::tools::ctx_read::is_instruction_file(path) {
192            ("full".to_string(), None)
193        } else {
194            auto_degrade_read_mode(&mode)
195        };
196
197        if mode.starts_with("lines:") {
198            fresh = true;
199        }
200
201        if crate::core::binary_detect::is_binary_file(path) {
202            let msg = crate::core::binary_detect::binary_file_message(path);
203            return Err(ErrorData::invalid_params(msg, None));
204        }
205        {
206            let cap = crate::core::limits::max_read_bytes() as u64;
207            if let Ok(meta) = std::fs::metadata(path) {
208                if meta.len() > cap {
209                    let msg = format!(
210                        "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
211                         Use mode=\"lines:1-100\" for partial reads or increase the limit.",
212                        meta.len(),
213                        cap
214                    );
215                    return Err(ErrorData::invalid_params(msg, None));
216                }
217            }
218        }
219
220        // Compaction-aware: if host compacted since last check, reset delivery flags
221        // so post-compaction reads deliver full content instead of stubs.
222        if !fresh {
223            if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
224                if let Ok(mut cache) = cache_lock.try_write() {
225                    crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
226                }
227            }
228        }
229
230        // Fast path: if both per-file lock and cache write-lock are immediately
231        // available, execute inline without spawning a thread. This avoids thread +
232        // channel overhead for the ~90% of calls that are cache hits.
233        let read_timeout = std::time::Duration::from_secs(30);
234        let cancelled = Arc::new(AtomicBool::new(false));
235        let (output, resolved_mode, original, is_cache_hit, file_ref, cache_stats) = {
236            let crp_mode = ctx.crp_mode;
237            let task_ref = current_task.as_deref();
238
239            let fast_result = 'fast: {
240                let file_lock = per_file_lock(path);
241                let Some(_file_guard) = file_lock.try_lock().ok() else {
242                    break 'fast None;
243                };
244                let Some(mut cache) = cache_lock.try_write().ok() else {
245                    break 'fast None;
246                };
247                let read_output = if fresh {
248                    crate::tools::ctx_read::handle_fresh_with_task_resolved(
249                        &mut cache, path, &mode, crp_mode, task_ref,
250                    )
251                } else {
252                    crate::tools::ctx_read::handle_with_task_resolved(
253                        &mut cache, path, &mode, crp_mode, task_ref,
254                    )
255                };
256                let content = read_output.content;
257                let rmode = read_output.resolved_mode;
258                let orig = cache.get(path).map_or(0, |e| e.original_tokens);
259                let hit = content.contains(" cached ")
260                    || content.contains("[unchanged")
261                    || content.contains("[delta:");
262                let fref = cache.file_ref_map().get(path).cloned();
263                let stats = cache.get_stats();
264                let stats_snapshot = (stats.total_reads, stats.cache_hits);
265                Some((content, rmode, orig, hit, fref, stats_snapshot))
266            };
267
268            if let Some(result) = fast_result {
269                result
270            } else {
271                // Slow path: spawn thread with bounded timeout for contended locks.
272                let cache_lock = cache_lock.clone();
273                let mode = mode.clone();
274                let task_owned = current_task.clone();
275                let path_owned = path.to_string();
276                let cancel_flag = cancelled.clone();
277                let (tx, rx) = std::sync::mpsc::sync_channel(1);
278                std::thread::spawn(move || {
279                    let file_lock = per_file_lock(&path_owned);
280
281                    // Bounded per-file lock: if a zombie thread still holds it, don't
282                    // wait forever. 25s keeps us inside the 30s recv_timeout.
283                    let _file_guard = {
284                        let deadline =
285                            std::time::Instant::now() + std::time::Duration::from_secs(25);
286                        loop {
287                            if cancel_flag.load(Ordering::Relaxed) {
288                                return;
289                            }
290                            if let Ok(guard) = file_lock.try_lock() {
291                                break guard;
292                            }
293                            if std::time::Instant::now() >= deadline {
294                                tracing::error!(
295                                    "ctx_read: per-file lock timeout after 25s for {path_owned}"
296                                );
297                                let _ = tx.send((
298                                    format!("per-file lock contention for {path_owned} — retry in a moment"),
299                                    "error".to_string(), 0, false, None, (0, 0),
300                                ));
301                                return;
302                            }
303                            std::thread::sleep(std::time::Duration::from_millis(50));
304                        }
305                    };
306
307                    if cancel_flag.load(Ordering::Relaxed) {
308                        return;
309                    }
310
311                    // Bounded cache write-lock: avoids indefinite block when a zombie
312                    // thread from a previous timed-out call still holds the lock.
313                    let mut cache = {
314                        let deadline =
315                            std::time::Instant::now() + std::time::Duration::from_secs(25);
316                        loop {
317                            if cancel_flag.load(Ordering::Relaxed) {
318                                return;
319                            }
320                            if let Ok(guard) = cache_lock.try_write() {
321                                break guard;
322                            }
323                            if std::time::Instant::now() >= deadline {
324                                tracing::error!(
325                                    "ctx_read: cache write-lock timeout after 25s for {path_owned}"
326                                );
327                                let _ = tx.send((
328                                    format!("cache lock contention for {path_owned} — retry in a moment"),
329                                    "error".to_string(), 0, false, None, (0, 0),
330                                ));
331                                return;
332                            }
333                            std::thread::sleep(std::time::Duration::from_millis(50));
334                        }
335                    };
336
337                    let task_ref = task_owned.as_deref();
338                    let read_output = if fresh {
339                        crate::tools::ctx_read::handle_fresh_with_task_resolved(
340                            &mut cache,
341                            &path_owned,
342                            &mode,
343                            crp_mode,
344                            task_ref,
345                        )
346                    } else {
347                        crate::tools::ctx_read::handle_with_task_resolved(
348                            &mut cache,
349                            &path_owned,
350                            &mode,
351                            crp_mode,
352                            task_ref,
353                        )
354                    };
355                    let content = read_output.content;
356                    let rmode = read_output.resolved_mode;
357                    let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
358                    let hit = content.contains(" cached ");
359                    let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
360                    let stats = cache.get_stats();
361                    let stats_snapshot = (stats.total_reads, stats.cache_hits);
362                    let _ = tx.send((content, rmode, orig, hit, fref, stats_snapshot));
363                });
364                if let Ok(result) = rx.recv_timeout(read_timeout) {
365                    result
366                } else {
367                    cancelled.store(true, Ordering::Relaxed);
368                    tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
369                    let msg = format!(
370                        "ERROR: ctx_read timed out after {}s reading {path}. \
371                     The file may be very large or a blocking I/O issue occurred. \
372                     Try mode=\"lines:1-100\" for a partial read.",
373                        read_timeout.as_secs()
374                    );
375                    return Err(ErrorData::internal_error(msg, None));
376                }
377            } // end else (slow path)
378        };
379
380        // Convert error results to proper MCP ErrorData instead of success body
381        if resolved_mode == "error" {
382            return Err(ErrorData::invalid_params(output, None));
383        }
384
385        let output_tokens = crate::core::tokens::count_tokens(&output);
386        let saved = original.saturating_sub(output_tokens);
387
388        // Session updates (bounded lock — 10s timeout, read already succeeded)
389        let mut ensured_root: Option<String> = None;
390        let project_root_snapshot;
391        {
392            let session_guard = tokio::task::block_in_place(|| {
393                let rt = tokio::runtime::Handle::current();
394                rt.block_on(tokio::time::timeout(
395                    std::time::Duration::from_secs(10),
396                    session_lock.write(),
397                ))
398            });
399            if let Ok(mut session) = session_guard {
400                session.touch_file(path, file_ref.as_deref(), &resolved_mode, original);
401                if is_cache_hit {
402                    session.record_cache_hit();
403                }
404                if session.active_structured_intent.is_none() && session.files_touched.len() >= 2 {
405                    let touched: Vec<String> = session
406                        .files_touched
407                        .iter()
408                        .map(|f| f.path.clone())
409                        .collect();
410                    let inferred =
411                        crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
412                    if inferred.confidence >= 0.4 {
413                        session.active_structured_intent = Some(inferred);
414                    }
415                }
416                let root_missing = session
417                    .project_root
418                    .as_deref()
419                    .is_none_or(|r| r.trim().is_empty());
420                if root_missing {
421                    if let Some(root) = crate::core::protocol::detect_project_root(path) {
422                        session.project_root = Some(root.clone());
423                        ensured_root = Some(root);
424                    }
425                }
426                project_root_snapshot = session
427                    .project_root
428                    .clone()
429                    .unwrap_or_else(|| ".".to_string());
430            } else {
431                tracing::warn!(
432                    "session write-lock timeout (5s) in ctx_read post-update for {path}"
433                );
434                project_root_snapshot = ctx.project_root.clone();
435            }
436        }
437
438        if let Some(root) = ensured_root.as_deref() {
439            crate::core::index_orchestrator::ensure_all_background(root);
440        }
441
442        crate::core::heatmap::record_file_access(path, original, saved);
443
444        // Mode predictor + feedback — no locks needed, uses snapshots from above
445        {
446            let sig = crate::core::mode_predictor::FileSignature::from_path(path, original);
447            let density = if output_tokens > 0 {
448                original as f64 / output_tokens as f64
449            } else {
450                1.0
451            };
452            let outcome = crate::core::mode_predictor::ModeOutcome {
453                mode: resolved_mode.clone(),
454                tokens_in: original,
455                tokens_out: output_tokens,
456                density: density.min(1.0),
457            };
458            let mut predictor = crate::core::mode_predictor::ModePredictor::new();
459            predictor.set_project_root(&project_root_snapshot);
460            predictor.record(sig, outcome);
461            predictor.save();
462
463            let ext = std::path::Path::new(path)
464                .extension()
465                .and_then(|e| e.to_str())
466                .unwrap_or("")
467                .to_string();
468            let thresholds = crate::core::adaptive_thresholds::thresholds_for_path(path);
469            let feedback_outcome = crate::core::feedback::CompressionOutcome {
470                session_id: format!("{}", std::process::id()),
471                language: ext,
472                entropy_threshold: thresholds.bpe_entropy,
473                jaccard_threshold: thresholds.jaccard,
474                total_turns: cache_stats.0 as u32,
475                tokens_saved: saved as u64,
476                tokens_original: original as u64,
477                cache_hits: cache_stats.1 as u32,
478                total_reads: cache_stats.0 as u32,
479                task_completed: true,
480                timestamp: chrono::Local::now().to_rfc3339(),
481            };
482            let mut store = crate::core::feedback::FeedbackStore::load();
483            store.project_root = Some(project_root_snapshot.clone());
484            store.record_outcome(feedback_outcome);
485        }
486
487        if let Some(aid) = resolved_agent_id.as_deref() {
488            crate::core::agent_budget::record_consumption(aid, output_tokens);
489        }
490
491        // Cross-source hints: if a graph index exists and has cross-source edges
492        // pointing to this file, append compact hints so the agent knows about
493        // related issues/PRs/schemas without a separate tool call.
494        let hints_suffix = {
495            if let Some(index) = crate::core::graph_index::ProjectIndex::load(&ctx.project_root) {
496                let hints = crate::core::cross_source_hints::hints_for_file(path, &index.edges);
497                if hints.is_empty() {
498                    String::new()
499                } else {
500                    crate::core::cross_source_hints::format_hints(&hints)
501                }
502            } else {
503                String::new()
504            }
505        };
506
507        let mut warnings = Vec::new();
508        if let Some(ref w) = budget_warning {
509            warnings.push(w.as_str());
510        }
511        if let Some(ref w) = degrade_warning {
512            warnings.push(w.as_str());
513        }
514        let final_output = if !warnings.is_empty() {
515            format!("{output}{hints_suffix}\n\n{}", warnings.join("\n"))
516        } else if hints_suffix.is_empty() {
517            output
518        } else {
519            format!("{output}{hints_suffix}")
520        };
521
522        Ok(ToolOutput {
523            text: final_output,
524            original_tokens: original,
525            saved_tokens: saved,
526            mode: Some(resolved_mode),
527            path: Some(path.to_string()),
528            changed: false,
529        })
530    }
531}
532
533fn apply_verdict(
534    mode: &str,
535    verdict: crate::core::degradation_policy::DegradationVerdictV1,
536) -> (String, bool) {
537    use crate::core::degradation_policy::DegradationVerdictV1;
538    match verdict {
539        DegradationVerdictV1::Ok => (mode.to_string(), false),
540        DegradationVerdictV1::Warn => match mode {
541            "full" => ("map".to_string(), true),
542            other => (other.to_string(), false),
543        },
544        DegradationVerdictV1::Throttle => match mode {
545            "full" | "map" => ("signatures".to_string(), true),
546            other => (other.to_string(), false),
547        },
548        DegradationVerdictV1::Block => {
549            if mode == "signatures" {
550                ("signatures".to_string(), false)
551            } else {
552                ("signatures".to_string(), true)
553            }
554        }
555    }
556}
557
558fn auto_degrade_read_mode(mode: &str) -> (String, Option<String>) {
559    let profile = crate::core::profiles::active_profile();
560    if !profile.degradation.enforce_effective() {
561        return (mode.to_string(), None);
562    }
563    let policy = crate::core::degradation_policy::evaluate_v1_for_tool("ctx_read", None);
564    let (new_mode, degraded) = apply_verdict(mode, policy.decision.verdict);
565    let warning = if degraded {
566        Some(format!(
567            "⚠ Context pressure: mode={mode} was downgraded to mode={new_mode} \
568             (verdict: {:?}). Use start_line=1 to bypass, or run ctx_compress to free budget.",
569            policy.decision.verdict
570        ))
571    } else {
572        None
573    };
574    (new_mode, warning)
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580    use std::sync::atomic::{AtomicUsize, Ordering};
581
582    #[test]
583    fn per_file_lock_same_path_returns_same_mutex() {
584        let lock_a1 = per_file_lock("/tmp/test_same_path.txt");
585        let lock_a2 = per_file_lock("/tmp/test_same_path.txt");
586        assert!(Arc::ptr_eq(&lock_a1, &lock_a2));
587    }
588
589    #[test]
590    fn per_file_lock_different_paths_return_different_mutexes() {
591        let lock_a = per_file_lock("/tmp/test_path_a.txt");
592        let lock_b = per_file_lock("/tmp/test_path_b.txt");
593        assert!(!Arc::ptr_eq(&lock_a, &lock_b));
594    }
595
596    #[test]
597    fn per_file_lock_serializes_concurrent_access() {
598        let counter = Arc::new(AtomicUsize::new(0));
599        let max_concurrent = Arc::new(AtomicUsize::new(0));
600        let path = "/tmp/test_concurrent_serialization.txt";
601        let mut handles = Vec::new();
602
603        for _ in 0..5 {
604            let counter = counter.clone();
605            let max_concurrent = max_concurrent.clone();
606            let path = path.to_string();
607            handles.push(std::thread::spawn(move || {
608                let lock = per_file_lock(&path);
609                let _guard = lock.lock().unwrap();
610                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
611                max_concurrent.fetch_max(active, Ordering::SeqCst);
612                std::thread::sleep(std::time::Duration::from_millis(10));
613                counter.fetch_sub(1, Ordering::SeqCst);
614            }));
615        }
616
617        for h in handles {
618            h.join().unwrap();
619        }
620
621        assert_eq!(max_concurrent.load(Ordering::SeqCst), 1);
622    }
623
624    #[test]
625    fn per_file_lock_allows_parallel_different_paths() {
626        let counter = Arc::new(AtomicUsize::new(0));
627        let max_concurrent = Arc::new(AtomicUsize::new(0));
628        let mut handles = Vec::new();
629
630        for i in 0..4 {
631            let counter = counter.clone();
632            let max_concurrent = max_concurrent.clone();
633            let path = format!("/tmp/test_parallel_{i}.txt");
634            handles.push(std::thread::spawn(move || {
635                let lock = per_file_lock(&path);
636                let _guard = lock.lock().unwrap();
637                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
638                max_concurrent.fetch_max(active, Ordering::SeqCst);
639                std::thread::sleep(std::time::Duration::from_millis(50));
640                counter.fetch_sub(1, Ordering::SeqCst);
641            }));
642        }
643
644        for h in handles {
645            h.join().unwrap();
646        }
647
648        assert!(max_concurrent.load(Ordering::SeqCst) > 1);
649    }
650
651    /// Regression test for Issue #229: a zombie thread holding the cache write-lock
652    /// must not block subsequent reads indefinitely. The try_write() loop inside
653    /// the spawned thread should respect its 25s deadline and the cancellation flag.
654    #[test]
655    fn zombie_thread_does_not_block_subsequent_cache_access() {
656        let cache: Arc<tokio::sync::RwLock<u32>> = Arc::new(tokio::sync::RwLock::new(0));
657
658        // Simulate a zombie: hold the write-lock on a background thread for 2s.
659        let zombie_lock = cache.clone();
660        let _zombie = std::thread::spawn(move || {
661            let _guard = zombie_lock.blocking_write();
662            std::thread::sleep(std::time::Duration::from_secs(2));
663        });
664        std::thread::sleep(std::time::Duration::from_millis(50));
665
666        // A try_read() must fail immediately (zombie holds write-lock).
667        assert!(cache.try_read().is_err());
668
669        // A try_write() loop with cancellation must exit promptly.
670        let cancel = Arc::new(AtomicBool::new(false));
671        let cancel2 = cancel.clone();
672        let lock2 = cache.clone();
673        let waiter = std::thread::spawn(move || {
674            let start = std::time::Instant::now();
675            loop {
676                if cancel2.load(Ordering::Relaxed) {
677                    return (false, start.elapsed());
678                }
679                if let Ok(_guard) = lock2.try_write() {
680                    return (true, start.elapsed());
681                }
682                std::thread::sleep(std::time::Duration::from_millis(50));
683            }
684        });
685
686        // Set cancellation after 200ms — the loop should exit quickly.
687        std::thread::sleep(std::time::Duration::from_millis(200));
688        cancel.store(true, Ordering::Relaxed);
689
690        let (acquired, elapsed) = waiter.join().unwrap();
691        assert!(
692            !acquired,
693            "should not have acquired lock while zombie holds it"
694        );
695        assert!(
696            elapsed < std::time::Duration::from_secs(1),
697            "cancellation should have stopped the loop promptly"
698        );
699    }
700
701    // -- Regression: GitHub Issue #253 + #259 --
702    // Helper that mirrors the runtime start_line logic.
703    fn apply_start_line(
704        mode: &mut String,
705        fresh: &mut bool,
706        explicit_mode: bool,
707        start_line: Option<i64>,
708    ) {
709        if let Some(sl) = start_line {
710            let sl = sl.max(1_i64);
711            if sl <= 1 {
712                return;
713            }
714            *fresh = true;
715            if !explicit_mode || mode.starts_with("lines") {
716                *mode = format!("lines:{sl}-999999");
717            }
718        }
719    }
720
721    #[test]
722    fn start_line_1_does_not_override_mode() {
723        let mut mode = "auto".to_string();
724        let mut fresh = false;
725        apply_start_line(&mut mode, &mut fresh, false, Some(1));
726        assert_eq!(mode, "auto", "start_line=1 should not change mode");
727        assert!(!fresh, "start_line=1 should not force fresh=true");
728    }
729
730    #[test]
731    fn start_line_gt1_overrides_implicit_mode() {
732        let mut mode = "auto".to_string();
733        let mut fresh = false;
734        apply_start_line(&mut mode, &mut fresh, false, Some(50));
735        assert_eq!(mode, "lines:50-999999");
736        assert!(fresh);
737    }
738
739    #[test]
740    fn start_line_gt1_does_not_override_explicit_map() {
741        // GitHub #259: mode=map + start_line=50 → mode stays map
742        let mut mode = "map".to_string();
743        let mut fresh = false;
744        apply_start_line(&mut mode, &mut fresh, true, Some(50));
745        assert_eq!(
746            mode, "map",
747            "explicit mode=map must not be clobbered by start_line"
748        );
749        assert!(fresh, "start_line>1 should still force fresh");
750    }
751
752    #[test]
753    fn start_line_gt1_does_not_override_explicit_signatures() {
754        let mut mode = "signatures".to_string();
755        let mut fresh = false;
756        apply_start_line(&mut mode, &mut fresh, true, Some(100));
757        assert_eq!(mode, "signatures");
758        assert!(fresh);
759    }
760
761    #[test]
762    fn start_line_gt1_honors_explicit_lines_mode() {
763        let mut mode = "lines:1-50".to_string();
764        let mut fresh = false;
765        apply_start_line(&mut mode, &mut fresh, true, Some(30));
766        assert_eq!(
767            mode, "lines:30-999999",
768            "explicit lines mode should accept start_line override"
769        );
770        assert!(fresh);
771    }
772
773    #[test]
774    fn start_line_none_does_nothing() {
775        let mut mode = "map".to_string();
776        let mut fresh = false;
777        apply_start_line(&mut mode, &mut fresh, true, None);
778        assert_eq!(mode, "map");
779        assert!(!fresh);
780    }
781
782    #[test]
783    fn start_line_1_with_explicit_mode_preserves_it() {
784        // OpenCode sends start_line=1 + mode=map — both should be preserved
785        let mut mode = "map".to_string();
786        let mut fresh = false;
787        apply_start_line(&mut mode, &mut fresh, true, Some(1));
788        assert_eq!(mode, "map");
789        assert!(!fresh);
790    }
791
792    // -- Regression: GitHub Issue #262 --
793    // auto_degrade_read_mode must produce a warning when mode is downgraded.
794
795    use crate::core::degradation_policy::DegradationVerdictV1;
796
797    #[test]
798    fn verdict_ok_does_not_degrade() {
799        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Ok);
800        assert_eq!(mode, "full");
801        assert!(!degraded);
802    }
803
804    #[test]
805    fn verdict_warn_degrades_full_to_map() {
806        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Warn);
807        assert_eq!(mode, "map");
808        assert!(degraded, "full→map must be flagged as degraded");
809    }
810
811    #[test]
812    fn verdict_warn_keeps_map() {
813        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Warn);
814        assert_eq!(mode, "map");
815        assert!(!degraded, "map is not degraded under Warn");
816    }
817
818    #[test]
819    fn verdict_warn_keeps_signatures() {
820        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Warn);
821        assert_eq!(mode, "signatures");
822        assert!(!degraded);
823    }
824
825    #[test]
826    fn verdict_throttle_degrades_full_to_signatures() {
827        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Throttle);
828        assert_eq!(mode, "signatures");
829        assert!(degraded);
830    }
831
832    #[test]
833    fn verdict_throttle_degrades_map_to_signatures() {
834        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Throttle);
835        assert_eq!(mode, "signatures");
836        assert!(degraded);
837    }
838
839    #[test]
840    fn verdict_throttle_keeps_lines() {
841        let (mode, degraded) = super::apply_verdict("lines:1-50", DegradationVerdictV1::Throttle);
842        assert_eq!(mode, "lines:1-50");
843        assert!(!degraded, "lines mode bypasses degradation");
844    }
845
846    #[test]
847    fn verdict_block_degrades_full_to_signatures() {
848        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Block);
849        assert_eq!(mode, "signatures");
850        assert!(degraded);
851    }
852
853    #[test]
854    fn verdict_block_does_not_degrade_signatures() {
855        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Block);
856        assert_eq!(mode, "signatures");
857        assert!(!degraded, "already at signatures — no degradation needed");
858    }
859
860    #[test]
861    fn degrade_warning_message_contains_mode_info() {
862        let (new_mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Warn);
863        assert!(degraded);
864        let warning = format!(
865            "⚠ Context pressure: mode=full was downgraded to mode={new_mode} (verdict: {:?}).",
866            DegradationVerdictV1::Warn
867        );
868        assert!(warning.contains("mode=full"));
869        assert!(warning.contains("mode=map"));
870        assert!(warning.contains("Warn"));
871    }
872}