1use std::path::Path;
4
5use lean_ctx::core::command_root::jail_cli_read_path;
6use lean_ctx::core::compressor;
7use lean_ctx::core::deps as dep_extract;
8use lean_ctx::core::entropy;
9use lean_ctx::core::io_boundary;
10use lean_ctx::core::patterns::deps_cmd;
11use lean_ctx::core::protocol;
12use lean_ctx::core::roles;
13use lean_ctx::core::signatures;
14
15use super::context_execution::{CommandOutput, LocalOperation, Recording, excerpt};
16
17#[path = "read_cmd_policy.rs"]
18mod policy_read;
19
20#[path = "read_cmd_carrier.rs"]
21mod carrier;
22#[cfg(unix)]
23use carrier::released_daemon_result;
24use carrier::{Stdout, deliver_carrier, tool_arguments};
25
26#[cfg(unix)]
30fn is_failed_daemon_result(output: &str) -> bool {
31 let first_line = output.lines().next().unwrap_or("");
32 if first_line.starts_with("ERROR:") {
33 return true;
34 }
35 if first_line.starts_with("Cannot read file:") {
36 return true;
37 }
38 if !first_line.ends_with(" 0L") {
39 return false;
40 }
41 let body: String = output
42 .lines()
43 .skip(1)
44 .filter(|l| {
45 let t = l.trim();
46 !t.is_empty()
47 && !t.starts_with("[no extractable structure")
48 && !t.starts_with("[lean-ctx]")
49 && !t.starts_with('[')
50 })
51 .collect();
52 body.is_empty()
53}
54
55fn resolve_cli_path(raw: &str) -> String {
56 if let Ok(abs) = std::path::Path::new(raw).canonicalize() {
57 return abs.to_string_lossy().to_string();
58 }
59 if Path::new(raw).is_relative()
60 && let Ok(cwd) = std::env::current_dir()
61 {
62 return cwd.join(raw).to_string_lossy().into_owned();
63 }
64 raw.to_string()
65}
66use lean_ctx::core::tokens::count_tokens;
67
68use super::common::print_savings;
69
70fn cap_cli_to_raw(framed: String, raw_content: &str, raw_tokens: usize) -> String {
77 if raw_tokens > 0 && count_tokens(&framed) > raw_tokens {
78 raw_content.to_string()
79 } else {
80 framed
81 }
82}
83
84fn should_force_fresh(args: &[String], hook_child: bool) -> bool {
89 hook_child || args.iter().any(|a| a == "--fresh" || a == "--no-cache")
90}
91
92fn resolve_cli_read_mode(args: &[String]) -> String {
98 if let Some(m) = args
99 .iter()
100 .position(|a| a == "--mode" || a == "-m")
101 .and_then(|i| args.get(i + 1))
102 {
103 return lean_ctx_server::tools::ctx_read::canonicalize_tail_mode(m)
106 .unwrap_or_else(|| m.clone());
107 }
108 args.iter()
109 .skip(1)
110 .find(|a| {
111 !a.starts_with('-')
112 && a.parse::<lean_ctx_server::tools::ctx_read::ReadMode>()
113 .is_ok()
114 })
115 .map_or_else(|| "auto".to_string(), std::clone::Clone::clone)
116}
117
118#[cfg(unix)]
122const CALLER_OUTPUT_OVERRIDES: [&str; 3] = [
123 "LEAN_CTX_CRP_MODE",
124 "LEAN_CTX_COMPRESSION",
125 "LEAN_CTX_PROFILE",
126];
127
128#[cfg(unix)]
129fn has_caller_output_override() -> bool {
130 CALLER_OUTPUT_OVERRIDES
131 .iter()
132 .any(|k| std::env::var(k).is_ok_and(|v| !v.trim().is_empty()))
133}
134
135fn push_signature_lines(
140 out: &mut String,
141 sigs: &[&signatures::Signature],
142 crp: lean_ctx_server::tools::CrpMode,
143 indent: &str,
144 legend_inline: bool,
145) {
146 if crp.is_tdd() {
147 let legend = signatures::tdd_legend(sigs);
148 if !legend.is_empty() {
149 out.push(if legend_inline { ' ' } else { '\n' });
150 out.push_str(&legend);
151 }
152 }
153 for sig in sigs {
154 out.push('\n');
155 out.push_str(indent);
156 if crp.is_tdd() {
157 out.push_str(&sig.to_tdd_located());
158 } else {
159 out.push_str(&sig.to_compact_located());
160 }
161 }
162}
163
164pub fn cmd_read(args: &[String]) -> bool {
165 super::context_execution::execute(super::context_execution::ContextCommand::Read, args)
166 .exit_code
167 == 0
168}
169
170pub(crate) fn observe_read<'a>(
171 args: &'a [String],
172 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
173) -> CommandOutput {
174 if args.is_empty() {
175 eprintln!(
176 "Usage: lean-ctx read <file> [--mode auto|full|map|signatures|aggressive|entropy|lines:N-M|lines:-N] [--fresh]"
177 );
178 return CommandOutput::rejected(1);
179 }
180
181 let raw_path = &args[0];
184 let project_root = super::common::detect_project_root(args);
185 let path = match jail_cli_read_path(raw_path, &project_root) {
186 Ok(p) => p,
187 Err(e) => {
188 eprintln!("{e}");
189 return CommandOutput::rejected(1);
190 }
191 };
192 let mode = resolve_cli_read_mode(args);
193 let force_fresh = should_force_fresh(args, lean_ctx::core::runtime_flags::hook_child_enabled());
195
196 let read_arguments = tool_arguments(serde_json::json!({ "path": path, "mode": mode }));
205 let cwd = std::env::current_dir()
206 .map(|dir| dir.to_string_lossy().into_owned())
207 .unwrap_or_default();
208 let protected_run = super::common::CliToolRun::new("ctx_read", &cwd, Some(&read_arguments))
209 .admitted_reader_output();
210 let (prepared, capture) = protected_run.acquire(|| policy_read::prepare(&path, &mode));
211 match prepared {
212 Ok(Some(prepared)) => {
213 return super::context_execution::run_protected(
214 super::context_execution::ContextCommand::Read,
215 Box::new(move || {
216 prepared.publish(|printable| protected_run.finish(printable, capture))
217 }),
218 );
219 }
220 Ok(None) => {}
221 Err(()) => {
222 eprintln!("Content withheld by the active context policy.");
223 return CommandOutput::rejected(1);
224 }
225 }
226
227 if let Ok(abs) = std::fs::canonicalize(&path) {
230 match io_boundary::check_secret_path_for_tool("cli_read", &abs) {
231 Ok(Some(w)) => eprintln!("{w}"),
232 Ok(None) => {}
233 Err(e) => {
234 eprintln!("{e}");
235 return CommandOutput::rejected(1);
236 }
237 }
238 } else {
239 match io_boundary::check_secret_path_for_tool("cli_read", Path::new(&path)) {
241 Ok(Some(w)) => eprintln!("{w}"),
242 Ok(None) => {}
243 Err(e) => {
244 eprintln!("{e}");
245 return CommandOutput::rejected(1);
246 }
247 }
248 }
249
250 #[cfg(unix)]
253 if !lean_ctx::core::pathutil::is_under_tcc_protected_dir(Path::new(&path))
254 && !has_caller_output_override()
255 {
256 match lean_ctx::daemon_client::try_daemon_tool_call_blocking_observed(
257 "ctx_read",
258 Some(serde_json::json!({
259 "path": path.clone(),
260 "mode": mode.clone(),
261 "fresh": force_fresh,
262 })),
263 ) {
264 lean_ctx::daemon_client::DaemonToolCallOutcome::Unavailable => {}
265 lean_ctx::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
266 let filtered = super::common::filter_daemon_output(&text);
267 let exit_code = i32::from(is_error || is_failed_daemon_result(&filtered));
268 if !filtered.trim().is_empty()
269 && let Some(released) = released_daemon_result(
270 "ctx_read",
271 &project_root,
272 Some(&read_arguments),
273 false,
274 filtered,
275 exit_code != 0,
276 )
277 {
278 super::common::print_released(&released);
279 }
280 return CommandOutput::daemon(exit_code);
281 }
282 lean_ctx::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
283 eprintln!("Error: daemon result uncertain: {message}");
284 return CommandOutput::daemon(1);
285 }
286 }
287 }
288 super::common::daemon_fallback_hint();
289
290 let requested_auto = mode == "auto";
291 run_local(Box::new(move || {
292 deliver_carrier(
293 "ctx_read",
294 &project_root,
295 Some(&read_arguments),
296 false,
297 |out| {
298 local_read(
299 &path,
300 &project_root,
301 &mode,
302 force_fresh,
303 requested_auto,
304 out,
305 )
306 },
307 )
308 }))
309}
310
311fn local_read(
312 path: &str,
313 project_root: &str,
314 mode: &str,
315 force_fresh: bool,
316 requested_auto: bool,
317 out: &mut Stdout,
318) -> CommandOutput {
319 let short = protocol::shorten_path(path);
320 let read_start = std::time::Instant::now();
321 let source = match lean_ctx_server::tools::ctx_read::read_file_lossy_admitted_for_cli(path) {
322 Ok(source) => source,
323 Err(e) => {
324 eprintln!("Error: {e}");
325 return CommandOutput::local(1, None);
326 }
327 };
328 lean_ctx::core::archive::authority::publish_read(
335 Path::new(project_root),
336 &lean_ctx::core::pathutil::safe_canonicalize_bounded(Path::new(path), 2000)
337 .to_string_lossy(),
338 "ctx_read",
339 &source.text,
340 );
341 let content = source.text.as_str();
342 let storable = source.storable;
343 let original_tokens = count_tokens(content);
344
345 if !force_fresh && mode == "full" {
346 use lean_ctx_ext::core::cli_cache::{self, CacheResult};
347 match cli_cache::check_admitted(path, &source) {
348 CacheResult::Hit { entry, file_ref } => {
349 let msg = cli_cache::format_hit(&entry, &file_ref, &short);
350 out.hint();
353 out.line(&msg);
354 let sent = count_tokens(&msg);
355 return CommandOutput::local(
356 0,
357 storable.then_some(Recording::Read {
358 path: path.to_string(),
359 mode: "full".to_string(),
360 input_tokens: entry.original_tokens,
361 output_tokens: sent,
362 cache_hit: true,
363 elapsed: read_start.elapsed(),
364 excerpt: excerpt(&msg),
365 }),
366 );
367 }
368 CacheResult::Miss { content } if content.is_empty() => {
369 eprintln!("Error: could not read {path}");
370 return CommandOutput::local(1, None);
371 }
372 CacheResult::Miss { content } => {
373 let line_count = content.lines().count();
374 let framed = format!("{short} [{line_count}L]\n{content}");
375 let output = cap_cli_to_raw(framed, &content, original_tokens);
376 out.line(&output);
377 let sent = count_tokens(&output);
378 return CommandOutput::local(
379 0,
380 storable.then_some(Recording::Read {
381 path: path.to_string(),
382 mode: "full".to_string(),
383 input_tokens: original_tokens,
384 output_tokens: sent,
385 cache_hit: false,
386 elapsed: read_start.elapsed(),
387 excerpt: excerpt(&output),
388 }),
389 );
390 }
391 }
392 }
393
394 let ext = Path::new(path)
395 .extension()
396 .and_then(|e| e.to_str())
397 .unwrap_or("");
398 let line_count = content.lines().count();
399
400 let mode = if mode == "auto" {
401 lean_ctx::core::auto_mode_resolver::resolve(
407 &lean_ctx::core::auto_mode_resolver::AutoModeContext {
408 path,
409 token_count: original_tokens,
410 line_count: None,
411 task: None,
412 cache: None,
413 },
414 )
415 .mode
416 } else if mode != "full" && lean_ctx_server::tools::ctx_read::is_instruction_file(path) {
417 "full".to_string()
418 } else {
419 mode.to_string()
420 };
421 let mode = if (mode == "map" || mode == "signatures") && original_tokens <= 400 {
422 "full".to_string()
423 } else {
424 mode
425 };
426 let mode = mode.as_str();
427
428 match mode {
429 "map" => {
430 let structured = match ext {
431 "md" | "mdx" | "rst" => {
432 lean_ctx::core::structured_read::extract_markdown_outline(&content)
433 }
434 "json" => lean_ctx::core::structured_read::extract_json_structure(&content),
435 "yaml" | "yml" => lean_ctx::core::structured_read::extract_yaml_structure(&content),
436 "toml" => lean_ctx::core::structured_read::extract_toml_structure(&content),
437 _ if path.to_lowercase().ends_with(".lock")
438 || path.to_lowercase().ends_with("go.sum") =>
439 {
440 lean_ctx::core::structured_read::extract_lock_summary(&content, path)
441 }
442 _ => String::new(),
443 };
444
445 let mut output_buf = if structured.is_empty() {
446 let sigs = signatures::extract_signatures(&content, ext);
447 let dep_info = dep_extract::extract_deps(&content, ext);
448 let mut buf = format!("{short} [{line_count}L]");
449 if !dep_info.imports.is_empty() {
450 buf.push_str(&format!("\n deps: {}", dep_info.imports.join(", ")));
451 }
452 let key_sigs: Vec<&signatures::Signature> = sigs
453 .iter()
454 .filter(|s| s.is_exported || s.indent == 0)
455 .collect();
456 let extra_exports =
460 signatures::exports_not_in_signatures(&dep_info.exports, &key_sigs);
461 if !extra_exports.is_empty() {
462 buf.push_str(&format!("\n exports: {}", extra_exports.join(", ")));
463 }
464 if !key_sigs.is_empty() {
465 buf.push_str("\n API:");
466 push_signature_lines(
467 &mut buf,
468 &key_sigs,
469 lean_ctx_server::tools::CrpMode::effective(),
470 " ",
471 true,
472 );
473 }
474 if key_sigs.is_empty() && dep_info.imports.is_empty() && extra_exports.is_empty() {
477 buf.push_str(&lean_ctx_server::tools::ctx_read::no_structure_marker(ext));
478 }
479 buf
480 } else {
481 format!("{short} [{line_count}L]\n{structured}")
482 };
483
484 let sent = count_tokens(&output_buf);
485 output_buf = protocol::append_savings(&output_buf, original_tokens, sent);
486 if requested_auto {
487 output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
488 }
489 let sent = count_tokens(&output_buf);
490 out.line(&output_buf);
491 CommandOutput::local(
492 0,
493 storable.then_some(Recording::Read {
494 path: path.to_string(),
495 mode: "map".to_string(),
496 input_tokens: original_tokens,
497 output_tokens: sent,
498 cache_hit: false,
499 elapsed: read_start.elapsed(),
500 excerpt: excerpt(&output_buf),
501 }),
502 )
503 }
504 "signatures" => {
505 let sigs = signatures::extract_signatures(&content, ext);
506 let mut output_buf = format!("{short} [{line_count}L]");
507 let refs: Vec<&signatures::Signature> = sigs.iter().collect();
508 push_signature_lines(
509 &mut output_buf,
510 &refs,
511 lean_ctx_server::tools::CrpMode::effective(),
512 "",
513 false,
514 );
515 if sigs.is_empty() {
517 output_buf.push_str(&lean_ctx_server::tools::ctx_read::no_structure_marker(ext));
518 }
519 if requested_auto {
520 output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
521 }
522 out.line(&output_buf);
523 let sent = count_tokens(&output_buf);
524 out.savings(original_tokens, sent);
525 CommandOutput::local(
526 0,
527 storable.then_some(Recording::Read {
528 path: path.to_string(),
529 mode: "signatures".to_string(),
530 input_tokens: original_tokens,
531 output_tokens: sent,
532 cache_hit: false,
533 elapsed: read_start.elapsed(),
534 excerpt: excerpt(&output_buf),
535 }),
536 )
537 }
538 "aggressive" => {
539 let compressed = compressor::aggressive_compress(&content, Some(ext));
540 out.line(format_args!("{short} [{line_count}L]"));
541 out.line(&compressed);
542 let sent = count_tokens(&compressed);
543 out.savings(original_tokens, sent);
544 CommandOutput::local(
545 0,
546 storable.then_some(Recording::Read {
547 path: path.to_string(),
548 mode: "aggressive".to_string(),
549 input_tokens: original_tokens,
550 output_tokens: sent,
551 cache_hit: false,
552 elapsed: read_start.elapsed(),
553 excerpt: excerpt(&compressed),
554 }),
555 )
556 }
557 "entropy" => {
558 let result = entropy::entropy_compress(&content);
559 let avg_h = entropy::analyze_entropy(&content).avg_entropy;
560 out.line(format_args!("{short} [{line_count}L] (H̄={avg_h:.1})"));
561 for tech in &result.techniques {
562 out.line(tech);
563 }
564 out.line(&result.output);
565 let sent = count_tokens(&result.output);
566 out.savings(original_tokens, sent);
567 CommandOutput::local(
568 0,
569 storable.then_some(Recording::Read {
570 path: path.to_string(),
571 mode: "entropy".to_string(),
572 input_tokens: original_tokens,
573 output_tokens: sent,
574 cache_hit: false,
575 elapsed: read_start.elapsed(),
576 excerpt: excerpt(&result.output),
577 }),
578 )
579 }
580 m if m.starts_with("lines:") => {
581 let range_str = &m[6..];
585 let extracted =
586 lean_ctx_server::tools::ctx_read::extract_line_range(&content, range_str);
587 let multi_hint = if range_str.contains(',') {
588 lean_ctx_server::tools::ctx_read::LINES_COMMA_HINT
589 } else {
590 ""
591 };
592 let output =
593 format!("{short} [{line_count}L] lines:{range_str}\n{extracted}{multi_hint}");
594 if !multi_hint.is_empty() {
595 out.hint();
597 }
598 out.line(&output);
599 let sent = count_tokens(&output);
600 out.savings(original_tokens, sent);
601 CommandOutput::local(
602 0,
603 storable.then_some(Recording::Read {
604 path: path.to_string(),
605 mode: "lines".to_string(),
606 input_tokens: original_tokens,
607 output_tokens: sent,
608 cache_hit: false,
609 elapsed: read_start.elapsed(),
610 excerpt: excerpt(&output),
611 }),
612 )
613 }
614 m if matches!(m, "cognitive" | "mdl" | "reference" | "task")
618 || m.starts_with("density:") =>
619 {
620 let (output, _) = lean_ctx_server::tools::ctx_read::process_mode(
621 &content,
622 mode,
623 "",
624 &short,
625 ext,
626 original_tokens,
627 lean_ctx::core::protocol::CrpMode::Off,
628 path,
629 None,
630 );
631 let output = if requested_auto {
632 cap_cli_to_raw(output, &content, original_tokens)
633 } else {
634 output
635 };
636 let sent = count_tokens(&output);
637 out.line(&output);
638 out.savings(original_tokens, sent);
639 CommandOutput::local(
640 0,
641 storable.then_some(Recording::Read {
642 path: path.to_string(),
643 mode: mode.to_string(),
644 input_tokens: original_tokens,
645 output_tokens: sent,
646 cache_hit: false,
647 elapsed: read_start.elapsed(),
648 excerpt: excerpt(&output),
649 }),
650 )
651 }
652 _ => {
653 let mut output = format!("{short} [{line_count}L]\n{content}");
660 if !lean_ctx::core::terse::is_verbatim_read("ctx_read", Some(mode)) {
661 let config = lean_ctx::core::config::Config::load();
662 let level = lean_ctx::core::config::CompressionLevel::effective(&config);
663 if level.is_active() {
664 let terse_result =
665 lean_ctx::core::terse::pipeline::compress(&output, &level, None);
666 if terse_result.quality_passed && terse_result.savings_pct >= 3.0 {
667 output = terse_result.output;
668 }
669 }
670 }
671 let output = cap_cli_to_raw(output, &content, original_tokens);
674 out.line(&output);
675 let sent = count_tokens(&output);
676 CommandOutput::local(
677 0,
678 storable.then_some(Recording::Read {
679 path: path.to_string(),
680 mode: "full".to_string(),
681 input_tokens: original_tokens,
682 output_tokens: sent,
683 cache_hit: false,
684 elapsed: read_start.elapsed(),
685 excerpt: excerpt(&output),
686 }),
687 )
688 }
689 }
690}
691
692pub fn cmd_diff(args: &[String]) {
693 let output =
694 super::context_execution::execute(super::context_execution::ContextCommand::Diff, args);
695 if output.exit_code != 0 {
696 std::process::exit(output.exit_code);
697 }
698}
699
700pub(crate) fn observe_diff<'a>(
701 args: &'a [String],
702 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
703) -> CommandOutput {
704 if args.len() < 2 {
705 eprintln!("Usage: lean-ctx diff <file1> <file2>");
706 return CommandOutput::rejected(1);
707 }
708
709 let path1 = args[0].clone();
710 let path2 = args[1].clone();
711 run_local(Box::new(move || local_diff(&path1, &path2)))
712}
713
714fn admitted_diff_sides(path1: &str, path2: &str) -> Result<(String, String), String> {
721 let side = |path: &str| {
722 lean_ctx_server::tools::ctx_read::read_file_lossy_admitted_for_cli(path)
723 .map(|source| source.text)
724 .map_err(|e| format!("Error reading {path}: {e}"))
725 };
726 Ok((side(path1)?, side(path2)?))
727}
728
729fn local_diff(path1: &str, path2: &str) -> CommandOutput {
730 let (content1, content2) = match admitted_diff_sides(path1, path2) {
731 Ok(sides) => sides,
732 Err(message) => {
733 eprintln!("{message}");
734 return CommandOutput::local(1, None);
735 }
736 };
737
738 let diff = compressor::diff_content(&content1, &content2);
739 let original = count_tokens(&content1) + count_tokens(&content2);
740 let sent = count_tokens(&diff);
741
742 println!(
743 "diff {} {}",
744 protocol::shorten_path(path1),
745 protocol::shorten_path(path2)
746 );
747 println!("{diff}");
748 print_savings(original, sent);
749 CommandOutput::local(
750 0,
751 Some(Recording::Stats {
752 tool: "cli_diff",
753 input_tokens: original,
754 output_tokens: sent,
755 }),
756 )
757}
758
759pub fn cmd_grep(args: &[String]) {
760 let output =
761 super::context_execution::execute(super::context_execution::ContextCommand::Grep, args);
762 if output.exit_code != 0 {
763 std::process::exit(output.exit_code);
764 }
765}
766
767pub(crate) fn observe_grep<'a>(
768 args: &'a [String],
769 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
770) -> CommandOutput {
771 if args.is_empty() {
772 eprintln!("Usage: lean-ctx grep <pattern> [path]");
773 return CommandOutput::rejected(1);
774 }
775
776 let pattern = args[0].clone();
777 let raw_path = args.get(1).map_or(".", std::string::String::as_str);
778 let path = resolve_cli_path(raw_path);
779
780 #[cfg(unix)]
781 if !lean_ctx::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
782 match lean_ctx::daemon_client::try_daemon_tool_call_blocking_observed(
783 "ctx_search",
784 Some(serde_json::json!({
785 "pattern": pattern.clone(),
786 "path": path.clone(),
787 })),
788 ) {
789 lean_ctx::daemon_client::DaemonToolCallOutcome::Unavailable => {}
790 lean_ctx::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
791 let out = super::common::filter_daemon_output(&text);
792 let exit_code = if is_error { 2 } else { grep_exit_status(&out) };
793 let arguments =
794 tool_arguments(serde_json::json!({ "pattern": pattern, "path": path }));
795 if let Some(released) = released_daemon_result(
796 "ctx_search",
797 &super::common::detect_project_root(&[]),
798 Some(&arguments),
799 false,
800 out,
801 is_error,
802 ) {
803 super::common::print_released(&released);
804 }
805 return CommandOutput::daemon(exit_code);
806 }
807 lean_ctx::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
808 eprintln!("Error: daemon result uncertain: {message}");
809 return CommandOutput::daemon(2);
810 }
811 }
812 }
813 super::common::daemon_fallback_hint();
814
815 let search_arguments = tool_arguments(serde_json::json!({ "pattern": pattern, "path": path }));
818 run_local(Box::new(move || {
819 let project_root = super::common::detect_project_root(&[]);
820 deliver_carrier(
821 "ctx_search",
822 &project_root,
823 Some(&search_arguments),
824 false,
825 |out| local_grep(pattern, path, out),
826 )
827 }))
828}
829
830fn local_grep(pattern: String, path: String, stdout: &mut Stdout) -> CommandOutput {
831 let search_start = std::time::Instant::now();
833
834 let outcome = lean_ctx_server::tools::ctx_search::handle(
835 &pattern,
836 &path,
837 None,
838 20,
839 lean_ctx_server::tools::CrpMode::effective(),
840 true,
841 roles::active_role().io.allow_secret_paths,
842 false,
843 );
844 let failed = outcome.failed;
845 let out = outcome.text;
846 stdout.line(&out);
847 let output_tokens = count_tokens(&out);
848 let exit_code = if failed { 2 } else { grep_exit_status(&out) };
849 CommandOutput::local(
850 exit_code,
851 Some(Recording::Search {
852 modeled_baseline: outcome.modeled_baseline,
853 observed_tokens: outcome.observed_tokens,
854 output_tokens,
855 pattern,
856 path,
857 elapsed: search_start.elapsed(),
858 excerpt: excerpt(&out),
859 }),
860 )
861}
862
863fn grep_exit_status(out: &str) -> i32 {
870 let out = out.trim_start();
871 if out.starts_with("ERROR") {
872 return 2;
873 }
874 if !out.starts_with("0 matches") {
875 return 0;
876 }
877 if out.contains("skipped") || out.contains("stopped") {
878 2
879 } else {
880 1
881 }
882}
883
884pub fn cmd_glob(args: &[String]) {
889 let output =
890 super::context_execution::execute(super::context_execution::ContextCommand::Glob, args);
891 if output.exit_code != 0 {
892 std::process::exit(output.exit_code);
893 }
894}
895
896#[cfg(unix)]
899fn print_daemon_listing(tool: &str, text: String, is_error: bool) {
900 let project_root = super::common::detect_project_root(&[]);
901 if let Some(released) = released_daemon_result(tool, &project_root, None, true, text, is_error)
902 {
903 super::common::print_released(&released);
904 }
905}
906
907pub(crate) fn observe_glob<'a>(
908 args: &'a [String],
909 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
910) -> CommandOutput {
911 if args.is_empty() {
912 eprintln!("Usage: lean-ctx glob <pattern> [path]");
913 return CommandOutput::rejected(1);
914 }
915
916 let pattern = args[0].clone();
917 let raw_path = args.get(1).map_or(".", std::string::String::as_str);
918 let path = resolve_cli_path(raw_path);
919
920 #[cfg(unix)]
921 if !lean_ctx::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
922 match lean_ctx::daemon_client::try_daemon_tool_call_blocking_observed(
923 "ctx_glob",
924 Some(serde_json::json!({
925 "pattern": pattern.clone(),
926 "path": path.clone(),
927 })),
928 ) {
929 lean_ctx::daemon_client::DaemonToolCallOutcome::Unavailable => {}
930 lean_ctx::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
931 let out = super::common::filter_daemon_output(&text);
932 print_daemon_listing("ctx_glob", out, is_error);
933 return CommandOutput::daemon(i32::from(is_error));
934 }
935 lean_ctx::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
936 eprintln!("Error: daemon result uncertain: {message}");
937 return CommandOutput::daemon(1);
938 }
939 }
940 }
941 super::common::daemon_fallback_hint();
942
943 run_local(Box::new(move || {
944 let project_root = super::common::detect_project_root(&[]);
945 deliver_carrier("ctx_glob", &project_root, None, true, |out| {
947 local_glob(&pattern, &path, out)
948 })
949 }))
950}
951
952fn local_glob(pattern: &str, path: &str, stdout: &mut Stdout) -> CommandOutput {
953 let (out, _original) = lean_ctx_server::tools::ctx_glob::handle(
954 pattern,
955 path,
956 true,
957 roles::active_role().io.allow_secret_paths,
958 200,
959 );
960 stdout.line(&out);
961 let exit_code = i32::from(out.starts_with("ERROR:"));
962 CommandOutput::local(
963 exit_code,
964 Some(Recording::Stats {
965 tool: "cli_glob",
966 input_tokens: 0,
967 output_tokens: 0,
968 }),
969 )
970}
971
972pub fn cmd_find(args: &[String]) {
973 let output =
974 super::context_execution::execute(super::context_execution::ContextCommand::Find, args);
975 if output.exit_code != 0 {
976 std::process::exit(output.exit_code);
977 }
978}
979
980pub(crate) fn observe_find<'a>(
981 args: &'a [String],
982 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
983) -> CommandOutput {
984 if args.is_empty() {
985 eprintln!("Usage: lean-ctx find <pattern> [path]");
986 return CommandOutput::rejected(1);
987 }
988
989 let raw_pattern = args[0].clone();
990 let path = args
991 .get(1)
992 .map_or(".", std::string::String::as_str)
993 .to_string();
994 run_local(Box::new(move || local_find(&raw_pattern, &path)))
995}
996
997fn local_find(raw_pattern: &str, path: &str) -> CommandOutput {
998 let is_glob = raw_pattern.contains('*') || raw_pattern.contains('?');
999 let glob_matcher = if is_glob {
1000 glob::Pattern::new(&raw_pattern.to_lowercase()).ok()
1001 } else {
1002 None
1003 };
1004 let substring = raw_pattern.to_lowercase();
1005
1006 let mut found = false;
1007 let walk_root = lean_ctx::core::walk_filter::explicit_walk_root(Path::new(path));
1008 for entry in ignore::WalkBuilder::new(&walk_root)
1009 .hidden(lean_ctx::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
1012 .git_ignore(true)
1013 .git_global(true)
1014 .git_exclude(true)
1015 .require_git(false)
1016 .max_depth(Some(10))
1017 .filter_entry(lean_ctx::core::walk_filter::keep_entry)
1018 .build()
1019 .flatten()
1020 {
1021 let name = entry.file_name().to_string_lossy().to_lowercase();
1022 let matches = if let Some(ref g) = glob_matcher {
1023 g.matches(&name)
1024 } else {
1025 name.contains(&substring)
1026 };
1027 if matches {
1028 println!("{}", entry.path().display());
1029 found = true;
1030 }
1031 }
1032
1033 CommandOutput::local(
1034 i32::from(!found),
1035 Some(Recording::Stats {
1036 tool: "cli_find",
1037 input_tokens: 0,
1038 output_tokens: 0,
1039 }),
1040 )
1041}
1042
1043pub fn cmd_ls(args: &[String]) {
1044 let output =
1045 super::context_execution::execute(super::context_execution::ContextCommand::Ls, args);
1046 if output.exit_code != 0 {
1047 std::process::exit(output.exit_code);
1048 }
1049}
1050
1051pub(crate) fn observe_ls<'a>(
1052 args: &'a [String],
1053 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
1054) -> CommandOutput {
1055 let mut raw_path = ".".to_string();
1056 let mut depth = 3usize;
1057 let mut show_hidden = false;
1058 let mut respect_gitignore = true;
1059 let mut i = 0;
1060
1061 while i < args.len() {
1062 let arg = &args[i];
1063 if arg == "--depth" {
1064 i += 1;
1065 if let Some(d) = args.get(i).and_then(|s| s.parse::<usize>().ok()) {
1066 depth = d.min(10);
1067 }
1068 } else if arg == "--all" || arg == "-a" {
1069 show_hidden = true;
1070 } else if arg == "--no-gitignore" {
1071 respect_gitignore = false;
1072 } else if arg.starts_with('-') {
1073 eprintln!("Error: lean-ctx ls does not support flag '{arg}'.\n");
1074 eprintln!(
1075 "lean-ctx ls is a compressed directory tree viewer for AI context, not a drop-in ls replacement."
1076 );
1077 eprintln!(
1078 "The shell hook (lean-ctx -t ls {arg} ...) passes flags to system ls transparently.\n"
1079 );
1080 eprintln!("Usage: lean-ctx ls [path] [--depth N] [--all] [--no-gitignore]");
1081 return CommandOutput::rejected(1);
1082 } else {
1083 raw_path.clone_from(arg);
1084 }
1085 i += 1;
1086 }
1087
1088 let abs_path = resolve_cli_path(&raw_path);
1089 let path = abs_path;
1090
1091 #[cfg(unix)]
1092 if !lean_ctx::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
1093 match lean_ctx::daemon_client::try_daemon_tool_call_blocking_observed(
1094 "ctx_tree",
1095 Some(serde_json::json!({
1096 "path": path.clone(),
1097 "depth": depth,
1098 "show_hidden": show_hidden,
1099 "respect_gitignore": respect_gitignore,
1100 })),
1101 ) {
1102 lean_ctx::daemon_client::DaemonToolCallOutcome::Unavailable => {}
1103 lean_ctx::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
1104 let out = super::common::filter_daemon_output(&text);
1105 print_daemon_listing("ctx_tree", out, is_error);
1106 return CommandOutput::daemon(i32::from(is_error));
1107 }
1108 lean_ctx::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
1109 eprintln!("Error: daemon result uncertain: {message}");
1110 return CommandOutput::daemon(1);
1111 }
1112 }
1113 }
1114 super::common::daemon_fallback_hint();
1115
1116 run_local(Box::new(move || {
1117 let project_root = super::common::detect_project_root(&[]);
1118 deliver_carrier("ctx_tree", &project_root, None, true, |out| {
1120 local_ls(&path, depth, show_hidden, respect_gitignore, out)
1121 })
1122 }))
1123}
1124
1125fn local_ls(
1126 path: &str,
1127 depth: usize,
1128 show_hidden: bool,
1129 respect_gitignore: bool,
1130 stdout: &mut Stdout,
1131) -> CommandOutput {
1132 let (out, original) =
1133 lean_ctx_server::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
1134 if out.starts_with("ERROR:") {
1135 eprintln!("{out}");
1136 std::process::exit(1);
1137 }
1138 stdout.line(&out);
1139 CommandOutput::local(
1140 0,
1141 Some(Recording::Tree {
1142 input_tokens: original,
1143 output_tokens: count_tokens(&out),
1144 }),
1145 )
1146}
1147
1148pub fn cmd_deps(args: &[String]) {
1149 let output =
1150 super::context_execution::execute(super::context_execution::ContextCommand::Deps, args);
1151 if output.exit_code != 0 {
1152 std::process::exit(output.exit_code);
1153 }
1154}
1155
1156pub(crate) fn observe_deps<'a>(
1157 args: &'a [String],
1158 run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
1159) -> CommandOutput {
1160 let path = args
1161 .first()
1162 .map_or(".", std::string::String::as_str)
1163 .to_string();
1164 run_local(Box::new(move || local_deps(&path)))
1165}
1166
1167fn local_deps(path: &str) -> CommandOutput {
1168 if let Some(result) = deps_cmd::detect_and_compress(path) {
1169 println!("{result}");
1170 CommandOutput::local(
1171 0,
1172 Some(Recording::Stats {
1173 tool: "cli_deps",
1174 input_tokens: 0,
1175 output_tokens: 0,
1176 }),
1177 )
1178 } else {
1179 eprintln!("No dependency file found in {path}");
1180 CommandOutput::local(1, None)
1181 }
1182}
1183
1184#[cfg(test)]
1185#[path = "read_cmd_adapter_tests.rs"]
1186mod adapter_tests;
1187
1188#[cfg(test)]
1189#[path = "read_cmd_tests.rs"]
1190mod tests;