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