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