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