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
13pub struct ReadOutput {
16 pub content: String,
17 pub resolved_mode: String,
18 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
51pub 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
103fn 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
116pub 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
121pub 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
126pub 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
137pub 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
148pub 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
159pub 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
181fn 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 original_tokens = existing.original_tokens;
298 let content_opt = existing.content();
299 if let Some(content) = content_opt {
300 let resolved_mode = if mode == "auto" {
301 resolve_auto_mode(path, original_tokens, task)
302 } else {
303 mode.to_string()
304 };
305 if is_cacheable_mode(&resolved_mode) {
306 let cache_key = compressed_cache_key(&resolved_mode, crp_mode);
307 if let Some(cached_output) = cache.get_compressed(path, &cache_key) {
308 let out = crate::core::redaction::redact_text_if_enabled(cached_output);
309 let sent = count_tokens(&out);
310 return ReadOutput {
311 content: out,
312 resolved_mode,
313 output_tokens: sent,
314 };
315 }
316 }
317 let (out, _) = process_mode(
318 &content,
319 &resolved_mode,
320 &file_ref,
321 &short,
322 ext,
323 original_tokens,
324 crp_mode,
325 path,
326 task,
327 );
328 if is_cacheable_mode(&resolved_mode) {
329 let cache_key = compressed_cache_key(&resolved_mode, crp_mode);
330 cache.set_compressed(path, &cache_key, out.clone());
331 }
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,
337 output_tokens: sent,
338 };
339 }
340 cache.invalidate(path);
341 }
342
343 let content = match read_file_lossy(path) {
344 Ok(c) => c,
345 Err(e) => {
346 let msg = format!("ERROR: {e}");
347 let tokens = count_tokens(&msg);
348 return ReadOutput {
349 content: msg,
350 resolved_mode: "error".into(),
351 output_tokens: tokens,
352 };
353 }
354 };
355
356 let hints = crate::core::profiles::active_profile().output_hints;
357 let similar_hint = if hints.semantic_hint() {
358 find_similar_and_update_semantic_index(path, &content)
359 } else {
360 None
361 };
362 let graph_hint = if hints.related_hint() {
363 build_graph_related_hint(path)
364 } else {
365 None
366 };
367
368 let store_result = cache.store(path, &content);
369
370 if mode == "full" {
371 cache.mark_full_delivered(path);
372 let (mut output, _) = format_full_output(
373 &file_ref,
374 &short,
375 ext,
376 &content,
377 store_result.original_tokens,
378 store_result.line_count,
379 task,
380 );
381 if let Some(hint) = &graph_hint {
382 output.push_str(&format!("\n{hint}"));
383 }
384 if let Some(hint) = similar_hint {
385 output.push_str(&format!("\n{hint}"));
386 }
387 let output = crate::core::redaction::redact_text_if_enabled(&output);
388 let sent = count_tokens(&output);
389 return ReadOutput {
390 content: output,
391 resolved_mode: "full".into(),
392 output_tokens: sent,
393 };
394 }
395
396 let resolved_mode = if mode == "auto" {
397 resolve_auto_mode(path, store_result.original_tokens, task)
398 } else {
399 mode.to_string()
400 };
401
402 let (mut output, _sent) = process_mode(
403 &content,
404 &resolved_mode,
405 &file_ref,
406 &short,
407 ext,
408 store_result.original_tokens,
409 crp_mode,
410 path,
411 task,
412 );
413 if let Some(hint) = &graph_hint {
414 output.push_str(&format!("\n{hint}"));
415 }
416 if let Some(hint) = similar_hint {
417 output.push_str(&format!("\n{hint}"));
418 }
419 if is_cacheable_mode(&resolved_mode) {
420 let cache_key = compressed_cache_key(&resolved_mode, crp_mode);
421 cache.set_compressed(path, &cache_key, output.clone());
422 }
423 let output = crate::core::redaction::redact_text_if_enabled(&output);
424 let final_tokens = count_tokens(&output);
425 ReadOutput {
426 content: output,
427 resolved_mode,
428 output_tokens: final_tokens,
429 }
430}
431
432pub fn is_instruction_file(path: &str) -> bool {
433 let lower = path.to_lowercase();
434 let filename = std::path::Path::new(&lower)
435 .file_name()
436 .and_then(|f| f.to_str())
437 .unwrap_or("");
438
439 matches!(
440 filename,
441 "skill.md"
442 | "agents.md"
443 | "rules.md"
444 | ".cursorrules"
445 | ".clinerules"
446 | "lean-ctx.md"
447 | "lean-ctx.mdc"
448 ) || lower.contains("/skills/")
449 || lower.contains("/.cursor/rules/")
450 || lower.contains("/.claude/rules/")
451 || lower.contains("/agents.md")
452}
453
454fn resolve_auto_mode(file_path: &str, original_tokens: usize, task: Option<&str>) -> String {
455 if is_instruction_file(file_path) {
456 return "full".to_string();
457 }
458
459 if let Ok(bt) = crate::core::bounce_tracker::global().lock() {
460 if bt.should_force_full(file_path) {
461 return "full".to_string();
462 }
463 }
464
465 let intent_query = task.unwrap_or("read");
466 let route = crate::core::intent_router::route_v1(intent_query);
467 let intent_mode = &route.decision.effective_read_mode;
468 if intent_mode != "auto" && intent_mode != "reference" {
469 return intent_mode.clone();
470 }
471
472 let sig = crate::core::mode_predictor::FileSignature::from_path(file_path, original_tokens);
474 let predictor = crate::core::mode_predictor::ModePredictor::new();
475 let mut predicted = predictor
476 .predict_best_mode(&sig)
477 .unwrap_or_else(|| "full".to_string());
478 if predicted == "auto" {
479 predicted = "full".to_string();
480 }
481
482 if predicted != "full" {
485 if let Some(project_root) =
486 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
487 {
488 let ext = std::path::Path::new(file_path)
489 .extension()
490 .and_then(|e| e.to_str())
491 .unwrap_or("");
492 let bucket = match original_tokens {
493 0..=2000 => "sm",
494 2001..=10000 => "md",
495 10001..=50000 => "lg",
496 _ => "xl",
497 };
498 let bandit_key = format!("{ext}_{bucket}");
499 let mut store = crate::core::bandit::BanditStore::load(&project_root);
500 let bandit = store.get_or_create(&bandit_key);
501 let arm = bandit.select_arm();
502 if arm.budget_ratio < 0.25 && original_tokens > 2000 {
503 predicted = "aggressive".to_string();
504 }
505 }
506 }
507
508 let policy = crate::core::adaptive_mode_policy::AdaptiveModePolicyStore::load();
510 let chosen = policy.choose_auto_mode(task, &predicted);
511
512 if original_tokens > 2000 {
513 if predicted == "map" || predicted == "signatures" {
514 if chosen != "map" && chosen != "signatures" {
515 return predicted;
516 }
517 } else if chosen == "full" && predicted != "full" {
518 return predicted;
519 }
520 }
521
522 chosen
523}
524
525fn find_similar_and_update_semantic_index(path: &str, content: &str) -> Option<String> {
526 const MAX_CONTENT_BYTES_FOR_SEMANTIC: usize = 32_768;
527
528 if content.len() > MAX_CONTENT_BYTES_FOR_SEMANTIC {
529 return None;
530 }
531
532 let cfg = crate::core::config::Config::load();
533 let profile = crate::core::config::MemoryProfile::effective(&cfg);
534 if !profile.semantic_cache_enabled() {
535 return None;
536 }
537
538 let project_root = detect_project_root(path);
539 let session_id = format!("{}", std::process::id());
540 let mut index = crate::core::semantic_cache::SemanticCacheIndex::load_or_create(&project_root);
541
542 let similar = index.find_similar(content, 0.7);
543 let relevant: Vec<_> = similar
544 .into_iter()
545 .filter(|(p, _)| p != path)
546 .take(3)
547 .collect();
548
549 index.add_file(path, content, &session_id);
550 let _ = index.save(&project_root);
551
552 if relevant.is_empty() {
553 return None;
554 }
555
556 let hints: Vec<String> = relevant
557 .iter()
558 .map(|(p, score)| format!(" {p} ({:.0}% similar)", score * 100.0))
559 .collect();
560
561 Some(format!(
562 "[semantic: {} similar file(s) in cache]\n{}",
563 relevant.len(),
564 hints.join("\n")
565 ))
566}
567
568fn detect_project_root(path: &str) -> String {
569 crate::core::protocol::detect_project_root_or_cwd(path)
570}
571
572fn build_graph_related_hint(path: &str) -> Option<String> {
573 let project_root = detect_project_root(path);
574 crate::core::graph_context::build_related_hint(path, &project_root, 5)
575}
576
577const AUTO_DELTA_THRESHOLD: f64 = 0.6;
578
579fn handle_full_with_auto_delta(
581 cache: &mut SessionCache,
582 path: &str,
583 file_ref: &str,
584 short: &str,
585 ext: &str,
586 task: Option<&str>,
587) -> (String, usize) {
588 let Ok(disk_content) = read_file_lossy(path) else {
589 cache.record_cache_hit(path);
590 if let Some(existing) = cache.get(path) {
591 if !crate::core::protocol::meta_visible() {
592 if let Some(cached) = existing.content() {
593 return format_full_output(
594 file_ref,
595 short,
596 ext,
597 &cached,
598 existing.original_tokens,
599 existing.line_count,
600 task,
601 );
602 }
603 }
604 let out = format!(
605 "[using cached version — file read failed]\n{file_ref}={short} cached {}t {}L",
606 existing.read_count, existing.line_count
607 );
608 let sent = count_tokens(&out);
609 return (out, sent);
610 }
611 let out = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
612 format!("[file read failed and no cached version available] {file_ref}={short}")
613 } else {
614 format!("[file read failed and no cached version available] {short}")
615 };
616 let sent = count_tokens(&out);
617 return (out, sent);
618 };
619
620 let old_content = cache
621 .get(path)
622 .and_then(crate::core::cache::CacheEntry::content)
623 .unwrap_or_default();
624 let store_result = cache.store(path, &disk_content);
625
626 if store_result.was_hit {
627 if store_result.full_content_delivered {
628 let out = if crate::core::protocol::meta_visible() {
629 format!(
630 "{file_ref}={short} cached {}t {}L\nFile content unchanged since last read (same hash). Already in your context window.",
631 store_result.read_count, store_result.line_count
632 )
633 } else {
634 format!(
635 "{file_ref}={short} [unchanged, {}L, use cached context]",
636 store_result.line_count
637 )
638 };
639 let sent = count_tokens(&out);
640 return (out, sent);
641 }
642 cache.mark_full_delivered(path);
643 return format_full_output(
644 file_ref,
645 short,
646 ext,
647 &disk_content,
648 store_result.original_tokens,
649 store_result.line_count,
650 task,
651 );
652 }
653
654 let diff = compressor::diff_content(&old_content, &disk_content);
655 let diff_tokens = count_tokens(&diff);
656 let full_tokens = store_result.original_tokens;
657
658 if full_tokens > 0 && (diff_tokens as f64) < (full_tokens as f64 * AUTO_DELTA_THRESHOLD) {
659 let savings = protocol::format_savings(full_tokens, diff_tokens);
660 let head = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
661 format!("{file_ref}={short}")
662 } else {
663 short.to_string()
664 };
665 let out = format!(
666 "{head} [auto-delta] ∆{}L\n{diff}\n{savings}",
667 disk_content.lines().count()
668 );
669 return (out, diff_tokens);
670 }
671
672 format_full_output(
673 file_ref,
674 short,
675 ext,
676 &disk_content,
677 store_result.original_tokens,
678 store_result.line_count,
679 task,
680 )
681}
682
683fn format_full_output(
684 file_ref: &str,
685 short: &str,
686 ext: &str,
687 content: &str,
688 original_tokens: usize,
689 line_count: usize,
690 _task: Option<&str>,
691) -> (String, usize) {
692 let tokens = original_tokens;
693 let metadata = build_header(file_ref, short, ext, content, line_count, true);
694
695 let output = format!("{metadata}\n{content}");
696 let sent = count_tokens(&output);
697 (protocol::append_savings(&output, tokens, sent), sent)
698}
699
700fn build_header(
701 file_ref: &str,
702 short: &str,
703 ext: &str,
704 content: &str,
705 line_count: usize,
706 include_deps: bool,
707) -> String {
708 let mut header = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
709 format!("{file_ref}={short} {line_count}L")
710 } else {
711 format!("{short} {line_count}L")
712 };
713
714 if include_deps {
715 let dep_info = deps::extract_deps(content, ext);
716 if !dep_info.imports.is_empty() {
717 let imports_str: Vec<&str> = dep_info
718 .imports
719 .iter()
720 .take(8)
721 .map(std::string::String::as_str)
722 .collect();
723 header.push_str(&format!("\n deps {}", imports_str.join(",")));
724 }
725 if !dep_info.exports.is_empty() {
726 let exports_str: Vec<&str> = dep_info
727 .exports
728 .iter()
729 .take(8)
730 .map(std::string::String::as_str)
731 .collect();
732 header.push_str(&format!("\n exports {}", exports_str.join(",")));
733 }
734 }
735
736 header
737}
738
739#[allow(clippy::too_many_arguments)]
740fn process_mode(
741 content: &str,
742 mode: &str,
743 file_ref: &str,
744 short: &str,
745 ext: &str,
746 original_tokens: usize,
747 crp_mode: CrpMode,
748 file_path: &str,
749 task: Option<&str>,
750) -> (String, usize) {
751 let line_count = content.lines().count();
752
753 match mode {
754 "auto" => {
755 let chosen = resolve_auto_mode(file_path, original_tokens, task);
756 process_mode(
757 content,
758 &chosen,
759 file_ref,
760 short,
761 ext,
762 original_tokens,
763 crp_mode,
764 file_path,
765 task,
766 )
767 }
768 "full" => format_full_output(
769 file_ref,
770 short,
771 ext,
772 content,
773 original_tokens,
774 line_count,
775 task,
776 ),
777 "signatures" => {
778 let sigs = signatures::extract_signatures(content, ext);
779 let dep_info = deps::extract_deps(content, ext);
780
781 let mut output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
782 format!("{file_ref}={short} {line_count}L")
783 } else {
784 format!("{short} {line_count}L")
785 };
786 if !dep_info.imports.is_empty() {
787 let imports_str: Vec<&str> = dep_info
788 .imports
789 .iter()
790 .take(8)
791 .map(std::string::String::as_str)
792 .collect();
793 output.push_str(&format!("\n deps {}", imports_str.join(",")));
794 }
795 for sig in &sigs {
796 output.push('\n');
797 if crp_mode.is_tdd() {
798 output.push_str(&sig.to_tdd());
799 } else {
800 output.push_str(&sig.to_compact());
801 }
802 }
803 let sent = count_tokens(&output);
804 (
805 append_compressed_hint(
806 &protocol::append_savings(&output, original_tokens, sent),
807 file_path,
808 ),
809 sent,
810 )
811 }
812 "map" => {
813 if ext == "php" {
814 if let Some(php_map) = crate::core::patterns::php::compress_php_map(content, short)
815 {
816 let output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
817 format!("{file_ref}={short} {line_count}L\n{php_map}")
818 } else {
819 format!("{short} {line_count}L\n{php_map}")
820 };
821 let sent = count_tokens(&output);
822 let output = protocol::append_savings(&output, original_tokens, sent);
823 return (append_compressed_hint(&output, file_path), sent);
824 }
825 }
826
827 let sigs = signatures::extract_signatures(content, ext);
828 let dep_info = deps::extract_deps(content, ext);
829
830 let mut output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
831 format!("{file_ref}={short} {line_count}L")
832 } else {
833 format!("{short} {line_count}L")
834 };
835
836 if !dep_info.imports.is_empty() {
837 output.push_str("\n deps: ");
838 output.push_str(&dep_info.imports.join(", "));
839 }
840
841 if !dep_info.exports.is_empty() {
842 output.push_str("\n exports: ");
843 output.push_str(&dep_info.exports.join(", "));
844 }
845
846 let key_sigs: Vec<&signatures::Signature> = sigs
847 .iter()
848 .filter(|s| s.is_exported || s.indent == 0)
849 .collect();
850
851 if !key_sigs.is_empty() {
852 output.push_str("\n API:");
853 for sig in &key_sigs {
854 output.push_str("\n ");
855 if crp_mode.is_tdd() {
856 output.push_str(&sig.to_tdd());
857 } else {
858 output.push_str(&sig.to_compact());
859 }
860 }
861 }
862
863 let sent = count_tokens(&output);
864 (
865 append_compressed_hint(
866 &protocol::append_savings(&output, original_tokens, sent),
867 file_path,
868 ),
869 sent,
870 )
871 }
872 "aggressive" => {
873 #[cfg(feature = "tree-sitter")]
874 let ast_pruned = crate::core::signatures_ts::ast_prune(content, ext);
875 #[cfg(not(feature = "tree-sitter"))]
876 let ast_pruned: Option<String> = None;
877
878 let base = ast_pruned.as_deref().unwrap_or(content);
879
880 let session_intent = crate::core::session::SessionState::load_latest()
881 .and_then(|s| s.active_structured_intent);
882 let raw = if let Some(ref intent) = session_intent {
883 compressor::task_aware_compress(base, Some(ext), intent)
884 } else {
885 compressor::aggressive_compress(base, Some(ext))
886 };
887 let compressed = compressor::safeguard_ratio(content, &raw);
888 let header = build_header(file_ref, short, ext, content, line_count, true);
889
890 let mut sym = SymbolMap::new();
891 let idents = symbol_map::extract_identifiers(&compressed, ext);
892 for ident in &idents {
893 sym.register(ident);
894 }
895
896 if sym.len() >= 3 {
897 let sym_table = sym.format_table();
898 let sym_applied = sym.apply(&compressed);
899 let orig_tok = count_tokens(&compressed);
900 let comp_tok = count_tokens(&sym_applied) + count_tokens(&sym_table);
901 let net = orig_tok.saturating_sub(comp_tok);
902 if orig_tok > 0 && net * 100 / orig_tok >= 5 {
903 let savings = protocol::format_savings(original_tokens, comp_tok);
904 return (
905 append_compressed_hint(
906 &format!("{header}\n{sym_applied}{sym_table}\n{savings}"),
907 file_path,
908 ),
909 comp_tok,
910 );
911 }
912 let savings = protocol::format_savings(original_tokens, orig_tok);
913 return (
914 append_compressed_hint(
915 &format!("{header}\n{compressed}\n{savings}"),
916 file_path,
917 ),
918 orig_tok,
919 );
920 }
921
922 let sent = count_tokens(&compressed);
923 let savings = protocol::format_savings(original_tokens, sent);
924 (
925 append_compressed_hint(&format!("{header}\n{compressed}\n{savings}"), file_path),
926 sent,
927 )
928 }
929 "entropy" => {
930 let result = entropy::entropy_compress_adaptive(content, file_path);
931 let avg_h = entropy::analyze_entropy(content).avg_entropy;
932 let header = build_header(file_ref, short, ext, content, line_count, false);
933 let techs = result.techniques.join(", ");
934 let output = format!("{header} H̄={avg_h:.1} [{techs}]\n{}", result.output);
935 let sent = count_tokens(&output);
936 let savings = protocol::format_savings(original_tokens, sent);
937 let compression_ratio = if original_tokens > 0 {
938 1.0 - (sent as f64 / original_tokens as f64)
939 } else {
940 0.0
941 };
942 crate::core::adaptive_thresholds::report_bandit_outcome(compression_ratio > 0.15);
943 (
944 append_compressed_hint(&format!("{output}\n{savings}"), file_path),
945 sent,
946 )
947 }
948 "task" => {
949 let task_str = task.unwrap_or("");
950 if task_str.is_empty() {
951 let header = build_header(file_ref, short, ext, content, line_count, true);
952 let out = format!("{header}\n{content}\n[task mode: no task set — returned full]");
953 let sent = count_tokens(&out);
954 return (out, sent);
955 }
956 let (_files, keywords) = crate::core::task_relevance::parse_task_hints(task_str);
957 if keywords.is_empty() {
958 let header = build_header(file_ref, short, ext, content, line_count, true);
959 let out = format!(
960 "{header}\n{content}\n[task mode: no keywords extracted — returned full]"
961 );
962 let sent = count_tokens(&out);
963 return (out, sent);
964 }
965 let filtered =
966 crate::core::task_relevance::information_bottleneck_filter(content, &keywords, 0.3);
967 let filtered_lines = filtered.lines().count();
968 let header = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
969 format!("{file_ref}={short} {line_count}L [task-filtered: {line_count}→{filtered_lines}]")
970 } else {
971 format!("{short} {line_count}L [task-filtered: {line_count}→{filtered_lines}]")
972 };
973 let graph_ctx = if crate::core::profiles::active_profile()
974 .output_hints
975 .graph_context_block()
976 {
977 let project_root = detect_project_root(file_path);
978 crate::core::graph_context::build_graph_context(
979 file_path,
980 &project_root,
981 Some(crate::core::graph_context::GraphContextOptions::default()),
982 )
983 .map(|c| crate::core::graph_context::format_graph_context(&c))
984 .unwrap_or_default()
985 } else {
986 String::new()
987 };
988
989 let sent = count_tokens(&filtered) + count_tokens(&header) + count_tokens(&graph_ctx);
990 let savings = protocol::format_savings(original_tokens, sent);
991 (
992 append_compressed_hint(
993 &format!("{header}\n{filtered}{graph_ctx}\n{savings}"),
994 file_path,
995 ),
996 sent,
997 )
998 }
999 "reference" => {
1000 let tok = count_tokens(content);
1001 let output = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1002 format!("{file_ref}={short}: {line_count} lines, {tok} tok ({ext})")
1003 } else {
1004 format!("{short}: {line_count} lines, {tok} tok ({ext})")
1005 };
1006 let sent = count_tokens(&output);
1007 let savings = protocol::format_savings(original_tokens, sent);
1008 (format!("{output}\n{savings}"), sent)
1009 }
1010 mode if mode.starts_with("lines:") => {
1011 let range_str = &mode[6..];
1012 let extracted = extract_line_range(content, range_str);
1013 let header = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1014 format!("{file_ref}={short} {line_count}L lines:{range_str}")
1015 } else {
1016 format!("{short} {line_count}L lines:{range_str}")
1017 };
1018 let sent = count_tokens(&extracted);
1019 let savings = protocol::format_savings(original_tokens, sent);
1020 (format!("{header}\n{extracted}\n{savings}"), sent)
1021 }
1022 unknown => {
1023 let header = build_header(file_ref, short, ext, content, line_count, true);
1024 let out = format!(
1025 "[WARNING: unknown mode '{unknown}', falling back to full]\n{header}\n{content}"
1026 );
1027 let sent = count_tokens(&out);
1028 (out, sent)
1029 }
1030 }
1031}
1032
1033fn extract_line_range(content: &str, range_str: &str) -> String {
1034 let lines: Vec<&str> = content.lines().collect();
1035 let total = lines.len();
1036 let mut selected = Vec::new();
1037
1038 for part in range_str.split(',') {
1039 let part = part.trim();
1040 if let Some((start_s, end_s)) = part.split_once('-') {
1041 let start = start_s.trim().parse::<usize>().unwrap_or(1).max(1);
1042 let end = end_s.trim().parse::<usize>().unwrap_or(total).min(total);
1043 for i in start..=end {
1044 if i >= 1 && i <= total {
1045 selected.push(format!("{i:>4}| {}", lines[i - 1]));
1046 }
1047 }
1048 } else if let Ok(n) = part.parse::<usize>() {
1049 if n >= 1 && n <= total {
1050 selected.push(format!("{n:>4}| {}", lines[n - 1]));
1051 }
1052 }
1053 }
1054
1055 if selected.is_empty() {
1056 "No lines matched the range.".to_string()
1057 } else {
1058 selected.join("\n")
1059 }
1060}
1061
1062fn handle_diff(cache: &mut SessionCache, path: &str, file_ref: &str) -> (String, usize) {
1063 let short = protocol::shorten_path(path);
1064 let old_content = cache
1065 .get(path)
1066 .and_then(crate::core::cache::CacheEntry::content);
1067
1068 let new_content = match read_file_lossy(path) {
1069 Ok(c) => c,
1070 Err(e) => {
1071 let msg = format!("ERROR: {e}");
1072 let tokens = count_tokens(&msg);
1073 return (msg, tokens);
1074 }
1075 };
1076
1077 let original_tokens = count_tokens(&new_content);
1078
1079 let diff_output = if let Some(old) = &old_content {
1080 compressor::diff_content(old, &new_content)
1081 } else {
1082 format!("[first read]\n{new_content}")
1083 };
1084
1085 cache.store(path, &new_content);
1086
1087 let sent = count_tokens(&diff_output);
1088 let savings = protocol::format_savings(original_tokens, sent);
1089 let head = if crate::core::protocol::meta_visible() && !file_ref.is_empty() {
1090 format!("{file_ref}={short}")
1091 } else {
1092 short.clone()
1093 };
1094 (format!("{head} [diff]\n{diff_output}\n{savings}"), sent)
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099 use super::*;
1100 use std::time::Duration;
1101
1102 #[test]
1103 fn test_header_toon_format_no_brackets() {
1104 let _lock = crate::core::data_dir::test_env_lock();
1105 std::env::set_var("LEAN_CTX_META", "1");
1106 let content = "use std::io;\nfn main() {}\n";
1107 let header = build_header("F1", "main.rs", "rs", content, 2, false);
1108 assert!(!header.contains('['));
1109 assert!(!header.contains(']'));
1110 assert!(header.contains("F1=main.rs 2L"));
1111 std::env::remove_var("LEAN_CTX_META");
1112 }
1113
1114 #[test]
1115 fn test_header_toon_deps_indented() {
1116 let _lock = crate::core::data_dir::test_env_lock();
1117 std::env::set_var("LEAN_CTX_META", "1");
1118 let content = "use crate::core::cache;\nuse crate::tools;\npub fn main() {}\n";
1119 let header = build_header("F1", "main.rs", "rs", content, 3, true);
1120 if header.contains("deps") {
1121 assert!(
1122 header.contains("\n deps "),
1123 "deps should use indented TOON format"
1124 );
1125 assert!(
1126 !header.contains("deps:["),
1127 "deps should not use bracket format"
1128 );
1129 }
1130 std::env::remove_var("LEAN_CTX_META");
1131 }
1132
1133 #[test]
1134 fn test_header_toon_saves_tokens() {
1135 let _lock = crate::core::data_dir::test_env_lock();
1136 std::env::set_var("LEAN_CTX_META", "1");
1137 let content = "use crate::foo;\nuse crate::bar;\npub fn baz() {}\npub fn qux() {}\n";
1138 let old_header = "F1=main.rs [4L +] deps:[foo,bar] exports:[baz,qux]".to_string();
1139 let new_header = build_header("F1", "main.rs", "rs", content, 4, true);
1140 let old_tokens = count_tokens(&old_header);
1141 let new_tokens = count_tokens(&new_header);
1142 assert!(
1143 new_tokens <= old_tokens,
1144 "TOON header ({new_tokens} tok) should be <= old format ({old_tokens} tok)"
1145 );
1146 std::env::remove_var("LEAN_CTX_META");
1147 }
1148
1149 #[test]
1150 fn test_tdd_symbols_are_compact() {
1151 let symbols = [
1152 "⊕", "⊖", "∆", "→", "⇒", "✓", "✗", "⚠", "λ", "§", "∂", "τ", "ε",
1153 ];
1154 for sym in &symbols {
1155 let tok = count_tokens(sym);
1156 assert!(tok <= 2, "Symbol {sym} should be 1-2 tokens, got {tok}");
1157 }
1158 }
1159
1160 #[test]
1161 fn test_task_mode_filters_content() {
1162 let content = (0..200)
1163 .map(|i| {
1164 if i % 20 == 0 {
1165 format!("fn validate_token(token: &str) -> bool {{ /* line {i} */ }}")
1166 } else {
1167 format!("fn unrelated_helper_{i}(x: i32) -> i32 {{ x + {i} }}")
1168 }
1169 })
1170 .collect::<Vec<_>>()
1171 .join("\n");
1172 let full_tokens = count_tokens(&content);
1173 let task = Some("fix bug in validate_token");
1174 let (result, result_tokens) = process_mode(
1175 &content,
1176 "task",
1177 "F1",
1178 "test.rs",
1179 "rs",
1180 full_tokens,
1181 CrpMode::Off,
1182 "test.rs",
1183 task,
1184 );
1185 assert!(
1186 result_tokens < full_tokens,
1187 "task mode ({result_tokens} tok) should be less than full ({full_tokens} tok)"
1188 );
1189 assert!(
1190 result.contains("task-filtered"),
1191 "output should contain task-filtered marker"
1192 );
1193 }
1194
1195 #[test]
1196 fn test_task_mode_without_task_returns_full() {
1197 let content = "fn main() {}\nfn helper() {}\n";
1198 let tokens = count_tokens(content);
1199 let (result, _sent) = process_mode(
1200 content,
1201 "task",
1202 "F1",
1203 "test.rs",
1204 "rs",
1205 tokens,
1206 CrpMode::Off,
1207 "test.rs",
1208 None,
1209 );
1210 assert!(
1211 result.contains("no task set"),
1212 "should indicate no task: {result}"
1213 );
1214 }
1215
1216 #[test]
1217 fn test_reference_mode_one_line() {
1218 let content = "fn main() {}\nfn helper() {}\nfn other() {}\n";
1219 let tokens = count_tokens(content);
1220 let (result, _sent) = process_mode(
1221 content,
1222 "reference",
1223 "F1",
1224 "test.rs",
1225 "rs",
1226 tokens,
1227 CrpMode::Off,
1228 "test.rs",
1229 None,
1230 );
1231 let lines: Vec<&str> = result.lines().collect();
1232 assert!(
1233 lines.len() <= 3,
1234 "reference mode should be very compact, got {} lines",
1235 lines.len()
1236 );
1237 assert!(result.contains("lines"), "should contain line count");
1238 assert!(result.contains("tok"), "should contain token count");
1239 }
1240
1241 #[test]
1242 fn cached_lines_mode_invalidates_on_mtime_change() {
1243 let dir = tempfile::tempdir().unwrap();
1244 let path = dir.path().join("file.txt");
1245 let p = path.to_string_lossy().to_string();
1246
1247 std::fs::write(&path, "one\nsecond\n").unwrap();
1248 let mut cache = SessionCache::new();
1249
1250 let r1 = handle_with_task_resolved(&mut cache, &p, "lines:1-1", CrpMode::Off, None);
1251 let l1: Vec<&str> = r1.content.lines().collect();
1252 let got1 = l1.get(1).copied().unwrap_or_default().trim();
1253 let got1 = got1.split_once('|').map_or(got1, |(_, s)| s.trim());
1254 assert_eq!(got1, "one");
1255
1256 std::thread::sleep(Duration::from_secs(1));
1257 std::fs::write(&path, "two\nsecond\n").unwrap();
1258
1259 let r2 = handle_with_task_resolved(&mut cache, &p, "lines:1-1", CrpMode::Off, None);
1260 let l2: Vec<&str> = r2.content.lines().collect();
1261 let got2 = l2.get(1).copied().unwrap_or_default().trim();
1262 let got2 = got2.split_once('|').map_or(got2, |(_, s)| s.trim());
1263 assert_eq!(got2, "two");
1264 }
1265
1266 #[test]
1267 #[cfg_attr(tarpaulin, ignore)]
1268 fn benchmark_task_conditioned_compression() {
1269 let content = generate_benchmark_code(200);
1271 let full_tokens = count_tokens(&content);
1272 let task = Some("fix authentication in validate_token");
1273
1274 let (_full_output, full_tok) = process_mode(
1275 &content,
1276 "full",
1277 "F1",
1278 "server.rs",
1279 "rs",
1280 full_tokens,
1281 CrpMode::Off,
1282 "server.rs",
1283 task,
1284 );
1285 let (_task_output, task_tok) = process_mode(
1286 &content,
1287 "task",
1288 "F1",
1289 "server.rs",
1290 "rs",
1291 full_tokens,
1292 CrpMode::Off,
1293 "server.rs",
1294 task,
1295 );
1296 let (_sig_output, sig_tok) = process_mode(
1297 &content,
1298 "signatures",
1299 "F1",
1300 "server.rs",
1301 "rs",
1302 full_tokens,
1303 CrpMode::Off,
1304 "server.rs",
1305 task,
1306 );
1307 let (_ref_output, ref_tok) = process_mode(
1308 &content,
1309 "reference",
1310 "F1",
1311 "server.rs",
1312 "rs",
1313 full_tokens,
1314 CrpMode::Off,
1315 "server.rs",
1316 task,
1317 );
1318
1319 eprintln!("\n=== Task-Conditioned Compression Benchmark ===");
1320 eprintln!("Source: 200-line Rust file, task='fix authentication in validate_token'");
1321 eprintln!(" full: {full_tok:>6} tokens (baseline)");
1322 eprintln!(
1323 " task: {task_tok:>6} tokens ({:.0}% savings)",
1324 (1.0 - task_tok as f64 / full_tok as f64) * 100.0
1325 );
1326 eprintln!(
1327 " signatures: {sig_tok:>6} tokens ({:.0}% savings)",
1328 (1.0 - sig_tok as f64 / full_tok as f64) * 100.0
1329 );
1330 eprintln!(
1331 " reference: {ref_tok:>6} tokens ({:.0}% savings)",
1332 (1.0 - ref_tok as f64 / full_tok as f64) * 100.0
1333 );
1334 eprintln!("================================================\n");
1335
1336 assert!(task_tok < full_tok, "task mode should save tokens");
1337 assert!(sig_tok < full_tok, "signatures should save tokens");
1338 assert!(ref_tok < sig_tok, "reference should be most compact");
1339 }
1340
1341 fn generate_benchmark_code(lines: usize) -> String {
1342 let mut code = Vec::with_capacity(lines);
1343 code.push("use std::collections::HashMap;".to_string());
1344 code.push("use crate::core::auth;".to_string());
1345 code.push(String::new());
1346 code.push("pub struct Server {".to_string());
1347 code.push(" config: Config,".to_string());
1348 code.push(" cache: HashMap<String, String>,".to_string());
1349 code.push("}".to_string());
1350 code.push(String::new());
1351 code.push("impl Server {".to_string());
1352 code.push(
1353 " pub fn validate_token(&self, token: &str) -> Result<Claims, AuthError> {"
1354 .to_string(),
1355 );
1356 code.push(" let decoded = auth::decode_jwt(token)?;".to_string());
1357 code.push(" if decoded.exp < chrono::Utc::now().timestamp() {".to_string());
1358 code.push(" return Err(AuthError::Expired);".to_string());
1359 code.push(" }".to_string());
1360 code.push(" Ok(decoded.claims)".to_string());
1361 code.push(" }".to_string());
1362 code.push(String::new());
1363
1364 let remaining = lines.saturating_sub(code.len());
1365 for i in 0..remaining {
1366 if i % 30 == 0 {
1367 code.push(format!(
1368 " pub fn handler_{i}(&self, req: Request) -> Response {{"
1369 ));
1370 } else if i % 30 == 29 {
1371 code.push(" }".to_string());
1372 } else {
1373 code.push(format!(" let val_{i} = self.cache.get(\"key_{i}\").unwrap_or(&\"default\".to_string());"));
1374 }
1375 }
1376 code.push("}".to_string());
1377 code.join("\n")
1378 }
1379
1380 #[test]
1381 fn instruction_file_detection() {
1382 assert!(is_instruction_file(
1383 "/home/user/.pi/agent/skills/committing-changes/SKILL.md"
1384 ));
1385 assert!(is_instruction_file("/workspace/.cursor/rules/lean-ctx.mdc"));
1386 assert!(is_instruction_file("/project/AGENTS.md"));
1387 assert!(is_instruction_file("/project/.cursorrules"));
1388 assert!(is_instruction_file("/home/user/.claude/rules/my-rule.md"));
1389 assert!(is_instruction_file("/skills/some-skill/README.md"));
1390
1391 assert!(!is_instruction_file("/project/src/main.rs"));
1392 assert!(!is_instruction_file("/project/config.json"));
1393 assert!(!is_instruction_file("/project/data/report.csv"));
1394 }
1395
1396 #[test]
1397 fn resolve_auto_mode_returns_full_for_instruction_files() {
1398 let mode = resolve_auto_mode(
1399 "/home/user/.pi/agent/skills/committing-changes/SKILL.md",
1400 5000,
1401 Some("read"),
1402 );
1403 assert_eq!(mode, "full", "SKILL.md must always be read in full");
1404
1405 let mode = resolve_auto_mode("/workspace/AGENTS.md", 3000, Some("read"));
1406 assert_eq!(mode, "full", "AGENTS.md must always be read in full");
1407
1408 let mode = resolve_auto_mode("/workspace/.cursorrules", 2000, None);
1409 assert_eq!(mode, "full", ".cursorrules must always be read in full");
1410 }
1411}