Skip to main content

lean_ctx/tools/
ctx_read.rs

1use std::path::Path;
2
3use crate::core::cache::SessionCache;
4use crate::core::compressor;
5use crate::core::deps;
6use crate::core::entropy;
7use crate::core::protocol;
8use crate::core::signatures;
9use crate::core::symbol_map::{self, SymbolMap};
10use crate::core::tokens::count_tokens;
11use crate::tools::CrpMode;
12
13/// Pre-counted read output carrying the output string, resolved mode,
14/// and token count computed during mode processing.
15pub struct ReadOutput {
16    pub content: String,
17    pub resolved_mode: String,
18    /// Approximate output token count from mode processing.
19    /// The dispatch layer recounts the final assembled string for accurate savings.
20    pub output_tokens: usize,
21}
22
23const COMPRESSED_HINT: &str = "[compressed — use mode=\"full\" for complete source]";
24
25const CACHEABLE_MODES: &[&str] = &["map", "signatures"];
26
27fn is_cacheable_mode(mode: &str) -> bool {
28    CACHEABLE_MODES.contains(&mode)
29}
30
31fn compressed_cache_key(mode: &str, crp_mode: CrpMode) -> String {
32    if crp_mode.is_tdd() {
33        format!("{mode}:tdd")
34    } else {
35        mode.to_string()
36    }
37}
38
39fn append_compressed_hint(output: &str, file_path: &str) -> String {
40    if !crate::core::profiles::active_profile()
41        .output_hints
42        .compressed_hint()
43    {
44        return output.to_string();
45    }
46    format!(
47        "{output}\n{COMPRESSED_HINT}\n  ctx_read(\"{file_path}\", mode=\"full\") | ctx_retrieve(\"{file_path}\")"
48    )
49}
50
51/// Reads a file as UTF-8 with lossy fallback, enforcing binary detection and max read size limit.
52/// Defense-in-depth: verifies that the canonical path stays within the process's project root
53/// (if determinable) even though callers SHOULD have already jail-checked the path.
54pub fn read_file_lossy(path: &str) -> Result<String, std::io::Error> {
55    if crate::core::binary_detect::is_binary_file(path) {
56        let msg = crate::core::binary_detect::binary_file_message(path);
57        return Err(std::io::Error::other(msg));
58    }
59
60    if let Ok(canonical) = std::path::Path::new(path).canonicalize() {
61        if let Ok(cwd) = std::env::current_dir() {
62            let root = crate::core::pathjail::canonicalize_or_self(&cwd);
63            if !canonical.starts_with(&root) {
64                let allow = crate::core::pathjail::allow_paths_from_env_and_config();
65                let data_dir_ok = crate::core::data_dir::lean_ctx_data_dir()
66                    .ok()
67                    .is_some_and(|d| canonical.starts_with(d));
68                let tmp_ok = canonical.starts_with(std::env::temp_dir());
69                if !allow.iter().any(|a| canonical.starts_with(a)) && !data_dir_ok && !tmp_ok {
70                    tracing::warn!(
71                        "defense-in-depth: path may escape project root: {}",
72                        canonical.display()
73                    );
74                }
75            }
76        }
77    }
78
79    let cap = crate::core::limits::max_read_bytes();
80
81    let file = open_with_retry(path)?;
82    let meta = file
83        .metadata()
84        .map_err(|e| std::io::Error::other(format!("cannot stat open file descriptor: {e}")))?;
85    if meta.len() > cap as u64 {
86        return Err(std::io::Error::other(format!(
87            "file too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
88             Increase the limit or use a line-range read: mode=\"lines:1-100\"",
89            meta.len(),
90            cap
91        )));
92    }
93
94    use std::io::Read;
95    let mut bytes = Vec::with_capacity(meta.len() as usize);
96    std::io::BufReader::new(file).read_to_end(&mut bytes)?;
97    match String::from_utf8(bytes) {
98        Ok(s) => Ok(s),
99        Err(e) => Ok(String::from_utf8_lossy(e.as_bytes()).into_owned()),
100    }
101}
102
103/// Opens a file, retrying once after a brief pause on NotFound.
104/// Works around overlay/FUSE stat-cache races in container runtimes (Docker, Codex).
105fn open_with_retry(path: &str) -> Result<std::fs::File, std::io::Error> {
106    match std::fs::File::open(path) {
107        Ok(f) => Ok(f),
108        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
109            std::thread::sleep(std::time::Duration::from_millis(50));
110            std::fs::File::open(path)
111        }
112        Err(e) => Err(e),
113    }
114}
115
116/// Reads a file through the cache and applies the requested compression mode.
117pub fn handle(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
118    handle_with_options(cache, path, mode, false, crp_mode, None)
119}
120
121/// Like `handle`, but invalidates the cache first to force a fresh disk read.
122pub fn handle_fresh(cache: &mut SessionCache, path: &str, mode: &str, crp_mode: CrpMode) -> String {
123    handle_with_options(cache, path, mode, true, crp_mode, None)
124}
125
126/// Reads a file with task-aware filtering to prioritize task-relevant content.
127pub fn handle_with_task(
128    cache: &mut SessionCache,
129    path: &str,
130    mode: &str,
131    crp_mode: CrpMode,
132    task: Option<&str>,
133) -> String {
134    handle_with_options(cache, path, mode, false, crp_mode, task)
135}
136
137/// Like `handle_with_task`, also returns the resolved mode name and pre-counted tokens.
138pub fn handle_with_task_resolved(
139    cache: &mut SessionCache,
140    path: &str,
141    mode: &str,
142    crp_mode: CrpMode,
143    task: Option<&str>,
144) -> ReadOutput {
145    handle_with_options_resolved(cache, path, mode, false, crp_mode, task)
146}
147
148/// Fresh read with task-aware filtering (invalidates cache first).
149pub fn handle_fresh_with_task(
150    cache: &mut SessionCache,
151    path: &str,
152    mode: &str,
153    crp_mode: CrpMode,
154    task: Option<&str>,
155) -> String {
156    handle_with_options(cache, path, mode, true, crp_mode, task)
157}
158
159/// Fresh read with task-aware filtering, also returns the resolved mode name and pre-counted tokens.
160pub fn handle_fresh_with_task_resolved(
161    cache: &mut SessionCache,
162    path: &str,
163    mode: &str,
164    crp_mode: CrpMode,
165    task: Option<&str>,
166) -> ReadOutput {
167    handle_with_options_resolved(cache, path, mode, true, crp_mode, task)
168}
169
170fn handle_with_options(
171    cache: &mut SessionCache,
172    path: &str,
173    mode: &str,
174    fresh: bool,
175    crp_mode: CrpMode,
176    task: Option<&str>,
177) -> String {
178    handle_with_options_resolved(cache, path, mode, fresh, crp_mode, task).content
179}
180
181/// Detects if the current execution context is a subagent (forked agent).
182/// Subagents inherit stale parent caches, so force-fresh prevents VERIFY FAIL.
183fn is_subagent_context() -> bool {
184    static IS_SUBAGENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
185    *IS_SUBAGENT.get_or_init(|| {
186        if std::env::var("LEAN_CTX_FORCE_FRESH").is_ok_and(|v| v == "1" || v == "true") {
187            return true;
188        }
189        std::env::var("CURSOR_TASK_ID").is_ok_and(|v| !v.is_empty())
190    })
191}
192
193fn handle_with_options_resolved(
194    cache: &mut SessionCache,
195    path: &str,
196    mode: &str,
197    fresh: bool,
198    crp_mode: CrpMode,
199    task: Option<&str>,
200) -> ReadOutput {
201    let effective_fresh = fresh || is_subagent_context();
202
203    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
204        bt.next_seq();
205    }
206    let mut result = handle_with_options_inner(cache, path, mode, effective_fresh, crp_mode, task);
207
208    if let Some(entry) = cache.get_mut(path) {
209        entry.last_mode.clone_from(&result.resolved_mode);
210    }
211
212    let dedup_allowed = matches!(
213        result.resolved_mode.as_str(),
214        "map" | "signatures" | "aggressive" | "entropy" | "task"
215    );
216    if dedup_allowed {
217        if let Some(deduped) = cache.apply_dedup(path, &result.content) {
218            let new_tokens = count_tokens(&deduped);
219            if new_tokens < result.output_tokens {
220                result.content = deduped;
221                result.output_tokens = new_tokens;
222            }
223        }
224    }
225
226    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
227        let original_tokens = cache.get(path).map_or(0, |e| e.original_tokens);
228        bt.record_read(
229            path,
230            &result.resolved_mode,
231            result.output_tokens,
232            original_tokens,
233        );
234    }
235
236    result
237}
238
239fn handle_with_options_inner(
240    cache: &mut SessionCache,
241    path: &str,
242    mode: &str,
243    fresh: bool,
244    crp_mode: CrpMode,
245    task: Option<&str>,
246) -> ReadOutput {
247    let file_ref = cache.get_file_ref(path);
248    let short = protocol::shorten_path(path);
249    let ext = Path::new(path)
250        .extension()
251        .and_then(|e| e.to_str())
252        .unwrap_or("");
253
254    if fresh {
255        if mode == "diff" {
256            let warning = "[warning] fresh+diff is redundant — fresh invalidates cache, no diff possible. Use mode=full with fresh=true instead.";
257            return ReadOutput {
258                content: warning.to_string(),
259                resolved_mode: "diff".into(),
260                output_tokens: count_tokens(warning),
261            };
262        }
263        cache.invalidate(path);
264    }
265
266    if mode == "diff" {
267        let (out, _) = handle_diff(cache, path, &file_ref);
268        let out = crate::core::redaction::redact_text_if_enabled(&out);
269        let sent = count_tokens(&out);
270        return ReadOutput {
271            content: out,
272            resolved_mode: "diff".into(),
273            output_tokens: sent,
274        };
275    }
276
277    if mode != "full" {
278        if let Some(existing) = cache.get(path) {
279            let stale = crate::core::cache::is_cache_entry_stale(path, existing.stored_mtime);
280            if stale {
281                cache.invalidate(path);
282            }
283        }
284    }
285
286    if let Some(existing) = cache.get(path) {
287        if mode == "full" {
288            let (out, _) = handle_full_with_auto_delta(cache, path, &file_ref, &short, ext, task);
289            let out = crate::core::redaction::redact_text_if_enabled(&out);
290            let sent = count_tokens(&out);
291            return ReadOutput {
292                content: out,
293                resolved_mode: "full".into(),
294                output_tokens: sent,
295            };
296        }
297        let content = existing.content();
298        let original_tokens = existing.original_tokens;
299        let resolved_mode = if mode == "auto" {
300            resolve_auto_mode(path, original_tokens, task)
301        } else {
302            mode.to_string()
303        };
304        if is_cacheable_mode(&resolved_mode) {
305            let cache_key = compressed_cache_key(&resolved_mode, crp_mode);
306            if let Some(cached_output) = cache.get_compressed(path, &cache_key) {
307                let out = crate::core::redaction::redact_text_if_enabled(cached_output);
308                let sent = count_tokens(&out);
309                return ReadOutput {
310                    content: out,
311                    resolved_mode,
312                    output_tokens: sent,
313                };
314            }
315        }
316        let (out, _) = process_mode(
317            &content,
318            &resolved_mode,
319            &file_ref,
320            &short,
321            ext,
322            original_tokens,
323            crp_mode,
324            path,
325            task,
326        );
327        if is_cacheable_mode(&resolved_mode) {
328            let cache_key = compressed_cache_key(&resolved_mode, crp_mode);
329            cache.set_compressed(path, &cache_key, out.clone());
330        }
331        let out = crate::core::redaction::redact_text_if_enabled(&out);
332        let sent = count_tokens(&out);
333        return ReadOutput {
334            content: out,
335            resolved_mode,
336            output_tokens: sent,
337        };
338    }
339
340    let content = match read_file_lossy(path) {
341        Ok(c) => c,
342        Err(e) => {
343            let msg = format!("ERROR: {e}");
344            let tokens = count_tokens(&msg);
345            return ReadOutput {
346                content: msg,
347                resolved_mode: "error".into(),
348                output_tokens: tokens,
349            };
350        }
351    };
352
353    let hints = crate::core::profiles::active_profile().output_hints;
354    let similar_hint = if hints.semantic_hint() {
355        find_similar_and_update_semantic_index(path, &content)
356    } else {
357        None
358    };
359    let graph_hint = if hints.related_hint() {
360        build_graph_related_hint(path)
361    } else {
362        None
363    };
364
365    let store_result = cache.store(path, &content);
366
367    if mode == "full" {
368        cache.mark_full_delivered(path);
369        let (mut output, _) = format_full_output(
370            &file_ref,
371            &short,
372            ext,
373            &content,
374            store_result.original_tokens,
375            store_result.line_count,
376            task,
377        );
378        if let Some(hint) = &graph_hint {
379            output.push_str(&format!("\n{hint}"));
380        }
381        if let Some(hint) = similar_hint {
382            output.push_str(&format!("\n{hint}"));
383        }
384        let output = crate::core::redaction::redact_text_if_enabled(&output);
385        let sent = count_tokens(&output);
386        return ReadOutput {
387            content: output,
388            resolved_mode: "full".into(),
389            output_tokens: sent,
390        };
391    }
392
393    let resolved_mode = if mode == "auto" {
394        resolve_auto_mode(path, store_result.original_tokens, task)
395    } else {
396        mode.to_string()
397    };
398
399    let (mut output, _sent) = process_mode(
400        &content,
401        &resolved_mode,
402        &file_ref,
403        &short,
404        ext,
405        store_result.original_tokens,
406        crp_mode,
407        path,
408        task,
409    );
410    if let Some(hint) = &graph_hint {
411        output.push_str(&format!("\n{hint}"));
412    }
413    if let Some(hint) = similar_hint {
414        output.push_str(&format!("\n{hint}"));
415    }
416    if is_cacheable_mode(&resolved_mode) {
417        let cache_key = compressed_cache_key(&resolved_mode, crp_mode);
418        cache.set_compressed(path, &cache_key, output.clone());
419    }
420    let output = crate::core::redaction::redact_text_if_enabled(&output);
421    let final_tokens = count_tokens(&output);
422    ReadOutput {
423        content: output,
424        resolved_mode,
425        output_tokens: final_tokens,
426    }
427}
428
429pub fn is_instruction_file(path: &str) -> bool {
430    let lower = path.to_lowercase();
431    let filename = std::path::Path::new(&lower)
432        .file_name()
433        .and_then(|f| f.to_str())
434        .unwrap_or("");
435
436    matches!(
437        filename,
438        "skill.md"
439            | "agents.md"
440            | "rules.md"
441            | ".cursorrules"
442            | ".clinerules"
443            | "lean-ctx.md"
444            | "lean-ctx.mdc"
445    ) || lower.contains("/skills/")
446        || lower.contains("/.cursor/rules/")
447        || lower.contains("/.claude/rules/")
448        || lower.contains("/agents.md")
449}
450
451fn resolve_auto_mode(file_path: &str, original_tokens: usize, task: Option<&str>) -> String {
452    if is_instruction_file(file_path) {
453        return "full".to_string();
454    }
455
456    if let Ok(bt) = crate::core::bounce_tracker::global().lock() {
457        if bt.should_force_full(file_path) {
458            return "full".to_string();
459        }
460    }
461
462    let intent_query = task.unwrap_or("read");
463    let route = crate::core::intent_router::route_v1(intent_query);
464    let intent_mode = &route.decision.effective_read_mode;
465    if intent_mode != "auto" && intent_mode != "reference" {
466        return intent_mode.clone();
467    }
468
469    // Priority 2: FileSignature-based predictor
470    let sig = crate::core::mode_predictor::FileSignature::from_path(file_path, original_tokens);
471    let predictor = crate::core::mode_predictor::ModePredictor::new();
472    let mut predicted = predictor
473        .predict_best_mode(&sig)
474        .unwrap_or_else(|| "full".to_string());
475    if predicted == "auto" {
476        predicted = "full".to_string();
477    }
478
479    // Priority 3: Bandit exploration when budget is tight
480    // SAFETY: Bandit NEVER overrides "full" — full is sacred (byte-accurate content needed for edits)
481    if predicted != "full" {
482        if let Some(project_root) =
483            crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
484        {
485            let ext = std::path::Path::new(file_path)
486                .extension()
487                .and_then(|e| e.to_str())
488                .unwrap_or("");
489            let bucket = match original_tokens {
490                0..=2000 => "sm",
491                2001..=10000 => "md",
492                10001..=50000 => "lg",
493                _ => "xl",
494            };
495            let bandit_key = format!("{ext}_{bucket}");
496            let mut store = crate::core::bandit::BanditStore::load(&project_root);
497            let bandit = store.get_or_create(&bandit_key);
498            let arm = bandit.select_arm();
499            if arm.budget_ratio < 0.25 && original_tokens > 2000 {
500                predicted = "aggressive".to_string();
501            }
502        }
503    }
504
505    // Priority 4: Adaptive mode policy
506    let policy = crate::core::adaptive_mode_policy::AdaptiveModePolicyStore::load();
507    let chosen = policy.choose_auto_mode(task, &predicted);
508
509    if original_tokens > 2000 {
510        if predicted == "map" || predicted == "signatures" {
511            if chosen != "map" && chosen != "signatures" {
512                return predicted;
513            }
514        } else if chosen == "full" && predicted != "full" {
515            return predicted;
516        }
517    }
518
519    chosen
520}
521
522fn find_similar_and_update_semantic_index(path: &str, content: &str) -> Option<String> {
523    const MAX_CONTENT_BYTES_FOR_SEMANTIC: usize = 32_768;
524
525    if content.len() > MAX_CONTENT_BYTES_FOR_SEMANTIC {
526        return None;
527    }
528
529    let cfg = crate::core::config::Config::load();
530    let profile = crate::core::config::MemoryProfile::effective(&cfg);
531    if !profile.semantic_cache_enabled() {
532        return None;
533    }
534
535    let project_root = detect_project_root(path);
536    let session_id = format!("{}", std::process::id());
537    let mut index = crate::core::semantic_cache::SemanticCacheIndex::load_or_create(&project_root);
538
539    let similar = index.find_similar(content, 0.7);
540    let relevant: Vec<_> = similar
541        .into_iter()
542        .filter(|(p, _)| p != path)
543        .take(3)
544        .collect();
545
546    index.add_file(path, content, &session_id);
547    let _ = index.save(&project_root);
548
549    if relevant.is_empty() {
550        return None;
551    }
552
553    let hints: Vec<String> = relevant
554        .iter()
555        .map(|(p, score)| format!("  {p} ({:.0}% similar)", score * 100.0))
556        .collect();
557
558    Some(format!(
559        "[semantic: {} similar file(s) in cache]\n{}",
560        relevant.len(),
561        hints.join("\n")
562    ))
563}
564
565fn detect_project_root(path: &str) -> String {
566    crate::core::protocol::detect_project_root_or_cwd(path)
567}
568
569fn build_graph_related_hint(path: &str) -> Option<String> {
570    let project_root = detect_project_root(path);
571    crate::core::graph_context::build_related_hint(path, &project_root, 5)
572}
573
574const AUTO_DELTA_THRESHOLD: f64 = 0.6;
575
576/// Re-reads from disk; if content changed and delta is compact, sends auto-delta.
577fn handle_full_with_auto_delta(
578    cache: &mut SessionCache,
579    path: &str,
580    file_ref: &str,
581    short: &str,
582    ext: &str,
583    task: Option<&str>,
584) -> (String, usize) {
585    let Ok(disk_content) = read_file_lossy(path) else {
586        cache.record_cache_hit(path);
587        if let Some(existing) = cache.get(path) {
588            if !crate::core::protocol::meta_visible() {
589                let cached = existing.content();
590                return format_full_output(
591                    file_ref,
592                    short,
593                    ext,
594                    &cached,
595                    existing.original_tokens,
596                    existing.line_count,
597                    task,
598                );
599            }
600            let out = format!(
601                "[using cached version — file read failed]\n{file_ref}={short} cached {}t {}L",
602                existing.read_count, existing.line_count
603            );
604            let sent = count_tokens(&out);
605            return (out, sent);
606        }
607        let out = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
608            format!("[file read failed and no cached version available] {file_ref}={short}")
609        } else {
610            format!("[file read failed and no cached version available] {short}")
611        };
612        let sent = count_tokens(&out);
613        return (out, sent);
614    };
615
616    let old_content = cache
617        .get(path)
618        .map(crate::core::cache::CacheEntry::content)
619        .unwrap_or_default();
620    let store_result = cache.store(path, &disk_content);
621
622    if store_result.was_hit {
623        if store_result.full_content_delivered {
624            let out = if crate::core::protocol::meta_visible() {
625                format!(
626                    "{file_ref}={short} cached {}t {}L\nFile content unchanged since last read (same hash). Already in your context window.",
627                    store_result.read_count, store_result.line_count
628                )
629            } else {
630                format!(
631                    "{file_ref}={short} [unchanged, {}L, use cached context]",
632                    store_result.line_count
633                )
634            };
635            let sent = count_tokens(&out);
636            return (out, sent);
637        }
638        cache.mark_full_delivered(path);
639        return format_full_output(
640            file_ref,
641            short,
642            ext,
643            &disk_content,
644            store_result.original_tokens,
645            store_result.line_count,
646            task,
647        );
648    }
649
650    let diff = compressor::diff_content(&old_content, &disk_content);
651    let diff_tokens = count_tokens(&diff);
652    let full_tokens = store_result.original_tokens;
653
654    if full_tokens > 0 && (diff_tokens as f64) < (full_tokens as f64 * AUTO_DELTA_THRESHOLD) {
655        let savings = protocol::format_savings(full_tokens, diff_tokens);
656        let head = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
657            format!("{file_ref}={short}")
658        } else {
659            short.to_string()
660        };
661        let out = format!(
662            "{head} [auto-delta] ∆{}L\n{diff}\n{savings}",
663            disk_content.lines().count()
664        );
665        return (out, diff_tokens);
666    }
667
668    format_full_output(
669        file_ref,
670        short,
671        ext,
672        &disk_content,
673        store_result.original_tokens,
674        store_result.line_count,
675        task,
676    )
677}
678
679fn format_full_output(
680    file_ref: &str,
681    short: &str,
682    ext: &str,
683    content: &str,
684    original_tokens: usize,
685    line_count: usize,
686    _task: Option<&str>,
687) -> (String, usize) {
688    let tokens = original_tokens;
689    let metadata = build_header(file_ref, short, ext, content, line_count, true);
690
691    let output = format!("{metadata}\n{content}");
692    let sent = count_tokens(&output);
693    (protocol::append_savings(&output, tokens, sent), sent)
694}
695
696fn build_header(
697    file_ref: &str,
698    short: &str,
699    ext: &str,
700    content: &str,
701    line_count: usize,
702    include_deps: bool,
703) -> String {
704    let mut header = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
705        format!("{file_ref}={short} {line_count}L")
706    } else {
707        format!("{short} {line_count}L")
708    };
709
710    if include_deps {
711        let dep_info = deps::extract_deps(content, ext);
712        if !dep_info.imports.is_empty() {
713            let imports_str: Vec<&str> = dep_info
714                .imports
715                .iter()
716                .take(8)
717                .map(std::string::String::as_str)
718                .collect();
719            header.push_str(&format!("\n deps {}", imports_str.join(",")));
720        }
721        if !dep_info.exports.is_empty() {
722            let exports_str: Vec<&str> = dep_info
723                .exports
724                .iter()
725                .take(8)
726                .map(std::string::String::as_str)
727                .collect();
728            header.push_str(&format!("\n exports {}", exports_str.join(",")));
729        }
730    }
731
732    header
733}
734
735#[allow(clippy::too_many_arguments)]
736fn process_mode(
737    content: &str,
738    mode: &str,
739    file_ref: &str,
740    short: &str,
741    ext: &str,
742    original_tokens: usize,
743    crp_mode: CrpMode,
744    file_path: &str,
745    task: Option<&str>,
746) -> (String, usize) {
747    let line_count = content.lines().count();
748
749    match mode {
750        "auto" => {
751            let chosen = resolve_auto_mode(file_path, original_tokens, task);
752            process_mode(
753                content,
754                &chosen,
755                file_ref,
756                short,
757                ext,
758                original_tokens,
759                crp_mode,
760                file_path,
761                task,
762            )
763        }
764        "full" => format_full_output(
765            file_ref,
766            short,
767            ext,
768            content,
769            original_tokens,
770            line_count,
771            task,
772        ),
773        "signatures" => {
774            let sigs = signatures::extract_signatures(content, ext);
775            let dep_info = deps::extract_deps(content, ext);
776
777            let mut output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
778                format!("{file_ref}={short} {line_count}L")
779            } else {
780                format!("{short} {line_count}L")
781            };
782            if !dep_info.imports.is_empty() {
783                let imports_str: Vec<&str> = dep_info
784                    .imports
785                    .iter()
786                    .take(8)
787                    .map(std::string::String::as_str)
788                    .collect();
789                output.push_str(&format!("\n deps {}", imports_str.join(",")));
790            }
791            for sig in &sigs {
792                output.push('\n');
793                if crp_mode.is_tdd() {
794                    output.push_str(&sig.to_tdd());
795                } else {
796                    output.push_str(&sig.to_compact());
797                }
798            }
799            let sent = count_tokens(&output);
800            (
801                append_compressed_hint(
802                    &protocol::append_savings(&output, original_tokens, sent),
803                    file_path,
804                ),
805                sent,
806            )
807        }
808        "map" => {
809            if ext == "php" {
810                if let Some(php_map) = crate::core::patterns::php::compress_php_map(content, short)
811                {
812                    let output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
813                        format!("{file_ref}={short} {line_count}L\n{php_map}")
814                    } else {
815                        format!("{short} {line_count}L\n{php_map}")
816                    };
817                    let sent = count_tokens(&output);
818                    let output = protocol::append_savings(&output, original_tokens, sent);
819                    return (append_compressed_hint(&output, file_path), sent);
820                }
821            }
822
823            let sigs = signatures::extract_signatures(content, ext);
824            let dep_info = deps::extract_deps(content, ext);
825
826            let mut output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
827                format!("{file_ref}={short} {line_count}L")
828            } else {
829                format!("{short} {line_count}L")
830            };
831
832            if !dep_info.imports.is_empty() {
833                output.push_str("\n  deps: ");
834                output.push_str(&dep_info.imports.join(", "));
835            }
836
837            if !dep_info.exports.is_empty() {
838                output.push_str("\n  exports: ");
839                output.push_str(&dep_info.exports.join(", "));
840            }
841
842            let key_sigs: Vec<&signatures::Signature> = sigs
843                .iter()
844                .filter(|s| s.is_exported || s.indent == 0)
845                .collect();
846
847            if !key_sigs.is_empty() {
848                output.push_str("\n  API:");
849                for sig in &key_sigs {
850                    output.push_str("\n    ");
851                    if crp_mode.is_tdd() {
852                        output.push_str(&sig.to_tdd());
853                    } else {
854                        output.push_str(&sig.to_compact());
855                    }
856                }
857            }
858
859            let sent = count_tokens(&output);
860            (
861                append_compressed_hint(
862                    &protocol::append_savings(&output, original_tokens, sent),
863                    file_path,
864                ),
865                sent,
866            )
867        }
868        "aggressive" => {
869            #[cfg(feature = "tree-sitter")]
870            let ast_pruned = crate::core::signatures_ts::ast_prune(content, ext);
871            #[cfg(not(feature = "tree-sitter"))]
872            let ast_pruned: Option<String> = None;
873
874            let base = ast_pruned.as_deref().unwrap_or(content);
875
876            let session_intent = crate::core::session::SessionState::load_latest()
877                .and_then(|s| s.active_structured_intent);
878            let raw = if let Some(ref intent) = session_intent {
879                compressor::task_aware_compress(base, Some(ext), intent)
880            } else {
881                compressor::aggressive_compress(base, Some(ext))
882            };
883            let compressed = compressor::safeguard_ratio(content, &raw);
884            let header = build_header(file_ref, short, ext, content, line_count, true);
885
886            let mut sym = SymbolMap::new();
887            let idents = symbol_map::extract_identifiers(&compressed, ext);
888            for ident in &idents {
889                sym.register(ident);
890            }
891
892            if sym.len() >= 3 {
893                let sym_table = sym.format_table();
894                let sym_applied = sym.apply(&compressed);
895                let orig_tok = count_tokens(&compressed);
896                let comp_tok = count_tokens(&sym_applied) + count_tokens(&sym_table);
897                let net = orig_tok.saturating_sub(comp_tok);
898                if orig_tok > 0 && net * 100 / orig_tok >= 5 {
899                    let savings = protocol::format_savings(original_tokens, comp_tok);
900                    return (
901                        append_compressed_hint(
902                            &format!("{header}\n{sym_applied}{sym_table}\n{savings}"),
903                            file_path,
904                        ),
905                        comp_tok,
906                    );
907                }
908                let savings = protocol::format_savings(original_tokens, orig_tok);
909                return (
910                    append_compressed_hint(
911                        &format!("{header}\n{compressed}\n{savings}"),
912                        file_path,
913                    ),
914                    orig_tok,
915                );
916            }
917
918            let sent = count_tokens(&compressed);
919            let savings = protocol::format_savings(original_tokens, sent);
920            (
921                append_compressed_hint(&format!("{header}\n{compressed}\n{savings}"), file_path),
922                sent,
923            )
924        }
925        "entropy" => {
926            let result = entropy::entropy_compress_adaptive(content, file_path);
927            let avg_h = entropy::analyze_entropy(content).avg_entropy;
928            let header = build_header(file_ref, short, ext, content, line_count, false);
929            let techs = result.techniques.join(", ");
930            let output = format!("{header} H̄={avg_h:.1} [{techs}]\n{}", result.output);
931            let sent = count_tokens(&output);
932            let savings = protocol::format_savings(original_tokens, sent);
933            let compression_ratio = if original_tokens > 0 {
934                1.0 - (sent as f64 / original_tokens as f64)
935            } else {
936                0.0
937            };
938            crate::core::adaptive_thresholds::report_bandit_outcome(compression_ratio > 0.15);
939            (
940                append_compressed_hint(&format!("{output}\n{savings}"), file_path),
941                sent,
942            )
943        }
944        "task" => {
945            let task_str = task.unwrap_or("");
946            if task_str.is_empty() {
947                let header = build_header(file_ref, short, ext, content, line_count, true);
948                let out = format!("{header}\n{content}\n[task mode: no task set — returned full]");
949                let sent = count_tokens(&out);
950                return (out, sent);
951            }
952            let (_files, keywords) = crate::core::task_relevance::parse_task_hints(task_str);
953            if keywords.is_empty() {
954                let header = build_header(file_ref, short, ext, content, line_count, true);
955                let out = format!(
956                    "{header}\n{content}\n[task mode: no keywords extracted — returned full]"
957                );
958                let sent = count_tokens(&out);
959                return (out, sent);
960            }
961            let filtered =
962                crate::core::task_relevance::information_bottleneck_filter(content, &keywords, 0.3);
963            let filtered_lines = filtered.lines().count();
964            let header = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
965                format!("{file_ref}={short} {line_count}L [task-filtered: {line_count}→{filtered_lines}]")
966            } else {
967                format!("{short} {line_count}L [task-filtered: {line_count}→{filtered_lines}]")
968            };
969            let graph_ctx = if crate::core::profiles::active_profile()
970                .output_hints
971                .graph_context_block()
972            {
973                let project_root = detect_project_root(file_path);
974                crate::core::graph_context::build_graph_context(
975                    file_path,
976                    &project_root,
977                    Some(crate::core::graph_context::GraphContextOptions::default()),
978                )
979                .map(|c| crate::core::graph_context::format_graph_context(&c))
980                .unwrap_or_default()
981            } else {
982                String::new()
983            };
984
985            let sent = count_tokens(&filtered) + count_tokens(&header) + count_tokens(&graph_ctx);
986            let savings = protocol::format_savings(original_tokens, sent);
987            (
988                append_compressed_hint(
989                    &format!("{header}\n{filtered}{graph_ctx}\n{savings}"),
990                    file_path,
991                ),
992                sent,
993            )
994        }
995        "reference" => {
996            let tok = count_tokens(content);
997            let output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
998                format!("{file_ref}={short}: {line_count} lines, {tok} tok ({ext})")
999            } else {
1000                format!("{short}: {line_count} lines, {tok} tok ({ext})")
1001            };
1002            let sent = count_tokens(&output);
1003            let savings = protocol::format_savings(original_tokens, sent);
1004            (format!("{output}\n{savings}"), sent)
1005        }
1006        mode if mode.starts_with("lines:") => {
1007            let range_str = &mode[6..];
1008            let extracted = extract_line_range(content, range_str);
1009            let header = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1010                format!("{file_ref}={short} {line_count}L lines:{range_str}")
1011            } else {
1012                format!("{short} {line_count}L lines:{range_str}")
1013            };
1014            let sent = count_tokens(&extracted);
1015            let savings = protocol::format_savings(original_tokens, sent);
1016            (format!("{header}\n{extracted}\n{savings}"), sent)
1017        }
1018        unknown => {
1019            let header = build_header(file_ref, short, ext, content, line_count, true);
1020            let out = format!(
1021                "[WARNING: unknown mode '{unknown}', falling back to full]\n{header}\n{content}"
1022            );
1023            let sent = count_tokens(&out);
1024            (out, sent)
1025        }
1026    }
1027}
1028
1029fn extract_line_range(content: &str, range_str: &str) -> String {
1030    let lines: Vec<&str> = content.lines().collect();
1031    let total = lines.len();
1032    let mut selected = Vec::new();
1033
1034    for part in range_str.split(',') {
1035        let part = part.trim();
1036        if let Some((start_s, end_s)) = part.split_once('-') {
1037            let start = start_s.trim().parse::<usize>().unwrap_or(1).max(1);
1038            let end = end_s.trim().parse::<usize>().unwrap_or(total).min(total);
1039            for i in start..=end {
1040                if i >= 1 && i <= total {
1041                    selected.push(format!("{i:>4}| {}", lines[i - 1]));
1042                }
1043            }
1044        } else if let Ok(n) = part.parse::<usize>() {
1045            if n >= 1 && n <= total {
1046                selected.push(format!("{n:>4}| {}", lines[n - 1]));
1047            }
1048        }
1049    }
1050
1051    if selected.is_empty() {
1052        "No lines matched the range.".to_string()
1053    } else {
1054        selected.join("\n")
1055    }
1056}
1057
1058fn handle_diff(cache: &mut SessionCache, path: &str, file_ref: &str) -> (String, usize) {
1059    let short = protocol::shorten_path(path);
1060    let old_content = cache.get(path).map(crate::core::cache::CacheEntry::content);
1061
1062    let new_content = match read_file_lossy(path) {
1063        Ok(c) => c,
1064        Err(e) => {
1065            let msg = format!("ERROR: {e}");
1066            let tokens = count_tokens(&msg);
1067            return (msg, tokens);
1068        }
1069    };
1070
1071    let original_tokens = count_tokens(&new_content);
1072
1073    let diff_output = if let Some(old) = &old_content {
1074        compressor::diff_content(old, &new_content)
1075    } else {
1076        format!("[first read]\n{new_content}")
1077    };
1078
1079    cache.store(path, &new_content);
1080
1081    let sent = count_tokens(&diff_output);
1082    let savings = protocol::format_savings(original_tokens, sent);
1083    let head = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1084        format!("{file_ref}={short}")
1085    } else {
1086        short.clone()
1087    };
1088    (format!("{head} [diff]\n{diff_output}\n{savings}"), sent)
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093    use super::*;
1094    use std::time::Duration;
1095
1096    #[test]
1097    fn test_header_toon_format_no_brackets() {
1098        let _lock = crate::core::data_dir::test_env_lock();
1099        std::env::set_var("LEAN_CTX_META", "1");
1100        let content = "use std::io;\nfn main() {}\n";
1101        let header = build_header("F1", "main.rs", "rs", content, 2, false);
1102        assert!(!header.contains('['));
1103        assert!(!header.contains(']'));
1104        assert!(header.contains("F1=main.rs 2L"));
1105        std::env::remove_var("LEAN_CTX_META");
1106    }
1107
1108    #[test]
1109    fn test_header_toon_deps_indented() {
1110        let _lock = crate::core::data_dir::test_env_lock();
1111        std::env::set_var("LEAN_CTX_META", "1");
1112        let content = "use crate::core::cache;\nuse crate::tools;\npub fn main() {}\n";
1113        let header = build_header("F1", "main.rs", "rs", content, 3, true);
1114        if header.contains("deps") {
1115            assert!(
1116                header.contains("\n deps "),
1117                "deps should use indented TOON format"
1118            );
1119            assert!(
1120                !header.contains("deps:["),
1121                "deps should not use bracket format"
1122            );
1123        }
1124        std::env::remove_var("LEAN_CTX_META");
1125    }
1126
1127    #[test]
1128    fn test_header_toon_saves_tokens() {
1129        let _lock = crate::core::data_dir::test_env_lock();
1130        std::env::set_var("LEAN_CTX_META", "1");
1131        let content = "use crate::foo;\nuse crate::bar;\npub fn baz() {}\npub fn qux() {}\n";
1132        let old_header = "F1=main.rs [4L +] deps:[foo,bar] exports:[baz,qux]".to_string();
1133        let new_header = build_header("F1", "main.rs", "rs", content, 4, true);
1134        let old_tokens = count_tokens(&old_header);
1135        let new_tokens = count_tokens(&new_header);
1136        assert!(
1137            new_tokens <= old_tokens,
1138            "TOON header ({new_tokens} tok) should be <= old format ({old_tokens} tok)"
1139        );
1140        std::env::remove_var("LEAN_CTX_META");
1141    }
1142
1143    #[test]
1144    fn test_tdd_symbols_are_compact() {
1145        let symbols = [
1146            "⊕", "⊖", "∆", "→", "⇒", "✓", "✗", "⚠", "λ", "§", "∂", "τ", "ε",
1147        ];
1148        for sym in &symbols {
1149            let tok = count_tokens(sym);
1150            assert!(tok <= 2, "Symbol {sym} should be 1-2 tokens, got {tok}");
1151        }
1152    }
1153
1154    #[test]
1155    fn test_task_mode_filters_content() {
1156        let content = (0..200)
1157            .map(|i| {
1158                if i % 20 == 0 {
1159                    format!("fn validate_token(token: &str) -> bool {{ /* line {i} */ }}")
1160                } else {
1161                    format!("fn unrelated_helper_{i}(x: i32) -> i32 {{ x + {i} }}")
1162                }
1163            })
1164            .collect::<Vec<_>>()
1165            .join("\n");
1166        let full_tokens = count_tokens(&content);
1167        let task = Some("fix bug in validate_token");
1168        let (result, result_tokens) = process_mode(
1169            &content,
1170            "task",
1171            "F1",
1172            "test.rs",
1173            "rs",
1174            full_tokens,
1175            CrpMode::Off,
1176            "test.rs",
1177            task,
1178        );
1179        assert!(
1180            result_tokens < full_tokens,
1181            "task mode ({result_tokens} tok) should be less than full ({full_tokens} tok)"
1182        );
1183        assert!(
1184            result.contains("task-filtered"),
1185            "output should contain task-filtered marker"
1186        );
1187    }
1188
1189    #[test]
1190    fn test_task_mode_without_task_returns_full() {
1191        let content = "fn main() {}\nfn helper() {}\n";
1192        let tokens = count_tokens(content);
1193        let (result, _sent) = process_mode(
1194            content,
1195            "task",
1196            "F1",
1197            "test.rs",
1198            "rs",
1199            tokens,
1200            CrpMode::Off,
1201            "test.rs",
1202            None,
1203        );
1204        assert!(
1205            result.contains("no task set"),
1206            "should indicate no task: {result}"
1207        );
1208    }
1209
1210    #[test]
1211    fn test_reference_mode_one_line() {
1212        let content = "fn main() {}\nfn helper() {}\nfn other() {}\n";
1213        let tokens = count_tokens(content);
1214        let (result, _sent) = process_mode(
1215            content,
1216            "reference",
1217            "F1",
1218            "test.rs",
1219            "rs",
1220            tokens,
1221            CrpMode::Off,
1222            "test.rs",
1223            None,
1224        );
1225        let lines: Vec<&str> = result.lines().collect();
1226        assert!(
1227            lines.len() <= 3,
1228            "reference mode should be very compact, got {} lines",
1229            lines.len()
1230        );
1231        assert!(result.contains("lines"), "should contain line count");
1232        assert!(result.contains("tok"), "should contain token count");
1233    }
1234
1235    #[test]
1236    fn cached_lines_mode_invalidates_on_mtime_change() {
1237        let dir = tempfile::tempdir().unwrap();
1238        let path = dir.path().join("file.txt");
1239        let p = path.to_string_lossy().to_string();
1240
1241        std::fs::write(&path, "one\nsecond\n").unwrap();
1242        let mut cache = SessionCache::new();
1243
1244        let r1 = handle_with_task_resolved(&mut cache, &p, "lines:1-1", CrpMode::Off, None);
1245        let l1: Vec<&str> = r1.content.lines().collect();
1246        let got1 = l1.get(1).copied().unwrap_or_default().trim();
1247        let got1 = got1.split_once('|').map_or(got1, |(_, s)| s.trim());
1248        assert_eq!(got1, "one");
1249
1250        std::thread::sleep(Duration::from_secs(1));
1251        std::fs::write(&path, "two\nsecond\n").unwrap();
1252
1253        let r2 = handle_with_task_resolved(&mut cache, &p, "lines:1-1", CrpMode::Off, None);
1254        let l2: Vec<&str> = r2.content.lines().collect();
1255        let got2 = l2.get(1).copied().unwrap_or_default().trim();
1256        let got2 = got2.split_once('|').map_or(got2, |(_, s)| s.trim());
1257        assert_eq!(got2, "two");
1258    }
1259
1260    #[test]
1261    #[cfg_attr(tarpaulin, ignore)]
1262    fn benchmark_task_conditioned_compression() {
1263        // Keep this reasonably small so CI coverage instrumentation stays fast.
1264        let content = generate_benchmark_code(200);
1265        let full_tokens = count_tokens(&content);
1266        let task = Some("fix authentication in validate_token");
1267
1268        let (_full_output, full_tok) = process_mode(
1269            &content,
1270            "full",
1271            "F1",
1272            "server.rs",
1273            "rs",
1274            full_tokens,
1275            CrpMode::Off,
1276            "server.rs",
1277            task,
1278        );
1279        let (_task_output, task_tok) = process_mode(
1280            &content,
1281            "task",
1282            "F1",
1283            "server.rs",
1284            "rs",
1285            full_tokens,
1286            CrpMode::Off,
1287            "server.rs",
1288            task,
1289        );
1290        let (_sig_output, sig_tok) = process_mode(
1291            &content,
1292            "signatures",
1293            "F1",
1294            "server.rs",
1295            "rs",
1296            full_tokens,
1297            CrpMode::Off,
1298            "server.rs",
1299            task,
1300        );
1301        let (_ref_output, ref_tok) = process_mode(
1302            &content,
1303            "reference",
1304            "F1",
1305            "server.rs",
1306            "rs",
1307            full_tokens,
1308            CrpMode::Off,
1309            "server.rs",
1310            task,
1311        );
1312
1313        eprintln!("\n=== Task-Conditioned Compression Benchmark ===");
1314        eprintln!("Source: 200-line Rust file, task='fix authentication in validate_token'");
1315        eprintln!("  full:       {full_tok:>6} tokens (baseline)");
1316        eprintln!(
1317            "  task:       {task_tok:>6} tokens ({:.0}% savings)",
1318            (1.0 - task_tok as f64 / full_tok as f64) * 100.0
1319        );
1320        eprintln!(
1321            "  signatures: {sig_tok:>6} tokens ({:.0}% savings)",
1322            (1.0 - sig_tok as f64 / full_tok as f64) * 100.0
1323        );
1324        eprintln!(
1325            "  reference:  {ref_tok:>6} tokens ({:.0}% savings)",
1326            (1.0 - ref_tok as f64 / full_tok as f64) * 100.0
1327        );
1328        eprintln!("================================================\n");
1329
1330        assert!(task_tok < full_tok, "task mode should save tokens");
1331        assert!(sig_tok < full_tok, "signatures should save tokens");
1332        assert!(ref_tok < sig_tok, "reference should be most compact");
1333    }
1334
1335    fn generate_benchmark_code(lines: usize) -> String {
1336        let mut code = Vec::with_capacity(lines);
1337        code.push("use std::collections::HashMap;".to_string());
1338        code.push("use crate::core::auth;".to_string());
1339        code.push(String::new());
1340        code.push("pub struct Server {".to_string());
1341        code.push("    config: Config,".to_string());
1342        code.push("    cache: HashMap<String, String>,".to_string());
1343        code.push("}".to_string());
1344        code.push(String::new());
1345        code.push("impl Server {".to_string());
1346        code.push(
1347            "    pub fn validate_token(&self, token: &str) -> Result<Claims, AuthError> {"
1348                .to_string(),
1349        );
1350        code.push("        let decoded = auth::decode_jwt(token)?;".to_string());
1351        code.push("        if decoded.exp < chrono::Utc::now().timestamp() {".to_string());
1352        code.push("            return Err(AuthError::Expired);".to_string());
1353        code.push("        }".to_string());
1354        code.push("        Ok(decoded.claims)".to_string());
1355        code.push("    }".to_string());
1356        code.push(String::new());
1357
1358        let remaining = lines.saturating_sub(code.len());
1359        for i in 0..remaining {
1360            if i % 30 == 0 {
1361                code.push(format!(
1362                    "    pub fn handler_{i}(&self, req: Request) -> Response {{"
1363                ));
1364            } else if i % 30 == 29 {
1365                code.push("    }".to_string());
1366            } else {
1367                code.push(format!("        let val_{i} = self.cache.get(\"key_{i}\").unwrap_or(&\"default\".to_string());"));
1368            }
1369        }
1370        code.push("}".to_string());
1371        code.join("\n")
1372    }
1373
1374    #[test]
1375    fn instruction_file_detection() {
1376        assert!(is_instruction_file(
1377            "/home/user/.pi/agent/skills/committing-changes/SKILL.md"
1378        ));
1379        assert!(is_instruction_file("/workspace/.cursor/rules/lean-ctx.mdc"));
1380        assert!(is_instruction_file("/project/AGENTS.md"));
1381        assert!(is_instruction_file("/project/.cursorrules"));
1382        assert!(is_instruction_file("/home/user/.claude/rules/my-rule.md"));
1383        assert!(is_instruction_file("/skills/some-skill/README.md"));
1384
1385        assert!(!is_instruction_file("/project/src/main.rs"));
1386        assert!(!is_instruction_file("/project/config.json"));
1387        assert!(!is_instruction_file("/project/data/report.csv"));
1388    }
1389
1390    #[test]
1391    fn resolve_auto_mode_returns_full_for_instruction_files() {
1392        let mode = resolve_auto_mode(
1393            "/home/user/.pi/agent/skills/committing-changes/SKILL.md",
1394            5000,
1395            Some("read"),
1396        );
1397        assert_eq!(mode, "full", "SKILL.md must always be read in full");
1398
1399        let mode = resolve_auto_mode("/workspace/AGENTS.md", 3000, Some("read"));
1400        assert_eq!(mode, "full", "AGENTS.md must always be read in full");
1401
1402        let mode = resolve_auto_mode("/workspace/.cursorrules", 2000, None);
1403        assert_eq!(mode, "full", ".cursorrules must always be read in full");
1404    }
1405}