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