Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

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