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::model::Tool;
5use rmcp::ErrorData;
6use serde_json::{json, Map, Value};
7
8use crate::server::tool_trait::{
9    get_bool, get_int, get_str, require_resolved_path, McpTool, ToolContext, ToolOutput,
10};
11use crate::tool_defs::tool_def;
12
13/// Per-file lock that serializes concurrent reads of the same path.
14///
15/// When multiple subagents read sequentially through a shared set of files,
16/// they tend to hit the same path at the same time. Without per-file locking
17/// they all contend on the global cache write lock while doing redundant I/O.
18/// This lock ensures only one thread reads a given file from disk; the others
19/// wait cheaply on the per-file mutex, then hit the warm cache.
20///
21/// Backed by the shared `core::path_locks` registry so reads and edits of the
22/// same path coordinate through a single mutex (see issue #320).
23fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
24    crate::core::path_locks::per_file_lock(path)
25}
26
27pub struct CtxReadTool;
28
29impl McpTool for CtxReadTool {
30    fn name(&self) -> &'static str {
31        "ctx_read"
32    }
33
34    fn tool_def(&self) -> Tool {
35        tool_def(
36            "ctx_read",
37            "Read a file. Prefer over native Read/cat/head/tail (cached, compressed).\n\
38             Unchanged re-reads cost ~13 tokens. Auto-selects mode (full|map|signatures|diff|aggressive|entropy|density:X|task|reference|raw|lines:N-M). fresh=true forces a disk re-read.",
39            json!({
40                "type": "object",
41                "properties": {
42                    "path": { "type": "string", "description": "Absolute file path to read" },
43                    "mode": {
44                        "type": "string",
45                        "description": "Compression mode (default: auto — resolved per file type/size). Explicit 'full' for guaranteed complete content with header/deps. Use 'raw' for zero-overhead file content (no header, no deps, no footer — ideal for one-shot CLI reads). Use 'map' for context-only files. For line ranges: 'lines:N-M' (e.g. 'lines:400-500'). For target density: 'density:0.4' keeps the highest-entropy lines until ~40% of the original tokens remain (SDE budget, deterministic)."
46                    },
47                    "start_line": {
48                        "type": "integer",
49                        "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."
50                    },
51                    "fresh": {
52                        "type": "boolean",
53                        "description": "Bypass cache and force a full re-read. Use when running as a subagent that may not have the parent's context."
54                    }
55                },
56                "required": ["path"]
57            }),
58        )
59    }
60
61    fn handle(
62        &self,
63        args: &Map<String, Value>,
64        ctx: &ToolContext,
65    ) -> Result<ToolOutput, ErrorData> {
66        let path = require_resolved_path(ctx, args, "path")?;
67
68        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
69            self.handle_inner(args, ctx, &path)
70        })) {
71            Ok(result) => result,
72            Err(_) => Err(ErrorData::internal_error(
73                format!("ctx_read panicked while processing '{path}'. This is a bug — please report it."),
74                None,
75            )),
76        }
77    }
78}
79
80impl CtxReadTool {
81    #[allow(clippy::unused_self)]
82    fn handle_inner(
83        &self,
84        args: &Map<String, Value>,
85        ctx: &ToolContext,
86        path: &str,
87    ) -> Result<ToolOutput, ErrorData> {
88        let session_lock = ctx
89            .session
90            .as_ref()
91            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
92        let cache_lock = ctx
93            .cache
94            .as_ref()
95            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
96
97        let current_task = {
98            let rt = tokio::runtime::Handle::current();
99            let mut attempt = 0u32;
100            loop {
101                if let Ok(session) = rt.block_on(tokio::time::timeout(
102                    std::time::Duration::from_secs(5),
103                    session_lock.read(),
104                )) {
105                    break session.task.as_ref().map(|t| t.description.clone());
106                }
107                attempt += 1;
108                if attempt >= 3 {
109                    tracing::warn!(
110                        "session read-lock timeout after {attempt} attempts in ctx_read for {path}"
111                    );
112                    return Err(ErrorData::internal_error(
113                        "session lock timeout — another tool may be holding it. Retry in a moment.",
114                        None,
115                    ));
116                }
117                tracing::debug!(
118                    "session read-lock attempt {attempt}/3 timed out for {path}, retrying"
119                );
120                std::thread::sleep(std::time::Duration::from_millis(100 * u64::from(attempt)));
121            }
122        };
123        let task_ref = current_task.as_deref();
124
125        let profile = crate::core::profiles::active_profile();
126        let explicit_mode_arg = get_str(args, "mode");
127        let explicit_mode = explicit_mode_arg.is_some();
128        let mut mode = if let Some(m) = explicit_mode_arg {
129            m
130        } else if profile.read.default_mode_effective() == "auto" {
131            if let Ok(cache) = cache_lock.try_read() {
132                crate::tools::ctx_smart_read::select_mode_with_task(&cache, path, task_ref)
133            } else {
134                tracing::debug!(
135                    "cache lock contested during auto-mode selection for {path}; \
136                     falling back to full"
137                );
138                "full".to_string()
139            }
140        } else {
141            profile.read.default_mode_effective().to_string()
142        };
143        let mut fresh = get_bool(args, "fresh").unwrap_or(false);
144        let cache_policy = crate::server::compaction_sync::effective_cache_policy();
145        if cache_policy == "off" {
146            fresh = true;
147        }
148        let start_line = get_int(args, "start_line");
149        if let Some(sl) = start_line {
150            let sl = sl.max(1_i64);
151            if sl > 1 {
152                fresh = true;
153                // Only override mode when no explicit mode was requested,
154                // or when the explicit mode is already a lines range.
155                // If the caller explicitly set mode=map/signatures/etc.,
156                // start_line must not clobber it (GitHub #259).
157                if !explicit_mode || mode.starts_with("lines") {
158                    mode = format!("lines:{sl}-999999");
159                }
160            }
161        }
162
163        let pressure_action = ctx.pressure_snapshot.as_ref().map(|p| &p.recommendation);
164        let resolved_agent_id = ctx.agent_id.as_ref().and_then(|a| match a.try_read() {
165            Ok(guard) => guard.clone(),
166            Err(_) => None,
167        });
168        let gate_result = crate::server::context_gate::pre_dispatch_read_for_agent(
169            path,
170            &mode,
171            task_ref,
172            Some(&ctx.project_root),
173            pressure_action,
174            resolved_agent_id.as_deref(),
175        );
176        if gate_result.budget_blocked {
177            let msg = gate_result
178                .budget_warning
179                .unwrap_or_else(|| "Agent token budget exceeded".to_string());
180            return Err(ErrorData::invalid_params(msg, None));
181        }
182        let budget_warning = gate_result.budget_warning.clone();
183        if let Some(overridden) = gate_result.overridden_mode {
184            mode = overridden;
185        }
186
187        let (mode, degrade_warning) = if crate::tools::ctx_read::is_instruction_file(path) {
188            ("full".to_string(), None)
189        } else {
190            auto_degrade_read_mode(&mode)
191        };
192
193        if mode.starts_with("lines:") {
194            fresh = true;
195        }
196
197        if crate::core::binary_detect::is_binary_file(path) {
198            let msg = crate::core::binary_detect::binary_file_message(path);
199            return Err(ErrorData::invalid_params(msg, None));
200        }
201        {
202            let cap = crate::core::limits::max_read_bytes() as u64;
203            if let Ok(meta) = std::fs::metadata(path) {
204                if meta.len() > cap {
205                    let msg = format!(
206                        "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
207                         Use mode=\"lines:1-100\" for partial reads or increase the limit.",
208                        meta.len(),
209                        cap
210                    );
211                    return Err(ErrorData::invalid_params(msg, None));
212                }
213            }
214        }
215
216        // Compaction-aware: if host compacted since last check, reset delivery flags
217        // so post-compaction reads deliver full content instead of stubs.
218        if !fresh {
219            if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
220                if let Ok(mut cache) = cache_lock.try_write() {
221                    crate::server::compaction_sync::sync_if_compacted(&mut cache, &data_dir);
222                }
223            }
224        }
225
226        // Fast path: if both per-file lock and cache write-lock are immediately
227        // available, execute inline without spawning a thread. This avoids thread +
228        // channel overhead for the ~90% of calls that are cache hits.
229        let read_timeout = std::time::Duration::from_secs(30);
230        let cancelled = Arc::new(AtomicBool::new(false));
231        let (output, resolved_mode, original, is_cache_hit, file_ref, cache_stats) = {
232            let crp_mode = ctx.crp_mode;
233            let task_ref = current_task.as_deref();
234
235            let fast_result = 'fast: {
236                let file_lock = per_file_lock(path);
237                let Some(_file_guard) = file_lock.try_lock().ok() else {
238                    break 'fast None;
239                };
240
241                // Phase 1 (shared lock): the dominant case is re-reading an
242                // unchanged file in full mode. Serve that stub under a *read*
243                // lock so parallel reads of distinct files run concurrently
244                // instead of serializing on the global write lock.
245                if !fresh && mode == "full" {
246                    if let Ok(cache) = cache_lock.try_read() {
247                        if let Some(read_output) =
248                            crate::tools::ctx_read::try_stub_hit_readonly(&cache, path)
249                        {
250                            let content = read_output.content;
251                            let rmode = read_output.resolved_mode;
252                            let orig = cache.get(path).map_or(0, |e| e.original_tokens);
253                            let hit = content.contains(" cached ")
254                                || content.contains("[unchanged")
255                                || content.contains("[delta:");
256                            let fref = cache.file_ref_map().get(path).cloned();
257                            let stats = cache.get_stats();
258                            let stats_snapshot = (stats.total_reads(), stats.cache_hits());
259                            break 'fast Some((content, rmode, orig, hit, fref, stats_snapshot));
260                        }
261                    }
262                }
263
264                // Phase 2 (write lock): cache miss, changed file, or non-stub
265                // modes (map/signatures/diff/lines) that mutate cache state.
266                let Some(mut cache) = cache_lock.try_write().ok() else {
267                    break 'fast None;
268                };
269                let read_output = if fresh {
270                    crate::tools::ctx_read::handle_fresh_with_task_resolved(
271                        &mut cache, path, &mode, crp_mode, task_ref,
272                    )
273                } else {
274                    crate::tools::ctx_read::handle_with_task_resolved(
275                        &mut cache, path, &mode, crp_mode, task_ref,
276                    )
277                };
278                let content = read_output.content;
279                let rmode = read_output.resolved_mode;
280                let orig = cache.get(path).map_or(0, |e| e.original_tokens);
281                let hit = content.contains(" cached ")
282                    || content.contains("[unchanged")
283                    || content.contains("[delta:");
284                let fref = cache.file_ref_map().get(path).cloned();
285                let stats = cache.get_stats();
286                let stats_snapshot = (stats.total_reads(), stats.cache_hits());
287                Some((content, rmode, orig, hit, fref, stats_snapshot))
288            };
289
290            if let Some(result) = fast_result {
291                result
292            } else {
293                // Slow path: spawn thread with bounded timeout for contended locks.
294                let cache_lock = cache_lock.clone();
295                let mode = mode.clone();
296                let task_owned = current_task.clone();
297                let path_owned = path.to_string();
298                let cancel_flag = cancelled.clone();
299                let (tx, rx) = std::sync::mpsc::sync_channel(1);
300                std::thread::spawn(move || {
301                    let file_lock = per_file_lock(&path_owned);
302
303                    // Bounded per-file lock: if a zombie thread still holds it, don't
304                    // wait forever. 25s keeps us inside the 30s recv_timeout.
305                    let _file_guard = {
306                        let deadline =
307                            std::time::Instant::now() + std::time::Duration::from_secs(25);
308                        loop {
309                            if cancel_flag.load(Ordering::Relaxed) {
310                                return;
311                            }
312                            if let Ok(guard) = file_lock.try_lock() {
313                                break guard;
314                            }
315                            if std::time::Instant::now() >= deadline {
316                                tracing::error!(
317                                    "ctx_read: per-file lock timeout after 25s for {path_owned}"
318                                );
319                                let _ = tx.send((
320                                    format!("per-file lock contention for {path_owned} — retry in a moment"),
321                                    "error".to_string(), 0, false, None, (0, 0),
322                                ));
323                                return;
324                            }
325                            std::thread::sleep(std::time::Duration::from_millis(50));
326                        }
327                    };
328
329                    if cancel_flag.load(Ordering::Relaxed) {
330                        return;
331                    }
332
333                    // Bounded cache write-lock: avoids indefinite block when a zombie
334                    // thread from a previous timed-out call still holds the lock.
335                    let mut cache = {
336                        let deadline =
337                            std::time::Instant::now() + std::time::Duration::from_secs(25);
338                        loop {
339                            if cancel_flag.load(Ordering::Relaxed) {
340                                return;
341                            }
342                            if let Ok(guard) = cache_lock.try_write() {
343                                break guard;
344                            }
345                            if std::time::Instant::now() >= deadline {
346                                tracing::error!(
347                                    "ctx_read: cache write-lock timeout after 25s for {path_owned}"
348                                );
349                                let _ = tx.send((
350                                    format!("cache lock contention for {path_owned} — retry in a moment"),
351                                    "error".to_string(), 0, false, None, (0, 0),
352                                ));
353                                return;
354                            }
355                            std::thread::sleep(std::time::Duration::from_millis(50));
356                        }
357                    };
358
359                    let task_ref = task_owned.as_deref();
360                    let read_output = if fresh {
361                        crate::tools::ctx_read::handle_fresh_with_task_resolved(
362                            &mut cache,
363                            &path_owned,
364                            &mode,
365                            crp_mode,
366                            task_ref,
367                        )
368                    } else {
369                        crate::tools::ctx_read::handle_with_task_resolved(
370                            &mut cache,
371                            &path_owned,
372                            &mode,
373                            crp_mode,
374                            task_ref,
375                        )
376                    };
377                    let content = read_output.content;
378                    let rmode = read_output.resolved_mode;
379                    let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
380                    let hit = content.contains(" cached ");
381                    let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
382                    let stats = cache.get_stats();
383                    let stats_snapshot = (stats.total_reads(), stats.cache_hits());
384                    let _ = tx.send((content, rmode, orig, hit, fref, stats_snapshot));
385                });
386                if let Ok(result) = rx.recv_timeout(read_timeout) {
387                    result
388                } else {
389                    cancelled.store(true, Ordering::Relaxed);
390                    tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
391                    let msg = format!(
392                        "ERROR: ctx_read timed out after {}s reading {path}. \
393                     The file may be very large or a blocking I/O issue occurred. \
394                     Try mode=\"lines:1-100\" for a partial read.",
395                        read_timeout.as_secs()
396                    );
397                    return Err(ErrorData::internal_error(msg, None));
398                }
399            } // end else (slow path)
400        };
401
402        // Convert error results to proper MCP ErrorData instead of success body
403        if resolved_mode == "error" {
404            return Err(ErrorData::invalid_params(output, None));
405        }
406
407        let output_tokens = crate::core::tokens::count_tokens(&output);
408        let saved = original.saturating_sub(output_tokens);
409
410        // Session updates (bounded lock — 10s timeout, read already succeeded)
411        let mut ensured_root: Option<String> = None;
412        let mut traversal_working_set: Vec<String> = Vec::new();
413        let project_root_snapshot;
414        {
415            let rt = tokio::runtime::Handle::current();
416            let session_guard = rt.block_on(tokio::time::timeout(
417                std::time::Duration::from_secs(10),
418                session_lock.write(),
419            ));
420            if let Ok(mut session) = session_guard {
421                session.touch_file(path, file_ref.as_deref(), &resolved_mode, original);
422                // Capture the recent working set (under the lock) so the
423                // background thread can record a traversal/co-access edge (#289).
424                traversal_working_set =
425                    crate::core::tool_lifecycle::recent_working_set(&session, path);
426                // Auto-generate file summary from output content
427                let file_summary = extract_file_summary(&output, path);
428                if !file_summary.is_empty() {
429                    session.set_file_summary(path, &file_summary);
430                }
431                if is_cache_hit {
432                    session.record_cache_hit();
433                }
434                if session.active_structured_intent.is_none() && session.files_touched.len() >= 2 {
435                    let touched: Vec<String> = session
436                        .files_touched
437                        .iter()
438                        .map(|f| f.path.clone())
439                        .collect();
440                    let inferred =
441                        crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
442                    if inferred.confidence >= 0.4 {
443                        session.active_structured_intent = Some(inferred);
444                    }
445                }
446                // Auto-infer task every 5th file read if not explicitly set
447                if session.task.is_none() && session.stats.files_read % 5 == 0 {
448                    session.auto_infer_task();
449                }
450                let root_missing = session
451                    .project_root
452                    .as_deref()
453                    .is_none_or(|r| r.trim().is_empty());
454                if root_missing {
455                    if let Some(root) = crate::core::protocol::detect_project_root(path) {
456                        session.project_root = Some(root.clone());
457                        ensured_root = Some(root);
458                    }
459                }
460                project_root_snapshot = session
461                    .project_root
462                    .clone()
463                    .unwrap_or_else(|| ".".to_string());
464            } else {
465                tracing::warn!(
466                    "session write-lock timeout (5s) in ctx_read post-update for {path}"
467                );
468                project_root_snapshot = ctx.project_root.clone();
469            }
470        }
471
472        if let Some(root) = ensured_root.as_deref() {
473            crate::core::index_orchestrator::ensure_all_background(root);
474        }
475
476        // Telemetry + learning are pure side-effects that never influence this
477        // response, yet they did synchronous disk I/O on every read (heatmap
478        // append, ModePredictor load+save, FeedbackStore load). Push them off
479        // the hot path so reads — especially cache-hit stubs — return without
480        // waiting on disk (#149).
481        {
482            let path_bg = path.to_string();
483            let resolved_mode_bg = resolved_mode.clone();
484            let project_root_bg = project_root_snapshot.clone();
485            let (turns, hits) = cache_stats;
486            std::thread::spawn(move || {
487                // A panic in telemetry must not poison locks or leave a zombie thread;
488                // it never affects the already-returned read response.
489                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
490                    crate::core::heatmap::record_file_access(&path_bg, original, saved);
491
492                    // Traversal/co-access edge: this read fired together with the
493                    // recent working set captured under the session lock (#289).
494                    if let Some(root) =
495                        crate::core::tool_lifecycle::usable_root(Some(project_root_bg.as_str()))
496                    {
497                        crate::core::cooccurrence::record_focus_access(
498                            root,
499                            &path_bg,
500                            &traversal_working_set,
501                        );
502                    }
503
504                    let sig =
505                        crate::core::mode_predictor::FileSignature::from_path(&path_bg, original);
506                    let density = if output_tokens > 0 {
507                        original as f64 / output_tokens as f64
508                    } else {
509                        1.0
510                    };
511                    let outcome = crate::core::mode_predictor::ModeOutcome {
512                        mode: resolved_mode_bg,
513                        tokens_in: original,
514                        tokens_out: output_tokens,
515                        density: density.min(1.0),
516                    };
517                    let mut predictor = crate::core::mode_predictor::ModePredictor::new();
518                    predictor.set_project_root(&project_root_bg);
519                    predictor.record(sig, outcome);
520                    predictor.save();
521
522                    let ext = std::path::Path::new(&path_bg)
523                        .extension()
524                        .and_then(|e| e.to_str())
525                        .unwrap_or("")
526                        .to_string();
527                    let thresholds =
528                        crate::core::adaptive_thresholds::thresholds_for_path(&path_bg);
529                    let feedback_outcome = crate::core::feedback::CompressionOutcome {
530                        session_id: format!("{}", std::process::id()),
531                        language: ext,
532                        entropy_threshold: thresholds.bpe_entropy,
533                        jaccard_threshold: thresholds.jaccard,
534                        total_turns: turns as u32,
535                        tokens_saved: saved as u64,
536                        tokens_original: original as u64,
537                        cache_hits: hits as u32,
538                        total_reads: turns as u32,
539                        task_completed: true,
540                        timestamp: chrono::Local::now().to_rfc3339(),
541                    };
542                    let mut store = crate::core::feedback::FeedbackStore::load();
543                    store.project_root = Some(project_root_bg);
544                    store.record_outcome(feedback_outcome);
545                }));
546            });
547        }
548
549        if let Some(aid) = resolved_agent_id.as_deref() {
550            crate::core::agent_budget::record_consumption(aid, output_tokens);
551        }
552
553        // Cross-source hints: if a graph index exists and has cross-source edges
554        // pointing to this file, append compact hints so the agent knows about
555        // related issues/PRs/schemas without a separate tool call.
556        let hints_suffix = {
557            if let Some(index) = crate::core::graph_index::ProjectIndex::load(&ctx.project_root) {
558                let hints = crate::core::cross_source_hints::hints_for_file(
559                    path,
560                    &index.edges,
561                    &ctx.project_root,
562                );
563                if hints.is_empty() {
564                    String::new()
565                } else {
566                    crate::core::cross_source_hints::format_hints(&hints)
567                }
568            } else {
569                String::new()
570            }
571        };
572
573        let mut warnings = Vec::new();
574        if let Some(ref w) = budget_warning {
575            warnings.push(w.as_str());
576        }
577        if let Some(ref w) = degrade_warning {
578            warnings.push(w.as_str());
579        }
580        let final_output = if !warnings.is_empty() {
581            format!("{output}{hints_suffix}\n\n{}", warnings.join("\n"))
582        } else if hints_suffix.is_empty() {
583            output
584        } else {
585            format!("{output}{hints_suffix}")
586        };
587
588        Ok(ToolOutput {
589            text: final_output,
590            original_tokens: original,
591            saved_tokens: saved,
592            mode: Some(resolved_mode),
593            path: Some(path.to_string()),
594            changed: false,
595            shell_outcome: None,
596        })
597    }
598}
599
600fn apply_verdict(
601    mode: &str,
602    verdict: crate::core::degradation_policy::DegradationVerdictV1,
603) -> (String, bool) {
604    use crate::core::degradation_policy::DegradationVerdictV1;
605    match verdict {
606        DegradationVerdictV1::Ok => (mode.to_string(), false),
607        DegradationVerdictV1::Warn => match mode {
608            "full" => ("map".to_string(), true),
609            other => (other.to_string(), false),
610        },
611        DegradationVerdictV1::Throttle => match mode {
612            "full" | "map" => ("signatures".to_string(), true),
613            other => (other.to_string(), false),
614        },
615        DegradationVerdictV1::Block => {
616            if mode == "signatures" {
617                ("signatures".to_string(), false)
618            } else {
619                ("signatures".to_string(), true)
620            }
621        }
622    }
623}
624
625fn auto_degrade_read_mode(mode: &str) -> (String, Option<String>) {
626    if crate::core::config::Config::load().no_degrade_effective() {
627        return (mode.to_string(), None);
628    }
629    let profile = crate::core::profiles::active_profile();
630    if !profile.degradation.enforce_effective() {
631        return (mode.to_string(), None);
632    }
633    let policy = crate::core::degradation_policy::evaluate_v1_for_tool("ctx_read", None);
634    let (new_mode, degraded) = apply_verdict(mode, policy.decision.verdict);
635    let warning = if degraded {
636        Some(format!(
637            "⚠ Context pressure: mode={mode} was downgraded to mode={new_mode} \
638             (verdict: {:?}). Use start_line=1 to bypass, or run ctx_compress to free budget.",
639            policy.decision.verdict
640        ))
641    } else {
642        None
643    };
644    (new_mode, warning)
645}
646
647fn extract_file_summary(output: &str, path: &str) -> String {
648    let hint = crate::core::auto_findings::extract_content_hint(output);
649    if !hint.is_empty() {
650        return hint;
651    }
652    let ext = std::path::Path::new(path)
653        .extension()
654        .and_then(|e| e.to_str())
655        .unwrap_or("");
656    let line_count = output.lines().count();
657    if line_count > 5 {
658        format!("{ext} file, {line_count} lines")
659    } else {
660        String::new()
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667    use std::sync::atomic::{AtomicUsize, Ordering};
668
669    #[test]
670    fn per_file_lock_same_path_returns_same_mutex() {
671        let lock_a1 = per_file_lock("/tmp/test_same_path.txt");
672        let lock_a2 = per_file_lock("/tmp/test_same_path.txt");
673        assert!(Arc::ptr_eq(&lock_a1, &lock_a2));
674    }
675
676    #[test]
677    fn per_file_lock_different_paths_return_different_mutexes() {
678        let lock_a = per_file_lock("/tmp/test_path_a.txt");
679        let lock_b = per_file_lock("/tmp/test_path_b.txt");
680        assert!(!Arc::ptr_eq(&lock_a, &lock_b));
681    }
682
683    #[test]
684    fn per_file_lock_serializes_concurrent_access() {
685        let counter = Arc::new(AtomicUsize::new(0));
686        let max_concurrent = Arc::new(AtomicUsize::new(0));
687        let path = "/tmp/test_concurrent_serialization.txt";
688        let mut handles = Vec::new();
689
690        for _ in 0..5 {
691            let counter = counter.clone();
692            let max_concurrent = max_concurrent.clone();
693            let path = path.to_string();
694            handles.push(std::thread::spawn(move || {
695                let lock = per_file_lock(&path);
696                let _guard = lock.lock().unwrap();
697                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
698                max_concurrent.fetch_max(active, Ordering::SeqCst);
699                std::thread::sleep(std::time::Duration::from_millis(10));
700                counter.fetch_sub(1, Ordering::SeqCst);
701            }));
702        }
703
704        for h in handles {
705            h.join().unwrap();
706        }
707
708        assert_eq!(max_concurrent.load(Ordering::SeqCst), 1);
709    }
710
711    #[test]
712    fn per_file_lock_allows_parallel_different_paths() {
713        let counter = Arc::new(AtomicUsize::new(0));
714        let max_concurrent = Arc::new(AtomicUsize::new(0));
715        let mut handles = Vec::new();
716
717        for i in 0..4 {
718            let counter = counter.clone();
719            let max_concurrent = max_concurrent.clone();
720            let path = format!("/tmp/test_parallel_{i}.txt");
721            handles.push(std::thread::spawn(move || {
722                let lock = per_file_lock(&path);
723                let _guard = lock.lock().unwrap();
724                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
725                max_concurrent.fetch_max(active, Ordering::SeqCst);
726                std::thread::sleep(std::time::Duration::from_millis(50));
727                counter.fetch_sub(1, Ordering::SeqCst);
728            }));
729        }
730
731        for h in handles {
732            h.join().unwrap();
733        }
734
735        assert!(max_concurrent.load(Ordering::SeqCst) > 1);
736    }
737
738    /// Regression test for Issue #229: a zombie thread holding the cache write-lock
739    /// must not block subsequent reads indefinitely. The try_write() loop inside
740    /// the spawned thread should respect its 25s deadline and the cancellation flag.
741    #[test]
742    fn zombie_thread_does_not_block_subsequent_cache_access() {
743        let cache: Arc<tokio::sync::RwLock<u32>> = Arc::new(tokio::sync::RwLock::new(0));
744
745        // Simulate a zombie: hold the write-lock on a background thread for 2s.
746        let zombie_lock = cache.clone();
747        let _zombie = std::thread::spawn(move || {
748            let _guard = zombie_lock.blocking_write();
749            std::thread::sleep(std::time::Duration::from_secs(2));
750        });
751        std::thread::sleep(std::time::Duration::from_millis(50));
752
753        // A try_read() must fail immediately (zombie holds write-lock).
754        assert!(cache.try_read().is_err());
755
756        // A try_write() loop with cancellation must exit promptly.
757        let cancel = Arc::new(AtomicBool::new(false));
758        let cancel2 = cancel.clone();
759        let lock2 = cache.clone();
760        let waiter = std::thread::spawn(move || {
761            let start = std::time::Instant::now();
762            loop {
763                if cancel2.load(Ordering::Relaxed) {
764                    return (false, start.elapsed());
765                }
766                if let Ok(_guard) = lock2.try_write() {
767                    return (true, start.elapsed());
768                }
769                std::thread::sleep(std::time::Duration::from_millis(50));
770            }
771        });
772
773        // Set cancellation after 200ms — the loop should exit quickly.
774        std::thread::sleep(std::time::Duration::from_millis(200));
775        cancel.store(true, Ordering::Relaxed);
776
777        let (acquired, elapsed) = waiter.join().unwrap();
778        assert!(
779            !acquired,
780            "should not have acquired lock while zombie holds it"
781        );
782        assert!(
783            elapsed < std::time::Duration::from_secs(1),
784            "cancellation should have stopped the loop promptly"
785        );
786    }
787
788    // -- Regression: GitHub Issue #253 + #259 --
789    // Helper that mirrors the runtime start_line logic.
790    fn apply_start_line(
791        mode: &mut String,
792        fresh: &mut bool,
793        explicit_mode: bool,
794        start_line: Option<i64>,
795    ) {
796        if let Some(sl) = start_line {
797            let sl = sl.max(1_i64);
798            if sl <= 1 {
799                return;
800            }
801            *fresh = true;
802            if !explicit_mode || mode.starts_with("lines") {
803                *mode = format!("lines:{sl}-999999");
804            }
805        }
806    }
807
808    #[test]
809    fn start_line_1_does_not_override_mode() {
810        let mut mode = "auto".to_string();
811        let mut fresh = false;
812        apply_start_line(&mut mode, &mut fresh, false, Some(1));
813        assert_eq!(mode, "auto", "start_line=1 should not change mode");
814        assert!(!fresh, "start_line=1 should not force fresh=true");
815    }
816
817    #[test]
818    fn start_line_gt1_overrides_implicit_mode() {
819        let mut mode = "auto".to_string();
820        let mut fresh = false;
821        apply_start_line(&mut mode, &mut fresh, false, Some(50));
822        assert_eq!(mode, "lines:50-999999");
823        assert!(fresh);
824    }
825
826    #[test]
827    fn start_line_gt1_does_not_override_explicit_map() {
828        // GitHub #259: mode=map + start_line=50 → mode stays map
829        let mut mode = "map".to_string();
830        let mut fresh = false;
831        apply_start_line(&mut mode, &mut fresh, true, Some(50));
832        assert_eq!(
833            mode, "map",
834            "explicit mode=map must not be clobbered by start_line"
835        );
836        assert!(fresh, "start_line>1 should still force fresh");
837    }
838
839    #[test]
840    fn start_line_gt1_does_not_override_explicit_signatures() {
841        let mut mode = "signatures".to_string();
842        let mut fresh = false;
843        apply_start_line(&mut mode, &mut fresh, true, Some(100));
844        assert_eq!(mode, "signatures");
845        assert!(fresh);
846    }
847
848    #[test]
849    fn start_line_gt1_honors_explicit_lines_mode() {
850        let mut mode = "lines:1-50".to_string();
851        let mut fresh = false;
852        apply_start_line(&mut mode, &mut fresh, true, Some(30));
853        assert_eq!(
854            mode, "lines:30-999999",
855            "explicit lines mode should accept start_line override"
856        );
857        assert!(fresh);
858    }
859
860    #[test]
861    fn start_line_none_does_nothing() {
862        let mut mode = "map".to_string();
863        let mut fresh = false;
864        apply_start_line(&mut mode, &mut fresh, true, None);
865        assert_eq!(mode, "map");
866        assert!(!fresh);
867    }
868
869    #[test]
870    fn start_line_1_with_explicit_mode_preserves_it() {
871        // OpenCode sends start_line=1 + mode=map — both should be preserved
872        let mut mode = "map".to_string();
873        let mut fresh = false;
874        apply_start_line(&mut mode, &mut fresh, true, Some(1));
875        assert_eq!(mode, "map");
876        assert!(!fresh);
877    }
878
879    // -- Regression: GitHub Issue #262 --
880    // auto_degrade_read_mode must produce a warning when mode is downgraded.
881
882    use crate::core::degradation_policy::DegradationVerdictV1;
883
884    #[test]
885    fn verdict_ok_does_not_degrade() {
886        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Ok);
887        assert_eq!(mode, "full");
888        assert!(!degraded);
889    }
890
891    #[test]
892    fn verdict_warn_degrades_full_to_map() {
893        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Warn);
894        assert_eq!(mode, "map");
895        assert!(degraded, "full→map must be flagged as degraded");
896    }
897
898    #[test]
899    fn verdict_warn_keeps_map() {
900        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Warn);
901        assert_eq!(mode, "map");
902        assert!(!degraded, "map is not degraded under Warn");
903    }
904
905    #[test]
906    fn verdict_warn_keeps_signatures() {
907        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Warn);
908        assert_eq!(mode, "signatures");
909        assert!(!degraded);
910    }
911
912    #[test]
913    fn verdict_throttle_degrades_full_to_signatures() {
914        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Throttle);
915        assert_eq!(mode, "signatures");
916        assert!(degraded);
917    }
918
919    #[test]
920    fn verdict_throttle_degrades_map_to_signatures() {
921        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Throttle);
922        assert_eq!(mode, "signatures");
923        assert!(degraded);
924    }
925
926    #[test]
927    fn verdict_throttle_keeps_lines() {
928        let (mode, degraded) = super::apply_verdict("lines:1-50", DegradationVerdictV1::Throttle);
929        assert_eq!(mode, "lines:1-50");
930        assert!(!degraded, "lines mode bypasses degradation");
931    }
932
933    #[test]
934    fn verdict_block_degrades_full_to_signatures() {
935        let (mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Block);
936        assert_eq!(mode, "signatures");
937        assert!(degraded);
938    }
939
940    #[test]
941    fn verdict_block_does_not_degrade_signatures() {
942        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Block);
943        assert_eq!(mode, "signatures");
944        assert!(!degraded, "already at signatures — no degradation needed");
945    }
946
947    #[test]
948    fn degrade_warning_message_contains_mode_info() {
949        let (new_mode, degraded) = super::apply_verdict("full", DegradationVerdictV1::Warn);
950        assert!(degraded);
951        let warning = format!(
952            "⚠ Context pressure: mode=full was downgraded to mode={new_mode} (verdict: {:?}).",
953            DegradationVerdictV1::Warn
954        );
955        assert!(warning.contains("mode=full"));
956        assert!(warning.contains("mode=map"));
957        assert!(warning.contains("Warn"));
958    }
959
960    // --- auto_degrade_read_mode: no_degrade integration ---
961    // With default config (no LCTX_NO_DEGRADE), the profile's degradation.enforce
962    // is also off by default, so auto_degrade_read_mode returns mode unchanged.
963
964    #[test]
965    fn auto_degrade_preserves_full_when_default_config() {
966        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
967            return;
968        }
969        let (mode, warning) = super::auto_degrade_read_mode("full");
970        assert_eq!(mode, "full");
971        assert!(warning.is_none());
972    }
973
974    #[test]
975    fn auto_degrade_preserves_map_when_default_config() {
976        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
977            return;
978        }
979        let (mode, warning) = super::auto_degrade_read_mode("map");
980        assert_eq!(mode, "map");
981        assert!(warning.is_none());
982    }
983
984    #[test]
985    fn auto_degrade_preserves_signatures_when_default_config() {
986        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
987            return;
988        }
989        let (mode, warning) = super::auto_degrade_read_mode("signatures");
990        assert_eq!(mode, "signatures");
991        assert!(warning.is_none());
992    }
993
994    #[test]
995    fn auto_degrade_preserves_diff_always() {
996        let (mode, warning) = super::auto_degrade_read_mode("diff");
997        assert_eq!(mode, "diff");
998        assert!(warning.is_none());
999    }
1000
1001    #[test]
1002    fn auto_degrade_preserves_lines_mode_always() {
1003        let (mode, warning) = super::auto_degrade_read_mode("lines:10-50");
1004        assert_eq!(mode, "lines:10-50");
1005        assert!(warning.is_none());
1006    }
1007
1008    #[test]
1009    fn auto_degrade_preserves_aggressive_when_default_config() {
1010        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1011            return;
1012        }
1013        let (mode, warning) = super::auto_degrade_read_mode("aggressive");
1014        assert_eq!(mode, "aggressive");
1015        assert!(warning.is_none());
1016    }
1017
1018    #[test]
1019    fn auto_degrade_preserves_entropy_when_default_config() {
1020        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1021            return;
1022        }
1023        let (mode, warning) = super::auto_degrade_read_mode("entropy");
1024        assert_eq!(mode, "entropy");
1025        assert!(warning.is_none());
1026    }
1027
1028    #[test]
1029    fn auto_degrade_preserves_auto_when_default_config() {
1030        if std::env::var("LCTX_NO_DEGRADE").is_ok() {
1031            return;
1032        }
1033        let (mode, warning) = super::auto_degrade_read_mode("auto");
1034        assert_eq!(mode, "auto");
1035        assert!(warning.is_none());
1036    }
1037
1038    // --- apply_verdict: exhaustive mode × verdict matrix ---
1039
1040    #[test]
1041    fn verdict_warn_does_not_degrade_diff() {
1042        let (mode, degraded) = super::apply_verdict("diff", DegradationVerdictV1::Warn);
1043        assert_eq!(mode, "diff");
1044        assert!(!degraded);
1045    }
1046
1047    #[test]
1048    fn verdict_throttle_does_not_degrade_signatures() {
1049        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Throttle);
1050        assert_eq!(mode, "signatures");
1051        assert!(!degraded);
1052    }
1053
1054    #[test]
1055    fn verdict_ok_preserves_map() {
1056        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Ok);
1057        assert_eq!(mode, "map");
1058        assert!(!degraded);
1059    }
1060
1061    #[test]
1062    fn verdict_ok_preserves_signatures() {
1063        let (mode, degraded) = super::apply_verdict("signatures", DegradationVerdictV1::Ok);
1064        assert_eq!(mode, "signatures");
1065        assert!(!degraded);
1066    }
1067
1068    #[test]
1069    fn verdict_ok_preserves_lines() {
1070        let (mode, degraded) = super::apply_verdict("lines:1-100", DegradationVerdictV1::Ok);
1071        assert_eq!(mode, "lines:1-100");
1072        assert!(!degraded);
1073    }
1074
1075    #[test]
1076    fn verdict_block_degrades_map_to_signatures() {
1077        let (mode, degraded) = super::apply_verdict("map", DegradationVerdictV1::Block);
1078        assert_eq!(mode, "signatures");
1079        assert!(degraded);
1080    }
1081}