Skip to main content

lean_ctx/cli/
read_cmd.rs

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/// Detect daemon results that indicate a read failure — the CLI should fall
13/// through to standalone (which runs as the user's process, not sandboxed).
14/// Catches: explicit tool errors, `"file.rs 0L"` stubs, and read-handler
15/// failures. A daemon is rooted at its startup project, so an absolute path from
16/// another CLI caller can be valid locally while the shared daemon rejects it.
17#[cfg(unix)]
18fn is_failed_daemon_result(output: &str) -> bool {
19    let first_line = output.lines().next().unwrap_or("");
20    if first_line.starts_with("ERROR:") {
21        return true;
22    }
23    if first_line.starts_with("Cannot read file:") || first_line.starts_with("File is empty:") {
24        return true;
25    }
26    if !first_line.ends_with(" 0L") {
27        return false;
28    }
29    let body: String = output
30        .lines()
31        .skip(1)
32        .filter(|l| {
33            let t = l.trim();
34            !t.is_empty()
35                && !t.starts_with("[no extractable structure")
36                && !t.starts_with("[lean-ctx]")
37                && !t.starts_with('[')
38        })
39        .collect();
40    body.is_empty()
41}
42
43fn resolve_cli_path(raw: &str) -> String {
44    if let Ok(abs) = std::path::Path::new(raw).canonicalize() {
45        return abs.to_string_lossy().to_string();
46    }
47    if Path::new(raw).is_relative()
48        && let Ok(cwd) = std::env::current_dir()
49    {
50        return cwd.join(raw).to_string_lossy().into_owned();
51    }
52    raw.to_string()
53}
54use crate::core::tokens::count_tokens;
55
56use super::common::print_savings;
57
58/// #361 anti-inflation guarantee for the additive one-shot CLI path (the pi
59/// default an independent benchmark measured). Mirrors the MCP `cap_to_raw`
60/// invariant: a read must never cost more tokens than the raw file, so when the
61/// framing (`short [NL]` header, deps/API summary, savings footer) would push
62/// the payload past the bare content we ship the content verbatim. Empty files
63/// keep their framing so the reader still gets a signal.
64fn cap_cli_to_raw(framed: String, raw_content: &str, raw_tokens: usize) -> String {
65    if raw_tokens > 0 && count_tokens(&framed) > raw_tokens {
66        raw_content.to_string()
67    } else {
68        framed
69    }
70}
71
72/// Whether the read must bypass all caches and return verbatim content. True for
73/// explicit `--fresh`/`--no-cache` and for hook children (`hook_child`), whose
74/// `-m full` output is piped into a temp file the host reads back as the file's
75/// content and must never be a `cached … [NL]` stub (#1037).
76fn should_force_fresh(args: &[String], hook_child: bool) -> bool {
77    hook_child || args.iter().any(|a| a == "--fresh" || a == "--no-cache")
78}
79
80/// Resolve the read mode from CLI args. `--mode`/`-m` wins; otherwise the
81/// first positional after the path that parses as a known mode counts — a bare
82/// `lean-ctx read f.ps1 map` used to silently serve the `auto` default instead
83/// of the requested view (limitations audit 2026-07-03). Unknown positionals
84/// and flags are left alone so existing invocations keep their meaning.
85fn resolve_cli_read_mode(args: &[String]) -> &str {
86    if let Some(m) = args
87        .iter()
88        .position(|a| a == "--mode" || a == "-m")
89        .and_then(|i| args.get(i + 1))
90    {
91        return m.as_str();
92    }
93    args.iter()
94        .skip(1)
95        .find(|a| !a.starts_with('-') && a.parse::<crate::tools::ctx_read::ReadMode>().is_ok())
96        .map_or("auto", std::string::String::as_str)
97}
98
99pub fn cmd_read(args: &[String]) {
100    if args.is_empty() {
101        eprintln!(
102            "Usage: lean-ctx read <file> [--mode auto|full|map|signatures|aggressive|entropy|lines:N-M|lines:-N] [--fresh]"
103        );
104        std::process::exit(1);
105    }
106
107    let raw_path = &args[0];
108    let path = if Path::new(raw_path).is_relative() {
109        std::env::current_dir().ok().map_or_else(
110            || raw_path.clone(),
111            |cwd| cwd.join(raw_path).to_string_lossy().into_owned(),
112        )
113    } else {
114        raw_path.clone()
115    };
116    let path = path.as_str();
117    let mode = resolve_cli_read_mode(args);
118    // #1037: redirect/rewrite hook children pipe `-m full` output into a temp file the
119    // host reads back AS the file's content, so a `cached <file> [NL]` cache-hit stub
120    // corrupts the read (and round-trips the stub into the real file on the next edit).
121    // The hook env (set by `mark_hook_environment`, inherited by the subprocess) forces
122    // verbatim content on BOTH the daemon (`fresh:true`) and standalone (skip cli_cache)
123    // paths. Direct CLI/MCP reads keep caching.
124    let force_fresh = should_force_fresh(args, crate::core::runtime_flags::hook_child_enabled());
125    // Whether *we* choose the mode (auto): only then do we cap framing to raw.
126    // An explicit mode is a deliberate view we return verbatim (#361).
127    let requested_auto = mode == "auto";
128
129    let short = protocol::shorten_path(path);
130
131    // Apply the same secret-path policy in CLI mode as in MCP tools.
132    // Default is warn; enforce depends on active role/policy.
133    if let Ok(abs) = std::fs::canonicalize(path) {
134        match io_boundary::check_secret_path_for_tool("cli_read", &abs) {
135            Ok(Some(w)) => eprintln!("{w}"),
136            Ok(None) => {}
137            Err(e) => {
138                eprintln!("{e}");
139                std::process::exit(1);
140            }
141        }
142    } else {
143        // Best-effort: still check the raw path string.
144        let raw = std::path::Path::new(path);
145        match io_boundary::check_secret_path_for_tool("cli_read", raw) {
146            Ok(Some(w)) => eprintln!("{w}"),
147            Ok(None) => {}
148            Err(e) => {
149                eprintln!("{e}");
150                std::process::exit(1);
151            }
152        }
153    }
154
155    #[cfg(unix)]
156    {
157        #[cfg(unix)]
158        if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
159            && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
160                "ctx_read",
161                Some(serde_json::json!({
162                    "path": path,
163                    "mode": mode,
164                    "fresh": force_fresh,
165                })),
166            )
167        {
168            let filtered = super::common::filter_daemon_output(&out);
169            if !filtered.trim().is_empty() && !is_failed_daemon_result(&filtered) {
170                println!("{filtered}");
171                return;
172            }
173            // else: fall through to standalone path
174        }
175    }
176    super::common::daemon_fallback_hint();
177
178    // Read latency for the Context IR lineage (#566) — the standalone path only;
179    // the daemon branch above records its own IR and returns before this.
180    let read_start = std::time::Instant::now();
181
182    if !force_fresh && mode == "full" {
183        use crate::core::cli_cache::{self, CacheResult};
184        match cli_cache::check_and_read(path) {
185            CacheResult::Hit { entry, file_ref } => {
186                let msg = cli_cache::format_hit(&entry, &file_ref, &short);
187                println!("{msg}");
188                let sent = count_tokens(&msg);
189                super::common::cli_track_read_cached(
190                    path,
191                    "full",
192                    entry.original_tokens,
193                    sent,
194                    &msg,
195                    read_start.elapsed(),
196                );
197                return;
198            }
199            CacheResult::Miss { content } if content.is_empty() => {
200                eprintln!("Error: could not read {path}");
201                std::process::exit(1);
202            }
203            CacheResult::Miss { content } => {
204                let line_count = content.lines().count();
205                let raw_tokens = count_tokens(&content);
206                let framed = format!("{short} [{line_count}L]\n{content}");
207                let output = cap_cli_to_raw(framed, &content, raw_tokens);
208                println!("{output}");
209                let sent = count_tokens(&output);
210                super::common::cli_track_read(
211                    path,
212                    "full",
213                    raw_tokens,
214                    sent,
215                    &output,
216                    read_start.elapsed(),
217                );
218                return;
219            }
220        }
221    }
222
223    let content = match crate::tools::ctx_read::read_file_lossy(path) {
224        Ok(c) => c,
225        Err(e) => {
226            eprintln!("Error: {e}");
227            std::process::exit(1);
228        }
229    };
230
231    let ext = Path::new(path)
232        .extension()
233        .and_then(|e| e.to_str())
234        .unwrap_or("");
235    let line_count = content.lines().count();
236    let original_tokens = count_tokens(&content);
237
238    let mode = if mode == "auto" {
239        // Unified resolver — the single source of truth shared with the MCP
240        // path. The old CLI-local predictor lacked the small-file / config /
241        // instruction guards, so auto could pick a compressing mode that
242        // inflated a tiny file. Routing through `resolve` fixes that at the
243        // source (#361).
244        crate::core::auto_mode_resolver::resolve(
245            &crate::core::auto_mode_resolver::AutoModeContext {
246                path,
247                token_count: original_tokens,
248                line_count: None,
249                task: None,
250                cache: None,
251            },
252        )
253        .mode
254    } else if mode != "full" && crate::tools::ctx_read::is_instruction_file(path) {
255        "full".to_string()
256    } else {
257        mode.to_string()
258    };
259    let mode = if (mode == "map" || mode == "signatures") && original_tokens <= 400 {
260        "full".to_string()
261    } else {
262        mode
263    };
264    let mode = mode.as_str();
265
266    match mode {
267        "map" => {
268            let structured = match ext {
269                "md" | "mdx" | "rst" => {
270                    crate::core::structured_read::extract_markdown_outline(&content)
271                }
272                "json" => crate::core::structured_read::extract_json_structure(&content),
273                "yaml" | "yml" => crate::core::structured_read::extract_yaml_structure(&content),
274                "toml" => crate::core::structured_read::extract_toml_structure(&content),
275                _ if path.to_lowercase().ends_with(".lock")
276                    || path.to_lowercase().ends_with("go.sum") =>
277                {
278                    crate::core::structured_read::extract_lock_summary(&content, path)
279                }
280                _ => String::new(),
281            };
282
283            let mut output_buf = if structured.is_empty() {
284                let sigs = signatures::extract_signatures(&content, ext);
285                let dep_info = dep_extract::extract_deps(&content, ext);
286                let mut buf = format!("{short} [{line_count}L]");
287                if !dep_info.imports.is_empty() {
288                    buf.push_str(&format!("\n  deps: {}", dep_info.imports.join(", ")));
289                }
290                let key_sigs: Vec<&signatures::Signature> = sigs
291                    .iter()
292                    .filter(|s| s.is_exported || s.indent == 0)
293                    .collect();
294                // Drop exports the API section already lists (same symbol in a
295                // fuller form) so map drops the duplicate names — mirrors the
296                // MCP map renderer in ctx_read::render (#361).
297                let extra_exports =
298                    signatures::exports_not_in_signatures(&dep_info.exports, &key_sigs);
299                if !extra_exports.is_empty() {
300                    buf.push_str(&format!("\n  exports: {}", extra_exports.join(", ")));
301                }
302                if !key_sigs.is_empty() {
303                    buf.push_str("\n  API:");
304                    for sig in &key_sigs {
305                        buf.push_str(&format!("\n    {}", sig.to_compact_located()));
306                    }
307                }
308                // Same honesty rule as the MCP renderer: an information-free
309                // map must say so (limitations audit, #4).
310                if key_sigs.is_empty() && dep_info.imports.is_empty() && extra_exports.is_empty() {
311                    buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
312                }
313                buf
314            } else {
315                format!("{short} [{line_count}L]\n{structured}")
316            };
317
318            let sent = count_tokens(&output_buf);
319            output_buf = protocol::append_savings(&output_buf, original_tokens, sent);
320            if requested_auto {
321                output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
322            }
323            let sent = count_tokens(&output_buf);
324            println!("{output_buf}");
325            super::common::cli_track_read(
326                path,
327                "map",
328                original_tokens,
329                sent,
330                &output_buf,
331                read_start.elapsed(),
332            );
333        }
334        "signatures" => {
335            let sigs = signatures::extract_signatures(&content, ext);
336            let mut output_buf = format!("{short} [{line_count}L]");
337            for sig in &sigs {
338                output_buf.push_str(&format!("\n{}", sig.to_compact_located()));
339            }
340            // Same honesty rule as the MCP renderer (limitations audit, #4).
341            if sigs.is_empty() {
342                output_buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
343            }
344            if requested_auto {
345                output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
346            }
347            println!("{output_buf}");
348            let sent = count_tokens(&output_buf);
349            print_savings(original_tokens, sent);
350            super::common::cli_track_read(
351                path,
352                "signatures",
353                original_tokens,
354                sent,
355                &output_buf,
356                read_start.elapsed(),
357            );
358        }
359        "aggressive" => {
360            let compressed = compressor::aggressive_compress(&content, Some(ext));
361            println!("{short} [{line_count}L]");
362            println!("{compressed}");
363            let sent = count_tokens(&compressed);
364            print_savings(original_tokens, sent);
365            super::common::cli_track_read(
366                path,
367                "aggressive",
368                original_tokens,
369                sent,
370                &compressed,
371                read_start.elapsed(),
372            );
373        }
374        "entropy" => {
375            let result = entropy::entropy_compress(&content);
376            let avg_h = entropy::analyze_entropy(&content).avg_entropy;
377            println!("{short} [{line_count}L] (H̄={avg_h:.1})");
378            for tech in &result.techniques {
379                println!("{tech}");
380            }
381            println!("{}", result.output);
382            let sent = count_tokens(&result.output);
383            print_savings(original_tokens, sent);
384            super::common::cli_track_read(
385                path,
386                "entropy",
387                original_tokens,
388                sent,
389                &result.output,
390                read_start.elapsed(),
391            );
392        }
393        m if m.starts_with("lines:") => {
394            // The CLI used to drop the window and print the whole file — a
395            // `lines:` read must return the requested selection, with the same
396            // comma-multi-select hint as the MCP renderer (limitations #7).
397            let range_str = &m[6..];
398            let extracted = crate::tools::ctx_read::extract_line_range(&content, range_str);
399            let multi_hint = if range_str.contains(',') {
400                crate::tools::ctx_read::LINES_COMMA_HINT
401            } else {
402                ""
403            };
404            let output =
405                format!("{short} [{line_count}L] lines:{range_str}\n{extracted}{multi_hint}");
406            println!("{output}");
407            let sent = count_tokens(&output);
408            print_savings(original_tokens, sent);
409            super::common::cli_track_read(
410                path,
411                "lines",
412                original_tokens,
413                sent,
414                &output,
415                read_start.elapsed(),
416            );
417        }
418        "cognitive" | "mdl" => {
419            let (output, _) = crate::tools::ctx_read::process_mode(
420                &content,
421                mode,
422                "",
423                &short,
424                ext,
425                original_tokens,
426                crate::core::protocol::CrpMode::Off,
427                path,
428                None,
429            );
430            let output = if requested_auto {
431                cap_cli_to_raw(output, &content, original_tokens)
432            } else {
433                output
434            };
435            let sent = count_tokens(&output);
436            println!("{output}");
437            print_savings(original_tokens, sent);
438            super::common::cli_track_read(
439                path,
440                mode,
441                original_tokens,
442                sent,
443                &output,
444                read_start.elapsed(),
445            );
446        }
447        _ => {
448            // `full` and any unrecognized mode land here. These are
449            // verbatim reads — the prose terse pipeline would mangle source
450            // (dictionary substitutions, line-drop dedup) and break a `full`
451            // read's "complete content" contract, so it must never run here
452            // (#404). Intentionally-lossy modes (map/signatures/aggressive/
453            // entropy/lines) have their own arms above.
454            let mut output = format!("{short} [{line_count}L]\n{content}");
455            if !crate::core::terse::is_verbatim_read("ctx_read", Some(mode)) {
456                let config = crate::core::config::Config::load();
457                let level = crate::core::config::CompressionLevel::effective(&config);
458                if level.is_active() {
459                    let terse_result =
460                        crate::core::terse::pipeline::compress(&output, &level, None);
461                    if terse_result.quality_passed && terse_result.savings_pct >= 3.0 {
462                        output = terse_result.output;
463                    }
464                }
465            }
466            // Full/verbatim reads never beat raw via framing — if terse didn't
467            // compress below the bare file, ship the file itself (#361).
468            let output = cap_cli_to_raw(output, &content, original_tokens);
469            println!("{output}");
470            let sent = count_tokens(&output);
471            super::common::cli_track_read(
472                path,
473                "full",
474                original_tokens,
475                sent,
476                &output,
477                read_start.elapsed(),
478            );
479        }
480    }
481}
482
483pub fn cmd_diff(args: &[String]) {
484    if args.len() < 2 {
485        eprintln!("Usage: lean-ctx diff <file1> <file2>");
486        std::process::exit(1);
487    }
488
489    let content1 = match crate::tools::ctx_read::read_file_lossy(&args[0]) {
490        Ok(c) => c,
491        Err(e) => {
492            eprintln!("Error reading {}: {e}", args[0]);
493            std::process::exit(1);
494        }
495    };
496
497    let content2 = match crate::tools::ctx_read::read_file_lossy(&args[1]) {
498        Ok(c) => c,
499        Err(e) => {
500            eprintln!("Error reading {}: {e}", args[1]);
501            std::process::exit(1);
502        }
503    };
504
505    let diff = compressor::diff_content(&content1, &content2);
506    let original = count_tokens(&content1) + count_tokens(&content2);
507    let sent = count_tokens(&diff);
508
509    println!(
510        "diff {} {}",
511        protocol::shorten_path(&args[0]),
512        protocol::shorten_path(&args[1])
513    );
514    println!("{diff}");
515    print_savings(original, sent);
516    crate::core::stats::record("cli_diff", original, sent);
517}
518
519pub fn cmd_grep(args: &[String]) {
520    if args.is_empty() {
521        eprintln!("Usage: lean-ctx grep <pattern> [path]");
522        std::process::exit(1);
523    }
524
525    let pattern = &args[0];
526    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
527    let abs_path = resolve_cli_path(raw_path);
528    let path = abs_path.as_str();
529
530    #[cfg(unix)]
531    {
532        #[cfg(unix)]
533        if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
534            && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
535                "ctx_search",
536                Some(serde_json::json!({
537                    "pattern": pattern,
538                    "path": path,
539                })),
540            )
541        {
542            let out = super::common::filter_daemon_output(&out);
543            println!("{out}");
544            if out.trim_start().starts_with("0 matches") {
545                std::process::exit(1);
546            }
547            return;
548        }
549    }
550    super::common::daemon_fallback_hint();
551
552    // Search latency for the Context IR lineage (#566), standalone path only.
553    let search_start = std::time::Instant::now();
554
555    let outcome = crate::tools::ctx_search::handle(
556        pattern,
557        path,
558        None,
559        20,
560        crate::tools::CrpMode::effective(),
561        true,
562        roles::active_role().io.allow_secret_paths,
563        false,
564    );
565    let out = outcome.text;
566    println!("{out}");
567    super::common::cli_track_search(
568        outcome.modeled_baseline,
569        outcome.observed_tokens,
570        count_tokens(&out),
571        pattern,
572        path,
573        &out,
574        search_start.elapsed(),
575    );
576    if outcome.modeled_baseline == 0 && out.trim_start().starts_with("0 matches") {
577        std::process::exit(1);
578    }
579}
580
581/// `lean-ctx glob <pattern> [path]` — find files by glob pattern, shares the
582/// exact `ctx_glob` core so the CLI, the MCP tool, and the shadow-mode redirect
583/// (#556) all return identical results. Prefers the daemon (warms its cache),
584/// falling back to an in-process call.
585pub fn cmd_glob(args: &[String]) {
586    if args.is_empty() {
587        eprintln!("Usage: lean-ctx glob <pattern> [path]");
588        std::process::exit(1);
589    }
590
591    let pattern = &args[0];
592    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
593    let abs_path = resolve_cli_path(raw_path);
594    let path = abs_path.as_str();
595
596    #[cfg(unix)]
597    if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
598        && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
599            "ctx_glob",
600            Some(serde_json::json!({
601                "pattern": pattern,
602                "path": path,
603            })),
604        )
605    {
606        let out = super::common::filter_daemon_output(&out);
607        println!("{out}");
608        return;
609    }
610    super::common::daemon_fallback_hint();
611
612    let (out, _original) = crate::tools::ctx_glob::handle(
613        pattern,
614        path,
615        true,
616        roles::active_role().io.allow_secret_paths,
617        200,
618    );
619    println!("{out}");
620    crate::core::stats::record("cli_glob", 0, 0);
621    if out.starts_with("ERROR:") {
622        std::process::exit(1);
623    }
624}
625
626pub fn cmd_find(args: &[String]) {
627    if args.is_empty() {
628        eprintln!("Usage: lean-ctx find <pattern> [path]");
629        std::process::exit(1);
630    }
631
632    let raw_pattern = &args[0];
633    let path = args.get(1).map_or(".", std::string::String::as_str);
634
635    let is_glob = raw_pattern.contains('*') || raw_pattern.contains('?');
636    let glob_matcher = if is_glob {
637        glob::Pattern::new(&raw_pattern.to_lowercase()).ok()
638    } else {
639        None
640    };
641    let substring = raw_pattern.to_lowercase();
642
643    let mut found = false;
644    let walk_root = crate::core::walk_filter::explicit_walk_root(std::path::Path::new(path));
645    for entry in ignore::WalkBuilder::new(&walk_root)
646        .hidden(true)
647        .git_ignore(true)
648        .git_global(true)
649        .git_exclude(true)
650        .require_git(false)
651        .max_depth(Some(10))
652        .filter_entry(crate::core::walk_filter::keep_entry)
653        .build()
654        .flatten()
655    {
656        let name = entry.file_name().to_string_lossy().to_lowercase();
657        let matches = if let Some(ref g) = glob_matcher {
658            g.matches(&name)
659        } else {
660            name.contains(&substring)
661        };
662        if matches {
663            println!("{}", entry.path().display());
664            found = true;
665        }
666    }
667
668    crate::core::stats::record("cli_find", 0, 0);
669
670    if !found {
671        std::process::exit(1);
672    }
673}
674
675pub fn cmd_ls(args: &[String]) {
676    let mut raw_path = ".";
677    let mut depth = 3usize;
678    let mut show_hidden = false;
679    let mut respect_gitignore = true;
680    let mut i = 0;
681
682    while i < args.len() {
683        let arg = &args[i];
684        if arg == "--depth" {
685            i += 1;
686            if let Some(d) = args.get(i).and_then(|s| s.parse::<usize>().ok()) {
687                depth = d.min(10);
688            }
689        } else if arg == "--all" || arg == "-a" {
690            show_hidden = true;
691        } else if arg == "--no-gitignore" {
692            respect_gitignore = false;
693        } else if arg.starts_with('-') {
694            eprintln!("Error: lean-ctx ls does not support flag '{arg}'.\n");
695            eprintln!(
696                "lean-ctx ls is a compressed directory tree viewer for AI context, not a drop-in ls replacement."
697            );
698            eprintln!(
699                "The shell hook (lean-ctx -t ls {arg} ...) passes flags to system ls transparently.\n"
700            );
701            eprintln!("Usage: lean-ctx ls [path] [--depth N] [--all] [--no-gitignore]");
702            std::process::exit(1);
703        } else {
704            raw_path = arg;
705        }
706        i += 1;
707    }
708
709    let abs_path = resolve_cli_path(raw_path);
710    let path = abs_path.as_str();
711
712    #[cfg(unix)]
713    {
714        #[cfg(unix)]
715        if !crate::core::pathutil::is_under_tcc_protected_dir(std::path::Path::new(path))
716            && let Some(out) = crate::daemon_client::try_daemon_tool_call_blocking_text(
717                "ctx_tree",
718                Some(serde_json::json!({
719                    "path": path,
720                    "depth": depth,
721                    "show_hidden": show_hidden,
722                    "respect_gitignore": respect_gitignore,
723                })),
724            )
725        {
726            let filtered = super::common::filter_daemon_output(&out);
727            if !filtered.trim().is_empty() && !is_failed_daemon_result(&filtered) {
728                println!("{filtered}");
729                return;
730            }
731        }
732    }
733    super::common::daemon_fallback_hint();
734
735    let (out, original) =
736        crate::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
737    if out.starts_with("ERROR:") {
738        eprintln!("{out}");
739        std::process::exit(1);
740    }
741    println!("{out}");
742    super::common::cli_track_tree(original, count_tokens(&out));
743}
744
745pub fn cmd_deps(args: &[String]) {
746    let path = args.first().map_or(".", std::string::String::as_str);
747
748    if let Some(result) = deps_cmd::detect_and_compress(path) {
749        println!("{result}");
750        crate::core::stats::record("cli_deps", 0, 0);
751    } else {
752        eprintln!("No dependency file found in {path}");
753        std::process::exit(1);
754    }
755}
756
757#[cfg(all(test, unix))]
758mod empty_daemon_tests {
759    use super::is_failed_daemon_result;
760
761    #[test]
762    fn detects_tcc_empty_stub() {
763        assert!(is_failed_daemon_result(
764            "file.rs 0L
765"
766        ));
767        assert!(is_failed_daemon_result(
768            "F1=file.rs 0L
769[lean-ctx: 0 tok saved]"
770        ));
771    }
772
773    #[test]
774    fn accepts_real_content() {
775        assert!(!is_failed_daemon_result(
776            "file.rs 10L
777fn main() {}
778"
779        ));
780    }
781
782    #[test]
783    fn accepts_nonzero_line_count() {
784        assert!(!is_failed_daemon_result(
785            "file.rs 1L
786"
787        ));
788    }
789
790    #[test]
791    fn ignores_structure_markers_in_body() {
792        assert!(is_failed_daemon_result(
793            "file.rs 0L
794[no extractable structure for .rs]
795"
796        ));
797    }
798
799    #[test]
800    fn detects_tcc_restricted_marker() {
801        assert!(is_failed_daemon_result(
802            "ERROR:TCC_RESTRICTED: daemon cannot access /Users/me/Documents/proj (sandboxed)"
803        ));
804    }
805
806    #[test]
807    fn detects_daemon_project_root_denial() {
808        assert!(is_failed_daemon_result(
809            "ERROR: path escapes project root: /work/current/scripts (root: /work/stale)"
810        ));
811    }
812}
813
814#[cfg(test)]
815mod cap_tests {
816    use super::{cap_cli_to_raw, count_tokens};
817
818    #[test]
819    fn caps_to_raw_when_framing_inflates() {
820        // A tiny file: the `path [NL]` header (+ any footer) pushes the framed
821        // payload past the bare content, so the cap must ship the content
822        // verbatim — the additive CLI default must never inflate a read (#361).
823        let raw = "x = 1\n";
824        let raw_tokens = count_tokens(raw);
825        let framed = format!("some/very/long/path/header.rs [1L]\n{raw}\n[lean-ctx: 0 tok saved]");
826        assert!(count_tokens(&framed) > raw_tokens, "fixture must inflate");
827        assert_eq!(cap_cli_to_raw(framed, raw, raw_tokens), raw);
828    }
829
830    #[test]
831    fn keeps_framing_when_it_saves() {
832        // A genuinely compressed payload (fewer tokens than raw) is kept as-is.
833        let raw = "fn a() {}\n".repeat(300);
834        let raw_tokens = count_tokens(&raw);
835        let framed = "f.rs [300L]\nfn a() {} …".to_string();
836        assert!(count_tokens(&framed) < raw_tokens);
837        assert_eq!(cap_cli_to_raw(framed.clone(), &raw, raw_tokens), framed);
838    }
839
840    #[test]
841    fn keeps_framing_for_empty_file() {
842        // raw_tokens == 0 disables the cap so an empty file still gets a signal.
843        let framed = "empty.rs [0L]\n".to_string();
844        assert_eq!(cap_cli_to_raw(framed.clone(), "", 0), framed);
845    }
846
847    #[test]
848    fn break_even_is_not_inflation() {
849        // Equal token counts use strict `>`, so framing is preserved at break-even.
850        let raw = "alpha beta gamma delta";
851        let raw_tokens = count_tokens(raw);
852        let framed = raw.to_string();
853        assert_eq!(count_tokens(&framed), raw_tokens);
854        assert_eq!(cap_cli_to_raw(framed.clone(), raw, raw_tokens), framed);
855    }
856
857    #[test]
858    fn emitted_never_exceeds_raw_across_sizes() {
859        // The invariant itself: for any bloated framing over a non-empty file the
860        // emitted token count is ≤ the raw token count.
861        for n in [1usize, 5, 50, 500] {
862            let raw = "data line here\n".repeat(n);
863            let raw_tokens = count_tokens(&raw);
864            let framed = format!("a/b/c/path.txt [{n}L]\n{raw}\n[lean-ctx: {n} tok saved ({n}%)]");
865            let out = cap_cli_to_raw(framed, &raw, raw_tokens);
866            assert!(
867                count_tokens(&out) <= raw_tokens,
868                "n={n}: emitted {} tok exceeds raw {raw_tokens}",
869                count_tokens(&out)
870            );
871        }
872    }
873}
874
875#[cfg(test)]
876mod fresh_tests {
877    use super::should_force_fresh;
878
879    #[test]
880    fn hook_child_forces_fresh_even_without_flags() {
881        // #1037: a hook child must always read verbatim (no `cached … [NL]` stub),
882        // even when the caller passed no `--fresh`/`--no-cache` flag.
883        assert!(should_force_fresh(&[], true));
884        assert!(!should_force_fresh(&[], false));
885    }
886
887    #[test]
888    fn explicit_flags_force_fresh() {
889        assert!(should_force_fresh(&["--fresh".to_string()], false));
890        assert!(should_force_fresh(&["--no-cache".to_string()], false));
891        assert!(!should_force_fresh(&["file.rs".to_string()], false));
892    }
893}
894
895#[cfg(test)]
896mod mode_arg_tests {
897    use super::resolve_cli_read_mode;
898
899    fn args(list: &[&str]) -> Vec<String> {
900        list.iter().map(ToString::to_string).collect()
901    }
902
903    // `lean-ctx read f.ps1 map` used to silently IGNORE the positional mode and
904    // serve the `auto` default — reads must honour it like `--mode map`
905    // (limitations audit 2026-07-03).
906    #[test]
907    fn positional_mode_is_honoured() {
908        assert_eq!(resolve_cli_read_mode(&args(&["f.ps1", "map"])), "map");
909        assert_eq!(
910            resolve_cli_read_mode(&args(&["f.rs", "lines:5-10"])),
911            "lines:5-10"
912        );
913    }
914
915    #[test]
916    fn mode_flag_wins_over_positional() {
917        assert_eq!(
918            resolve_cli_read_mode(&args(&["f.rs", "map", "--mode", "signatures"])),
919            "signatures"
920        );
921        assert_eq!(
922            resolve_cli_read_mode(&args(&["f.rs", "-m", "full"])),
923            "full"
924        );
925    }
926
927    #[test]
928    fn defaults_to_auto_and_skips_flags_and_junk() {
929        assert_eq!(resolve_cli_read_mode(&args(&["f.rs"])), "auto");
930        assert_eq!(resolve_cli_read_mode(&args(&["f.rs", "--fresh"])), "auto");
931        // An unknown positional is not silently treated as a mode.
932        assert_eq!(resolve_cli_read_mode(&args(&["f.rs", "banana"])), "auto");
933    }
934}