1use std::path::Path;
2
3use crate::core::compressor;
4use crate::core::deps as dep_extract;
5use crate::core::entropy;
6use crate::core::io_boundary;
7use crate::core::patterns::deps_cmd;
8use crate::core::protocol;
9use crate::core::roles;
10use crate::core::signatures;
11
12#[cfg(unix)]
16fn is_failed_daemon_result(output: &str) -> bool {
17 let first_line = output.lines().next().unwrap_or("");
18 if first_line.starts_with("ERROR:TCC_RESTRICTED:") {
19 return true;
20 }
21 if first_line.starts_with("Cannot read file:") || first_line.starts_with("File is empty:") {
22 return true;
23 }
24 if !first_line.ends_with(" 0L") {
25 return false;
26 }
27 let body: String = output
28 .lines()
29 .skip(1)
30 .filter(|l| {
31 let t = l.trim();
32 !t.is_empty()
33 && !t.starts_with("[no extractable structure")
34 && !t.starts_with("[lean-ctx]")
35 && !t.starts_with('[')
36 })
37 .collect();
38 body.is_empty()
39}
40
41fn resolve_cli_path(raw: &str) -> String {
42 if let Ok(abs) = std::path::Path::new(raw).canonicalize() {
43 return abs.to_string_lossy().to_string();
44 }
45 if Path::new(raw).is_relative()
46 && let Ok(cwd) = std::env::current_dir()
47 {
48 return cwd.join(raw).to_string_lossy().into_owned();
49 }
50 raw.to_string()
51}
52use crate::core::tokens::count_tokens;
53
54use super::common::print_savings;
55
56fn cap_cli_to_raw(framed: String, raw_content: &str, raw_tokens: usize) -> String {
63 if raw_tokens > 0 && count_tokens(&framed) > raw_tokens {
64 raw_content.to_string()
65 } else {
66 framed
67 }
68}
69
70fn should_force_fresh(args: &[String], hook_child: bool) -> bool {
75 hook_child || args.iter().any(|a| a == "--fresh" || a == "--no-cache")
76}
77
78fn resolve_cli_read_mode(args: &[String]) -> &str {
84 if let Some(m) = args
85 .iter()
86 .position(|a| a == "--mode" || a == "-m")
87 .and_then(|i| args.get(i + 1))
88 {
89 return m.as_str();
90 }
91 args.iter()
92 .skip(1)
93 .find(|a| !a.starts_with('-') && a.parse::<crate::tools::ctx_read::ReadMode>().is_ok())
94 .map_or("auto", std::string::String::as_str)
95}
96
97pub fn cmd_read(args: &[String]) {
98 if args.is_empty() {
99 eprintln!(
100 "Usage: lean-ctx read <file> [--mode auto|full|map|signatures|aggressive|entropy] [--fresh]"
101 );
102 std::process::exit(1);
103 }
104
105 let raw_path = &args[0];
106 let path = if Path::new(raw_path).is_relative() {
107 std::env::current_dir().ok().map_or_else(
108 || raw_path.clone(),
109 |cwd| cwd.join(raw_path).to_string_lossy().into_owned(),
110 )
111 } else {
112 raw_path.clone()
113 };
114 let path = path.as_str();
115 let mode = resolve_cli_read_mode(args);
116 let force_fresh = should_force_fresh(args, crate::core::runtime_flags::hook_child_enabled());
123 let requested_auto = mode == "auto";
126
127 let short = protocol::shorten_path(path);
128
129 if let Ok(abs) = std::fs::canonicalize(path) {
132 match io_boundary::check_secret_path_for_tool("cli_read", &abs) {
133 Ok(Some(w)) => eprintln!("{w}"),
134 Ok(None) => {}
135 Err(e) => {
136 eprintln!("{e}");
137 std::process::exit(1);
138 }
139 }
140 } else {
141 let raw = std::path::Path::new(path);
143 match io_boundary::check_secret_path_for_tool("cli_read", raw) {
144 Ok(Some(w)) => eprintln!("{w}"),
145 Ok(None) => {}
146 Err(e) => {
147 eprintln!("{e}");
148 std::process::exit(1);
149 }
150 }
151 }
152
153 #[cfg(unix)]
154 {
155 #[cfg(unix)]
156 if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
157 && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
158 "ctx_read",
159 Some(serde_json::json!({
160 "path": path,
161 "mode": mode,
162 "fresh": force_fresh,
163 })),
164 )
165 {
166 let filtered = super::common::filter_daemon_output(&out);
167 if !filtered.trim().is_empty() && !is_failed_daemon_result(&filtered) {
168 println!("{filtered}");
169 return;
170 }
171 }
173 }
174 super::common::daemon_fallback_hint();
175
176 let read_start = std::time::Instant::now();
179
180 if !force_fresh && mode == "full" {
181 use crate::core::cli_cache::{self, CacheResult};
182 match cli_cache::check_and_read(path) {
183 CacheResult::Hit { entry, file_ref } => {
184 let msg = cli_cache::format_hit(&entry, &file_ref, &short);
185 println!("{msg}");
186 let sent = count_tokens(&msg);
187 super::common::cli_track_read_cached(
188 path,
189 "full",
190 entry.original_tokens,
191 sent,
192 &msg,
193 read_start.elapsed(),
194 );
195 return;
196 }
197 CacheResult::Miss { content } if content.is_empty() => {
198 eprintln!("Error: could not read {path}");
199 std::process::exit(1);
200 }
201 CacheResult::Miss { content } => {
202 let line_count = content.lines().count();
203 let raw_tokens = count_tokens(&content);
204 let framed = format!("{short} [{line_count}L]\n{content}");
205 let output = cap_cli_to_raw(framed, &content, raw_tokens);
206 println!("{output}");
207 let sent = count_tokens(&output);
208 super::common::cli_track_read(
209 path,
210 "full",
211 raw_tokens,
212 sent,
213 &output,
214 read_start.elapsed(),
215 );
216 return;
217 }
218 }
219 }
220
221 let content = match crate::tools::ctx_read::read_file_lossy(path) {
222 Ok(c) => c,
223 Err(e) => {
224 eprintln!("Error: {e}");
225 std::process::exit(1);
226 }
227 };
228
229 let ext = Path::new(path)
230 .extension()
231 .and_then(|e| e.to_str())
232 .unwrap_or("");
233 let line_count = content.lines().count();
234 let original_tokens = count_tokens(&content);
235
236 let mode = if mode == "auto" {
237 crate::core::auto_mode_resolver::resolve(
243 &crate::core::auto_mode_resolver::AutoModeContext {
244 path,
245 token_count: original_tokens,
246 line_count: None,
247 task: None,
248 cache: None,
249 },
250 )
251 .mode
252 } else if mode != "full" && crate::tools::ctx_read::is_instruction_file(path) {
253 "full".to_string()
254 } else {
255 mode.to_string()
256 };
257 let mode = if (mode == "map" || mode == "signatures") && original_tokens <= 400 {
258 "full".to_string()
259 } else {
260 mode
261 };
262 let mode = mode.as_str();
263
264 match mode {
265 "map" => {
266 let structured = match ext {
267 "md" | "mdx" | "rst" => {
268 crate::core::structured_read::extract_markdown_outline(&content)
269 }
270 "json" => crate::core::structured_read::extract_json_structure(&content),
271 "yaml" | "yml" => crate::core::structured_read::extract_yaml_structure(&content),
272 "toml" => crate::core::structured_read::extract_toml_structure(&content),
273 _ if path.to_lowercase().ends_with(".lock")
274 || path.to_lowercase().ends_with("go.sum") =>
275 {
276 crate::core::structured_read::extract_lock_summary(&content, path)
277 }
278 _ => String::new(),
279 };
280
281 let mut output_buf = if structured.is_empty() {
282 let sigs = signatures::extract_signatures(&content, ext);
283 let dep_info = dep_extract::extract_deps(&content, ext);
284 let mut buf = format!("{short} [{line_count}L]");
285 if !dep_info.imports.is_empty() {
286 buf.push_str(&format!("\n deps: {}", dep_info.imports.join(", ")));
287 }
288 let key_sigs: Vec<&signatures::Signature> = sigs
289 .iter()
290 .filter(|s| s.is_exported || s.indent == 0)
291 .collect();
292 let extra_exports =
296 signatures::exports_not_in_signatures(&dep_info.exports, &key_sigs);
297 if !extra_exports.is_empty() {
298 buf.push_str(&format!("\n exports: {}", extra_exports.join(", ")));
299 }
300 if !key_sigs.is_empty() {
301 buf.push_str("\n API:");
302 for sig in &key_sigs {
303 buf.push_str(&format!("\n {}", sig.to_compact_located()));
304 }
305 }
306 if key_sigs.is_empty() && dep_info.imports.is_empty() && extra_exports.is_empty() {
309 buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
310 }
311 buf
312 } else {
313 format!("{short} [{line_count}L]\n{structured}")
314 };
315
316 let sent = count_tokens(&output_buf);
317 output_buf = protocol::append_savings(&output_buf, original_tokens, sent);
318 if requested_auto {
319 output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
320 }
321 let sent = count_tokens(&output_buf);
322 println!("{output_buf}");
323 super::common::cli_track_read(
324 path,
325 "map",
326 original_tokens,
327 sent,
328 &output_buf,
329 read_start.elapsed(),
330 );
331 }
332 "signatures" => {
333 let sigs = signatures::extract_signatures(&content, ext);
334 let mut output_buf = format!("{short} [{line_count}L]");
335 for sig in &sigs {
336 output_buf.push_str(&format!("\n{}", sig.to_compact_located()));
337 }
338 if sigs.is_empty() {
340 output_buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
341 }
342 if requested_auto {
343 output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
344 }
345 println!("{output_buf}");
346 let sent = count_tokens(&output_buf);
347 print_savings(original_tokens, sent);
348 super::common::cli_track_read(
349 path,
350 "signatures",
351 original_tokens,
352 sent,
353 &output_buf,
354 read_start.elapsed(),
355 );
356 }
357 "aggressive" => {
358 let compressed = compressor::aggressive_compress(&content, Some(ext));
359 println!("{short} [{line_count}L]");
360 println!("{compressed}");
361 let sent = count_tokens(&compressed);
362 print_savings(original_tokens, sent);
363 super::common::cli_track_read(
364 path,
365 "aggressive",
366 original_tokens,
367 sent,
368 &compressed,
369 read_start.elapsed(),
370 );
371 }
372 "entropy" => {
373 let result = entropy::entropy_compress(&content);
374 let avg_h = entropy::analyze_entropy(&content).avg_entropy;
375 println!("{short} [{line_count}L] (H̄={avg_h:.1})");
376 for tech in &result.techniques {
377 println!("{tech}");
378 }
379 println!("{}", result.output);
380 let sent = count_tokens(&result.output);
381 print_savings(original_tokens, sent);
382 super::common::cli_track_read(
383 path,
384 "entropy",
385 original_tokens,
386 sent,
387 &result.output,
388 read_start.elapsed(),
389 );
390 }
391 m if m.starts_with("lines:") => {
392 let range_str = &m[6..];
396 let extracted = crate::tools::ctx_read::extract_line_range(&content, range_str);
397 let multi_hint = if range_str.contains(',') {
398 crate::tools::ctx_read::LINES_COMMA_HINT
399 } else {
400 ""
401 };
402 let output =
403 format!("{short} [{line_count}L] lines:{range_str}\n{extracted}{multi_hint}");
404 println!("{output}");
405 let sent = count_tokens(&output);
406 print_savings(original_tokens, sent);
407 super::common::cli_track_read(
408 path,
409 "lines",
410 original_tokens,
411 sent,
412 &output,
413 read_start.elapsed(),
414 );
415 }
416 "cognitive" | "mdl" => {
417 let (output, _) = crate::tools::ctx_read::process_mode(
418 &content,
419 mode,
420 "",
421 &short,
422 ext,
423 original_tokens,
424 crate::core::protocol::CrpMode::Off,
425 path,
426 None,
427 );
428 let output = if requested_auto {
429 cap_cli_to_raw(output, &content, original_tokens)
430 } else {
431 output
432 };
433 let sent = count_tokens(&output);
434 println!("{output}");
435 print_savings(original_tokens, sent);
436 super::common::cli_track_read(
437 path,
438 mode,
439 original_tokens,
440 sent,
441 &output,
442 read_start.elapsed(),
443 );
444 }
445 _ => {
446 let mut output = format!("{short} [{line_count}L]\n{content}");
453 if !crate::core::terse::is_verbatim_read("ctx_read", Some(mode)) {
454 let config = crate::core::config::Config::load();
455 let level = crate::core::config::CompressionLevel::effective(&config);
456 if level.is_active() {
457 let terse_result =
458 crate::core::terse::pipeline::compress(&output, &level, None);
459 if terse_result.quality_passed && terse_result.savings_pct >= 3.0 {
460 output = terse_result.output;
461 }
462 }
463 }
464 let output = cap_cli_to_raw(output, &content, original_tokens);
467 println!("{output}");
468 let sent = count_tokens(&output);
469 super::common::cli_track_read(
470 path,
471 "full",
472 original_tokens,
473 sent,
474 &output,
475 read_start.elapsed(),
476 );
477 }
478 }
479}
480
481pub fn cmd_diff(args: &[String]) {
482 if args.len() < 2 {
483 eprintln!("Usage: lean-ctx diff <file1> <file2>");
484 std::process::exit(1);
485 }
486
487 let content1 = match crate::tools::ctx_read::read_file_lossy(&args[0]) {
488 Ok(c) => c,
489 Err(e) => {
490 eprintln!("Error reading {}: {e}", args[0]);
491 std::process::exit(1);
492 }
493 };
494
495 let content2 = match crate::tools::ctx_read::read_file_lossy(&args[1]) {
496 Ok(c) => c,
497 Err(e) => {
498 eprintln!("Error reading {}: {e}", args[1]);
499 std::process::exit(1);
500 }
501 };
502
503 let diff = compressor::diff_content(&content1, &content2);
504 let original = count_tokens(&content1) + count_tokens(&content2);
505 let sent = count_tokens(&diff);
506
507 println!(
508 "diff {} {}",
509 protocol::shorten_path(&args[0]),
510 protocol::shorten_path(&args[1])
511 );
512 println!("{diff}");
513 print_savings(original, sent);
514 crate::core::stats::record("cli_diff", original, sent);
515}
516
517pub fn cmd_grep(args: &[String]) {
518 if args.is_empty() {
519 eprintln!("Usage: lean-ctx grep <pattern> [path]");
520 std::process::exit(1);
521 }
522
523 let pattern = &args[0];
524 let raw_path = args.get(1).map_or(".", std::string::String::as_str);
525 let abs_path = resolve_cli_path(raw_path);
526 let path = abs_path.as_str();
527
528 #[cfg(unix)]
529 {
530 #[cfg(unix)]
531 if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
532 && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
533 "ctx_search",
534 Some(serde_json::json!({
535 "pattern": pattern,
536 "path": path,
537 })),
538 )
539 {
540 let out = super::common::filter_daemon_output(&out);
541 println!("{out}");
542 if out.trim_start().starts_with("0 matches") {
543 std::process::exit(1);
544 }
545 return;
546 }
547 }
548 super::common::daemon_fallback_hint();
549
550 let search_start = std::time::Instant::now();
552
553 let outcome = crate::tools::ctx_search::handle(
554 pattern,
555 path,
556 None,
557 20,
558 crate::tools::CrpMode::effective(),
559 true,
560 roles::active_role().io.allow_secret_paths,
561 false,
562 );
563 let out = outcome.text;
564 println!("{out}");
565 super::common::cli_track_search(
566 outcome.modeled_baseline,
567 outcome.observed_tokens,
568 count_tokens(&out),
569 pattern,
570 path,
571 &out,
572 search_start.elapsed(),
573 );
574 if outcome.modeled_baseline == 0 && out.trim_start().starts_with("0 matches") {
575 std::process::exit(1);
576 }
577}
578
579pub fn cmd_glob(args: &[String]) {
584 if args.is_empty() {
585 eprintln!("Usage: lean-ctx glob <pattern> [path]");
586 std::process::exit(1);
587 }
588
589 let pattern = &args[0];
590 let raw_path = args.get(1).map_or(".", std::string::String::as_str);
591 let abs_path = resolve_cli_path(raw_path);
592 let path = abs_path.as_str();
593
594 #[cfg(unix)]
595 if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
596 && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
597 "ctx_glob",
598 Some(serde_json::json!({
599 "pattern": pattern,
600 "path": path,
601 })),
602 )
603 {
604 let out = super::common::filter_daemon_output(&out);
605 println!("{out}");
606 return;
607 }
608 super::common::daemon_fallback_hint();
609
610 let (out, _original) = crate::tools::ctx_glob::handle(
611 pattern,
612 path,
613 true,
614 roles::active_role().io.allow_secret_paths,
615 200,
616 );
617 println!("{out}");
618 crate::core::stats::record("cli_glob", 0, 0);
619 if out.starts_with("ERROR:") {
620 std::process::exit(1);
621 }
622}
623
624pub fn cmd_find(args: &[String]) {
625 if args.is_empty() {
626 eprintln!("Usage: lean-ctx find <pattern> [path]");
627 std::process::exit(1);
628 }
629
630 let raw_pattern = &args[0];
631 let path = args.get(1).map_or(".", std::string::String::as_str);
632
633 let is_glob = raw_pattern.contains('*') || raw_pattern.contains('?');
634 let glob_matcher = if is_glob {
635 glob::Pattern::new(&raw_pattern.to_lowercase()).ok()
636 } else {
637 None
638 };
639 let substring = raw_pattern.to_lowercase();
640
641 let mut found = false;
642 let walk_root = crate::core::walk_filter::explicit_walk_root(std::path::Path::new(path));
643 for entry in ignore::WalkBuilder::new(&walk_root)
644 .hidden(true)
645 .git_ignore(true)
646 .git_global(true)
647 .git_exclude(true)
648 .require_git(false)
649 .max_depth(Some(10))
650 .filter_entry(crate::core::walk_filter::keep_entry)
651 .build()
652 .flatten()
653 {
654 let name = entry.file_name().to_string_lossy().to_lowercase();
655 let matches = if let Some(ref g) = glob_matcher {
656 g.matches(&name)
657 } else {
658 name.contains(&substring)
659 };
660 if matches {
661 println!("{}", entry.path().display());
662 found = true;
663 }
664 }
665
666 crate::core::stats::record("cli_find", 0, 0);
667
668 if !found {
669 std::process::exit(1);
670 }
671}
672
673pub fn cmd_ls(args: &[String]) {
674 let mut raw_path = ".";
675 let mut depth = 3usize;
676 let mut show_hidden = false;
677 let mut respect_gitignore = true;
678 let mut i = 0;
679
680 while i < args.len() {
681 let arg = &args[i];
682 if arg == "--depth" {
683 i += 1;
684 if let Some(d) = args.get(i).and_then(|s| s.parse::<usize>().ok()) {
685 depth = d.min(10);
686 }
687 } else if arg == "--all" || arg == "-a" {
688 show_hidden = true;
689 } else if arg == "--no-gitignore" {
690 respect_gitignore = false;
691 } else if arg.starts_with('-') {
692 eprintln!("Error: lean-ctx ls does not support flag '{arg}'.\n");
693 eprintln!(
694 "lean-ctx ls is a compressed directory tree viewer for AI context, not a drop-in ls replacement."
695 );
696 eprintln!(
697 "The shell hook (lean-ctx -t ls {arg} ...) passes flags to system ls transparently.\n"
698 );
699 eprintln!("Usage: lean-ctx ls [path] [--depth N] [--all] [--no-gitignore]");
700 std::process::exit(1);
701 } else {
702 raw_path = arg;
703 }
704 i += 1;
705 }
706
707 let abs_path = resolve_cli_path(raw_path);
708 let path = abs_path.as_str();
709
710 #[cfg(unix)]
711 {
712 #[cfg(unix)]
713 if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
714 && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
715 "ctx_tree",
716 Some(serde_json::json!({
717 "path": path,
718 "depth": depth,
719 "show_hidden": show_hidden,
720 "respect_gitignore": respect_gitignore,
721 })),
722 )
723 {
724 if !out.starts_with("ERROR:TCC_RESTRICTED:") {
725 println!("{}", super::common::filter_daemon_output(&out));
726 return;
727 }
728 }
729 }
730 super::common::daemon_fallback_hint();
731
732 let (out, original) =
733 crate::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
734 println!("{out}");
735 super::common::cli_track_tree(original, count_tokens(&out));
736}
737
738pub fn cmd_deps(args: &[String]) {
739 let path = args.first().map_or(".", std::string::String::as_str);
740
741 if let Some(result) = deps_cmd::detect_and_compress(path) {
742 println!("{result}");
743 crate::core::stats::record("cli_deps", 0, 0);
744 } else {
745 eprintln!("No dependency file found in {path}");
746 std::process::exit(1);
747 }
748}
749
750#[cfg(all(test, unix))]
751mod empty_daemon_tests {
752 use super::is_failed_daemon_result;
753
754 #[test]
755 fn detects_tcc_empty_stub() {
756 assert!(is_failed_daemon_result(
757 "file.rs 0L
758"
759 ));
760 assert!(is_failed_daemon_result(
761 "F1=file.rs 0L
762[lean-ctx: 0 tok saved]"
763 ));
764 }
765
766 #[test]
767 fn accepts_real_content() {
768 assert!(!is_failed_daemon_result(
769 "file.rs 10L
770fn main() {}
771"
772 ));
773 }
774
775 #[test]
776 fn accepts_nonzero_line_count() {
777 assert!(!is_failed_daemon_result(
778 "file.rs 1L
779"
780 ));
781 }
782
783 #[test]
784 fn ignores_structure_markers_in_body() {
785 assert!(is_failed_daemon_result(
786 "file.rs 0L
787[no extractable structure for .rs]
788"
789 ));
790 }
791
792 #[test]
793 fn detects_tcc_restricted_marker() {
794 assert!(is_failed_daemon_result(
795 "ERROR:TCC_RESTRICTED: daemon cannot access /Users/me/Documents/proj (sandboxed)"
796 ));
797 }
798}
799
800#[cfg(test)]
801mod cap_tests {
802 use super::{cap_cli_to_raw, count_tokens};
803
804 #[test]
805 fn caps_to_raw_when_framing_inflates() {
806 let raw = "x = 1\n";
810 let raw_tokens = count_tokens(raw);
811 let framed = format!("some/very/long/path/header.rs [1L]\n{raw}\n[lean-ctx: 0 tok saved]");
812 assert!(count_tokens(&framed) > raw_tokens, "fixture must inflate");
813 assert_eq!(cap_cli_to_raw(framed, raw, raw_tokens), raw);
814 }
815
816 #[test]
817 fn keeps_framing_when_it_saves() {
818 let raw = "fn a() {}\n".repeat(300);
820 let raw_tokens = count_tokens(&raw);
821 let framed = "f.rs [300L]\nfn a() {} …".to_string();
822 assert!(count_tokens(&framed) < raw_tokens);
823 assert_eq!(cap_cli_to_raw(framed.clone(), &raw, raw_tokens), framed);
824 }
825
826 #[test]
827 fn keeps_framing_for_empty_file() {
828 let framed = "empty.rs [0L]\n".to_string();
830 assert_eq!(cap_cli_to_raw(framed.clone(), "", 0), framed);
831 }
832
833 #[test]
834 fn break_even_is_not_inflation() {
835 let raw = "alpha beta gamma delta";
837 let raw_tokens = count_tokens(raw);
838 let framed = raw.to_string();
839 assert_eq!(count_tokens(&framed), raw_tokens);
840 assert_eq!(cap_cli_to_raw(framed.clone(), raw, raw_tokens), framed);
841 }
842
843 #[test]
844 fn emitted_never_exceeds_raw_across_sizes() {
845 for n in [1usize, 5, 50, 500] {
848 let raw = "data line here\n".repeat(n);
849 let raw_tokens = count_tokens(&raw);
850 let framed = format!("a/b/c/path.txt [{n}L]\n{raw}\n[lean-ctx: {n} tok saved ({n}%)]");
851 let out = cap_cli_to_raw(framed, &raw, raw_tokens);
852 assert!(
853 count_tokens(&out) <= raw_tokens,
854 "n={n}: emitted {} tok exceeds raw {raw_tokens}",
855 count_tokens(&out)
856 );
857 }
858 }
859}
860
861#[cfg(test)]
862mod fresh_tests {
863 use super::should_force_fresh;
864
865 #[test]
866 fn hook_child_forces_fresh_even_without_flags() {
867 assert!(should_force_fresh(&[], true));
870 assert!(!should_force_fresh(&[], false));
871 }
872
873 #[test]
874 fn explicit_flags_force_fresh() {
875 assert!(should_force_fresh(&["--fresh".to_string()], false));
876 assert!(should_force_fresh(&["--no-cache".to_string()], false));
877 assert!(!should_force_fresh(&["file.rs".to_string()], false));
878 }
879}
880
881#[cfg(test)]
882mod mode_arg_tests {
883 use super::resolve_cli_read_mode;
884
885 fn args(list: &[&str]) -> Vec<String> {
886 list.iter().map(ToString::to_string).collect()
887 }
888
889 #[test]
893 fn positional_mode_is_honoured() {
894 assert_eq!(resolve_cli_read_mode(&args(&["f.ps1", "map"])), "map");
895 assert_eq!(
896 resolve_cli_read_mode(&args(&["f.rs", "lines:5-10"])),
897 "lines:5-10"
898 );
899 }
900
901 #[test]
902 fn mode_flag_wins_over_positional() {
903 assert_eq!(
904 resolve_cli_read_mode(&args(&["f.rs", "map", "--mode", "signatures"])),
905 "signatures"
906 );
907 assert_eq!(
908 resolve_cli_read_mode(&args(&["f.rs", "-m", "full"])),
909 "full"
910 );
911 }
912
913 #[test]
914 fn defaults_to_auto_and_skips_flags_and_junk() {
915 assert_eq!(resolve_cli_read_mode(&args(&["f.rs"])), "auto");
916 assert_eq!(resolve_cli_read_mode(&args(&["f.rs", "--fresh"])), "auto");
917 assert_eq!(resolve_cli_read_mode(&args(&["f.rs", "banana"])), "auto");
919 }
920}