Skip to main content

lean_ctx/cli/
read_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::path::Path;
4
5use crate::core::compressor;
6use crate::core::deps as dep_extract;
7use crate::core::entropy;
8use crate::core::io_boundary;
9use crate::core::patterns::deps_cmd;
10use crate::core::protocol;
11use crate::core::roles;
12use crate::core::signatures;
13
14use super::context_execution::{CommandOutput, LocalOperation, Recording, excerpt};
15
16#[path = "read_cmd_policy.rs"]
17mod policy_read;
18
19#[path = "read_cmd_carrier.rs"]
20mod carrier;
21use carrier::{Stdout, deliver_carrier, tool_arguments};
22
23/// Detect legacy daemon read failures for the exit status. A completed daemon
24/// request must not fall through to standalone and dispatch the operation twice.
25/// Catches: `"file.rs 0L"` stubs and `"Cannot read file:"` handler errors.
26#[cfg(unix)]
27fn is_failed_daemon_result(output: &str) -> bool {
28    let first_line = output.lines().next().unwrap_or("");
29    if first_line.starts_with("ERROR:") {
30        return true;
31    }
32    if first_line.starts_with("Cannot read file:") {
33        return true;
34    }
35    if !first_line.ends_with(" 0L") {
36        return false;
37    }
38    let body: String = output
39        .lines()
40        .skip(1)
41        .filter(|l| {
42            let t = l.trim();
43            !t.is_empty()
44                && !t.starts_with("[no extractable structure")
45                && !t.starts_with("[lean-ctx]")
46                && !t.starts_with('[')
47        })
48        .collect();
49    body.is_empty()
50}
51
52fn resolve_cli_path(raw: &str) -> String {
53    if let Ok(abs) = std::path::Path::new(raw).canonicalize() {
54        return abs.to_string_lossy().to_string();
55    }
56    if Path::new(raw).is_relative()
57        && let Ok(cwd) = std::env::current_dir()
58    {
59        return cwd.join(raw).to_string_lossy().into_owned();
60    }
61    raw.to_string()
62}
63use crate::core::tokens::count_tokens;
64
65use super::common::print_savings;
66
67/// #361 anti-inflation guarantee for the additive one-shot CLI path (the pi
68/// default an independent benchmark measured). Mirrors the MCP `cap_to_raw`
69/// invariant: a read must never cost more tokens than the raw file, so when the
70/// framing (`short [NL]` header, deps/API summary, savings footer) would push
71/// the payload past the bare content we ship the content verbatim. Empty files
72/// keep their framing so the reader still gets a signal.
73fn cap_cli_to_raw(framed: String, raw_content: &str, raw_tokens: usize) -> String {
74    if raw_tokens > 0 && count_tokens(&framed) > raw_tokens {
75        raw_content.to_string()
76    } else {
77        framed
78    }
79}
80
81/// Whether the read must bypass all caches and return verbatim content. True for
82/// explicit `--fresh`/`--no-cache` and for hook children (`hook_child`), whose
83/// `-m full` output is piped into a temp file the host reads back as the file's
84/// content and must never be a `cached … [NL]` stub (#1037).
85fn should_force_fresh(args: &[String], hook_child: bool) -> bool {
86    hook_child || args.iter().any(|a| a == "--fresh" || a == "--no-cache")
87}
88
89/// Resolve the read mode from CLI args. `--mode`/`-m` wins; otherwise the
90/// first positional after the path that parses as a known mode counts — a bare
91/// `lean-ctx read f.ps1 map` used to silently serve the `auto` default instead
92/// of the requested view (limitations audit 2026-07-03). Unknown positionals
93/// and flags are left alone so existing invocations keep their meaning.
94fn resolve_cli_read_mode(args: &[String]) -> String {
95    if let Some(m) = args
96        .iter()
97        .position(|a| a == "--mode" || a == "-m")
98        .and_then(|i| args.get(i + 1))
99    {
100        // #1813: `--mode -3` is the documented tail spelling; canonicalize it
101        // here too, or the CLI keeps answering with the head while MCP does not.
102        return crate::tools::ctx_read::canonicalize_tail_mode(m).unwrap_or_else(|| m.clone());
103    }
104    args.iter()
105        .skip(1)
106        .find(|a| !a.starts_with('-') && a.parse::<crate::tools::ctx_read::ReadMode>().is_ok())
107        .map_or_else(|| "auto".to_string(), std::clone::Clone::clone)
108}
109
110/// Env vars that change how a read is rendered but only exist in the caller's
111/// process — a long-lived daemon never sees them (#1889). The daemon path is
112/// Unix-only, so these are too.
113#[cfg(unix)]
114const CALLER_OUTPUT_OVERRIDES: [&str; 3] = [
115    "LEAN_CTX_CRP_MODE",
116    "LEAN_CTX_COMPRESSION",
117    "LEAN_CTX_PROFILE",
118];
119
120#[cfg(unix)]
121fn has_caller_output_override() -> bool {
122    CALLER_OUTPUT_OVERRIDES
123        .iter()
124        .any(|k| std::env::var(k).is_ok_and(|v| !v.trim().is_empty()))
125}
126
127/// Appends the API symbol lines the same way the MCP renderer does
128/// (`ctx_read::render`): TDD notation plus its one-line legend under
129/// `CrpMode::Tdd`, compact notation otherwise (#1889). `legend_inline` puts the
130/// legend on the current line (map's `API:` header) instead of its own line.
131fn push_signature_lines(
132    out: &mut String,
133    sigs: &[&signatures::Signature],
134    crp: crate::tools::CrpMode,
135    indent: &str,
136    legend_inline: bool,
137) {
138    if crp.is_tdd() {
139        let legend = signatures::tdd_legend(sigs);
140        if !legend.is_empty() {
141            out.push(if legend_inline { ' ' } else { '\n' });
142            out.push_str(&legend);
143        }
144    }
145    for sig in sigs {
146        out.push('\n');
147        out.push_str(indent);
148        if crp.is_tdd() {
149            out.push_str(&sig.to_tdd_located());
150        } else {
151            out.push_str(&sig.to_compact_located());
152        }
153    }
154}
155
156/// #1903: `lean-ctx read` enforces the same boundary as MCP `ctx_read` — the
157/// PathJail (project root + `allow_paths`/`extra_roots`/`read_only_roots` + the
158/// lean-ctx state dir) and the secret-path policy — with the same error text.
159/// A relative path is resolved against the process CWD (a shell user's
160/// intent), never re-anchored at the project root. A broad root (home, `/`,
161/// agent config dir) is refused like `lean-ctx call` does, unless the jail is
162/// disabled (`path_jail = false`), because jailing to `~` would admit every
163/// file the user owns.
164pub(crate) fn jail_cli_read_path(raw: &str, project_root: &str) -> Result<String, String> {
165    let candidate = if Path::new(raw).is_relative() {
166        std::env::current_dir().map_or_else(
167            |_| raw.to_string(),
168            |cwd| cwd.join(raw).to_string_lossy().into_owned(),
169        )
170    } else {
171        raw.to_string()
172    };
173    let jail_disabled = crate::core::config::Config::load().path_jail == Some(false);
174    if !jail_disabled && crate::core::pathutil::is_broad_or_unsafe_root(Path::new(project_root)) {
175        return Err(format!(
176            "path escapes project root: {candidate} (root: {project_root}). Access denied: \
177             no project detected — run inside a project, or pass --root <dir> \
178             (or set LEAN_CTX_PROJECT_ROOT)"
179        ));
180    }
181    crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &candidate)
182}
183
184/// Whether `lean-ctx read <raw>` from this process would be refused (#1903).
185/// Shell-hook rewriters keep such reads on the native command instead of
186/// turning a working `cat` into an access-denied error.
187pub(crate) fn cli_read_is_refused(raw: &str) -> bool {
188    jail_cli_read_path(raw, &super::common::detect_project_root(&[])).is_err()
189}
190
191pub fn cmd_read(args: &[String]) -> bool {
192    super::context_execution::execute(super::context_execution::ContextCommand::Read, args)
193        .exit_code
194        == 0
195}
196
197pub(crate) fn observe_read<'a>(
198    args: &'a [String],
199    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
200) -> CommandOutput {
201    if args.is_empty() {
202        eprintln!(
203            "Usage: lean-ctx read <file> [--mode auto|full|map|signatures|aggressive|entropy|lines:N-M|lines:-N] [--fresh]"
204        );
205        return CommandOutput::rejected(1);
206    }
207
208    // The PathJail is the outermost boundary: it runs before protected reads,
209    // the secret-path policy, the daemon and the local renderer (#1903).
210    let raw_path = &args[0];
211    let project_root = super::common::detect_project_root(args);
212    let path = match jail_cli_read_path(raw_path, &project_root) {
213        Ok(p) => p,
214        Err(e) => {
215            eprintln!("{e}");
216            return CommandOutput::rejected(1);
217        }
218    };
219    let mode = resolve_cli_read_mode(args);
220    // #1037: hook children must bypass cache and receive verbatim content.
221    let force_fresh = should_force_fresh(args, crate::core::runtime_flags::hook_child_enabled());
222
223    // Active project protection must precede the legacy daemon/cache routes.
224    // The prepared value is released only after its source authority is rechecked.
225    //
226    // The acquisition runs inside the shared CLI tool run's request scope and
227    // source capture; the capture travels with the prepared value and the
228    // publication finishes the same run (release, lineage record of the
229    // printed text). The scope is the working directory — exactly the project
230    // authority `prepare` resolved before.
231    let read_arguments = tool_arguments(serde_json::json!({ "path": path, "mode": mode }));
232    let cwd = std::env::current_dir()
233        .map(|dir| dir.to_string_lossy().into_owned())
234        .unwrap_or_default();
235    let protected_run = super::common::CliToolRun::new("ctx_read", &cwd, Some(&read_arguments))
236        .admitted_reader_output();
237    let (prepared, capture) = protected_run.acquire(|| policy_read::prepare(&path, &mode));
238    match prepared {
239        Ok(Some(prepared)) => {
240            return super::context_execution::run_protected(
241                super::context_execution::ContextCommand::Read,
242                Box::new(move || {
243                    prepared.publish(|printable| protected_run.finish(printable, capture))
244                }),
245            );
246        }
247        Ok(None) => {}
248        Err(()) => {
249            eprintln!("Content withheld by the active context policy.");
250            return CommandOutput::rejected(1);
251        }
252    }
253
254    // Apply the same secret-path policy in CLI mode as in MCP tools.
255    // Default is warn; enforce depends on active role/policy.
256    if let Ok(abs) = std::fs::canonicalize(&path) {
257        match io_boundary::check_secret_path_for_tool("cli_read", &abs) {
258            Ok(Some(w)) => eprintln!("{w}"),
259            Ok(None) => {}
260            Err(e) => {
261                eprintln!("{e}");
262                return CommandOutput::rejected(1);
263            }
264        }
265    } else {
266        // Best-effort: still check the raw path string.
267        match io_boundary::check_secret_path_for_tool("cli_read", Path::new(&path)) {
268            Ok(Some(w)) => eprintln!("{w}"),
269            Ok(None) => {}
270            Err(e) => {
271                eprintln!("{e}");
272                return CommandOutput::rejected(1);
273            }
274        }
275    }
276
277    // The shared daemon renders with *its* environment, so a caller-scoped
278    // output override (#1889) must be served by the standalone path.
279    #[cfg(unix)]
280    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path))
281        && !has_caller_output_override()
282    {
283        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
284            "ctx_read",
285            Some(serde_json::json!({
286                "path": path.clone(),
287                "mode": mode.clone(),
288                "fresh": force_fresh,
289            })),
290        ) {
291            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
292            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
293                let filtered = super::common::filter_daemon_output(&text);
294                if !filtered.trim().is_empty() {
295                    println!("{filtered}");
296                }
297                let exit_code = i32::from(is_error || is_failed_daemon_result(&filtered));
298                return CommandOutput::daemon(exit_code);
299            }
300            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
301                eprintln!("Error: daemon result uncertain: {message}");
302                return CommandOutput::daemon(1);
303            }
304        }
305    }
306    super::common::daemon_fallback_hint();
307
308    let requested_auto = mode == "auto";
309    run_local(Box::new(move || {
310        deliver_carrier(
311            "ctx_read",
312            &project_root,
313            Some(&read_arguments),
314            false,
315            |out| {
316                local_read(
317                    &path,
318                    &project_root,
319                    &mode,
320                    force_fresh,
321                    requested_auto,
322                    out,
323                )
324            },
325        )
326    }))
327}
328
329fn local_read(
330    path: &str,
331    project_root: &str,
332    mode: &str,
333    force_fresh: bool,
334    requested_auto: bool,
335    out: &mut Stdout,
336) -> CommandOutput {
337    let short = protocol::shorten_path(path);
338    let read_start = std::time::Instant::now();
339    let source = match crate::tools::ctx_read::read_file_lossy_admitted_for_cli(path) {
340        Ok(source) => source,
341        Err(e) => {
342            eprintln!("Error: {e}");
343            return CommandOutput::local(1, None);
344        }
345    };
346    // The CLI's admitted reader does not publish what it read. The source is
347    // published here, exactly as the rooted reader does it for the MCP tool
348    // (`archive::authority::publish_read`): the admitted text of the whole
349    // file, under the project the run is bound to. A no-op without a capture
350    // or without protection; a file outside the project marks the capture
351    // incomplete, so its output stays unknown lineage.
352    crate::core::archive::authority::publish_read(
353        Path::new(project_root),
354        &crate::core::pathutil::safe_canonicalize_bounded(Path::new(path), 2000).to_string_lossy(),
355        "ctx_read",
356        &source.text,
357    );
358    let content = source.text.as_str();
359    let storable = source.storable;
360    let original_tokens = count_tokens(content);
361
362    if !force_fresh && mode == "full" {
363        use crate::core::cli_cache::{self, CacheResult};
364        match cli_cache::check_admitted(path, &source) {
365            CacheResult::Hit { entry, file_ref } => {
366                let msg = cli_cache::format_hit(&entry, &file_ref, &short);
367                // A cache-hit stub is session state ("cached … [NL]"), not the
368                // source's text: printed as before, never a delivery record.
369                out.hint();
370                out.line(&msg);
371                let sent = count_tokens(&msg);
372                return CommandOutput::local(
373                    0,
374                    storable.then_some(Recording::Read {
375                        path: path.to_string(),
376                        mode: "full".to_string(),
377                        input_tokens: entry.original_tokens,
378                        output_tokens: sent,
379                        cache_hit: true,
380                        elapsed: read_start.elapsed(),
381                        excerpt: excerpt(&msg),
382                    }),
383                );
384            }
385            CacheResult::Miss { content } if content.is_empty() => {
386                eprintln!("Error: could not read {path}");
387                return CommandOutput::local(1, None);
388            }
389            CacheResult::Miss { content } => {
390                let line_count = content.lines().count();
391                let framed = format!("{short} [{line_count}L]\n{content}");
392                let output = cap_cli_to_raw(framed, &content, original_tokens);
393                out.line(&output);
394                let sent = count_tokens(&output);
395                return CommandOutput::local(
396                    0,
397                    storable.then_some(Recording::Read {
398                        path: path.to_string(),
399                        mode: "full".to_string(),
400                        input_tokens: original_tokens,
401                        output_tokens: sent,
402                        cache_hit: false,
403                        elapsed: read_start.elapsed(),
404                        excerpt: excerpt(&output),
405                    }),
406                );
407            }
408        }
409    }
410
411    let ext = Path::new(path)
412        .extension()
413        .and_then(|e| e.to_str())
414        .unwrap_or("");
415    let line_count = content.lines().count();
416
417    let mode = if mode == "auto" {
418        // Unified resolver — the single source of truth shared with the MCP
419        // path. The old CLI-local predictor lacked the small-file / config /
420        // instruction guards, so auto could pick a compressing mode that
421        // inflated a tiny file. Routing through `resolve` fixes that at the
422        // source (#361).
423        crate::core::auto_mode_resolver::resolve(
424            &crate::core::auto_mode_resolver::AutoModeContext {
425                path,
426                token_count: original_tokens,
427                line_count: None,
428                task: None,
429                cache: None,
430            },
431        )
432        .mode
433    } else if mode != "full" && crate::tools::ctx_read::is_instruction_file(path) {
434        "full".to_string()
435    } else {
436        mode.to_string()
437    };
438    let mode = if (mode == "map" || mode == "signatures") && original_tokens <= 400 {
439        "full".to_string()
440    } else {
441        mode
442    };
443    let mode = mode.as_str();
444
445    match mode {
446        "map" => {
447            let structured = match ext {
448                "md" | "mdx" | "rst" => {
449                    crate::core::structured_read::extract_markdown_outline(&content)
450                }
451                "json" => crate::core::structured_read::extract_json_structure(&content),
452                "yaml" | "yml" => crate::core::structured_read::extract_yaml_structure(&content),
453                "toml" => crate::core::structured_read::extract_toml_structure(&content),
454                _ if path.to_lowercase().ends_with(".lock")
455                    || path.to_lowercase().ends_with("go.sum") =>
456                {
457                    crate::core::structured_read::extract_lock_summary(&content, path)
458                }
459                _ => String::new(),
460            };
461
462            let mut output_buf = if structured.is_empty() {
463                let sigs = signatures::extract_signatures(&content, ext);
464                let dep_info = dep_extract::extract_deps(&content, ext);
465                let mut buf = format!("{short} [{line_count}L]");
466                if !dep_info.imports.is_empty() {
467                    buf.push_str(&format!("\n  deps: {}", dep_info.imports.join(", ")));
468                }
469                let key_sigs: Vec<&signatures::Signature> = sigs
470                    .iter()
471                    .filter(|s| s.is_exported || s.indent == 0)
472                    .collect();
473                // Drop exports the API section already lists (same symbol in a
474                // fuller form) so map drops the duplicate names — mirrors the
475                // MCP map renderer in ctx_read::render (#361).
476                let extra_exports =
477                    signatures::exports_not_in_signatures(&dep_info.exports, &key_sigs);
478                if !extra_exports.is_empty() {
479                    buf.push_str(&format!("\n  exports: {}", extra_exports.join(", ")));
480                }
481                if !key_sigs.is_empty() {
482                    buf.push_str("\n  API:");
483                    push_signature_lines(
484                        &mut buf,
485                        &key_sigs,
486                        crate::tools::CrpMode::effective(),
487                        "    ",
488                        true,
489                    );
490                }
491                // Same honesty rule as the MCP renderer: an information-free
492                // map must say so (limitations audit, #4).
493                if key_sigs.is_empty() && dep_info.imports.is_empty() && extra_exports.is_empty() {
494                    buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
495                }
496                buf
497            } else {
498                format!("{short} [{line_count}L]\n{structured}")
499            };
500
501            let sent = count_tokens(&output_buf);
502            output_buf = protocol::append_savings(&output_buf, original_tokens, sent);
503            if requested_auto {
504                output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
505            }
506            let sent = count_tokens(&output_buf);
507            out.line(&output_buf);
508            CommandOutput::local(
509                0,
510                storable.then_some(Recording::Read {
511                    path: path.to_string(),
512                    mode: "map".to_string(),
513                    input_tokens: original_tokens,
514                    output_tokens: sent,
515                    cache_hit: false,
516                    elapsed: read_start.elapsed(),
517                    excerpt: excerpt(&output_buf),
518                }),
519            )
520        }
521        "signatures" => {
522            let sigs = signatures::extract_signatures(&content, ext);
523            let mut output_buf = format!("{short} [{line_count}L]");
524            let refs: Vec<&signatures::Signature> = sigs.iter().collect();
525            push_signature_lines(
526                &mut output_buf,
527                &refs,
528                crate::tools::CrpMode::effective(),
529                "",
530                false,
531            );
532            // Same honesty rule as the MCP renderer (limitations audit, #4).
533            if sigs.is_empty() {
534                output_buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
535            }
536            if requested_auto {
537                output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
538            }
539            out.line(&output_buf);
540            let sent = count_tokens(&output_buf);
541            out.savings(original_tokens, sent);
542            CommandOutput::local(
543                0,
544                storable.then_some(Recording::Read {
545                    path: path.to_string(),
546                    mode: "signatures".to_string(),
547                    input_tokens: original_tokens,
548                    output_tokens: sent,
549                    cache_hit: false,
550                    elapsed: read_start.elapsed(),
551                    excerpt: excerpt(&output_buf),
552                }),
553            )
554        }
555        "aggressive" => {
556            let compressed = compressor::aggressive_compress(&content, Some(ext));
557            out.line(format_args!("{short} [{line_count}L]"));
558            out.line(&compressed);
559            let sent = count_tokens(&compressed);
560            out.savings(original_tokens, sent);
561            CommandOutput::local(
562                0,
563                storable.then_some(Recording::Read {
564                    path: path.to_string(),
565                    mode: "aggressive".to_string(),
566                    input_tokens: original_tokens,
567                    output_tokens: sent,
568                    cache_hit: false,
569                    elapsed: read_start.elapsed(),
570                    excerpt: excerpt(&compressed),
571                }),
572            )
573        }
574        "entropy" => {
575            let result = entropy::entropy_compress(&content);
576            let avg_h = entropy::analyze_entropy(&content).avg_entropy;
577            out.line(format_args!("{short} [{line_count}L] (H̄={avg_h:.1})"));
578            for tech in &result.techniques {
579                out.line(tech);
580            }
581            out.line(&result.output);
582            let sent = count_tokens(&result.output);
583            out.savings(original_tokens, sent);
584            CommandOutput::local(
585                0,
586                storable.then_some(Recording::Read {
587                    path: path.to_string(),
588                    mode: "entropy".to_string(),
589                    input_tokens: original_tokens,
590                    output_tokens: sent,
591                    cache_hit: false,
592                    elapsed: read_start.elapsed(),
593                    excerpt: excerpt(&result.output),
594                }),
595            )
596        }
597        m if m.starts_with("lines:") => {
598            // The CLI used to drop the window and print the whole file — a
599            // `lines:` read must return the requested selection, with the same
600            // comma-multi-select hint as the MCP renderer (limitations #7).
601            let range_str = &m[6..];
602            let extracted = crate::tools::ctx_read::extract_line_range(&content, range_str);
603            let multi_hint = if range_str.contains(',') {
604                crate::tools::ctx_read::LINES_COMMA_HINT
605            } else {
606                ""
607            };
608            let output =
609                format!("{short} [{line_count}L] lines:{range_str}\n{extracted}{multi_hint}");
610            if !multi_hint.is_empty() {
611                // A usage hint rides on the selection: no delivery record.
612                out.hint();
613            }
614            out.line(&output);
615            let sent = count_tokens(&output);
616            out.savings(original_tokens, sent);
617            CommandOutput::local(
618                0,
619                storable.then_some(Recording::Read {
620                    path: path.to_string(),
621                    mode: "lines".to_string(),
622                    input_tokens: original_tokens,
623                    output_tokens: sent,
624                    cache_hit: false,
625                    elapsed: read_start.elapsed(),
626                    excerpt: excerpt(&output),
627                }),
628            )
629        }
630        // Views rendered only by the shared MCP renderer. They used to fall into
631        // the `full` arm below, so `read -m density:0.4` / `-m reference` /
632        // `-m task` printed the whole file while MCP returned the view.
633        m if matches!(m, "cognitive" | "mdl" | "reference" | "task")
634            || m.starts_with("density:") =>
635        {
636            let (output, _) = crate::tools::ctx_read::process_mode(
637                &content,
638                mode,
639                "",
640                &short,
641                ext,
642                original_tokens,
643                crate::core::protocol::CrpMode::Off,
644                path,
645                None,
646            );
647            let output = if requested_auto {
648                cap_cli_to_raw(output, &content, original_tokens)
649            } else {
650                output
651            };
652            let sent = count_tokens(&output);
653            out.line(&output);
654            out.savings(original_tokens, sent);
655            CommandOutput::local(
656                0,
657                storable.then_some(Recording::Read {
658                    path: path.to_string(),
659                    mode: mode.to_string(),
660                    input_tokens: original_tokens,
661                    output_tokens: sent,
662                    cache_hit: false,
663                    elapsed: read_start.elapsed(),
664                    excerpt: excerpt(&output),
665                }),
666            )
667        }
668        _ => {
669            // `full` and any unrecognized mode land here. These are
670            // verbatim reads — the prose terse pipeline would mangle source
671            // (dictionary substitutions, line-drop dedup) and break a `full`
672            // read's "complete content" contract, so it must never run here
673            // (#404). Intentionally-lossy modes (map/signatures/aggressive/
674            // entropy/lines) have their own arms above.
675            let mut output = format!("{short} [{line_count}L]\n{content}");
676            if !crate::core::terse::is_verbatim_read("ctx_read", Some(mode)) {
677                let config = crate::core::config::Config::load();
678                let level = crate::core::config::CompressionLevel::effective(&config);
679                if level.is_active() {
680                    let terse_result =
681                        crate::core::terse::pipeline::compress(&output, &level, None);
682                    if terse_result.quality_passed && terse_result.savings_pct >= 3.0 {
683                        output = terse_result.output;
684                    }
685                }
686            }
687            // Full/verbatim reads never beat raw via framing — if terse didn't
688            // compress below the bare file, ship the file itself (#361).
689            let output = cap_cli_to_raw(output, &content, original_tokens);
690            out.line(&output);
691            let sent = count_tokens(&output);
692            CommandOutput::local(
693                0,
694                storable.then_some(Recording::Read {
695                    path: path.to_string(),
696                    mode: "full".to_string(),
697                    input_tokens: original_tokens,
698                    output_tokens: sent,
699                    cache_hit: false,
700                    elapsed: read_start.elapsed(),
701                    excerpt: excerpt(&output),
702                }),
703            )
704        }
705    }
706}
707
708pub fn cmd_diff(args: &[String]) {
709    let output =
710        super::context_execution::execute(super::context_execution::ContextCommand::Diff, args);
711    if output.exit_code != 0 {
712        std::process::exit(output.exit_code);
713    }
714}
715
716pub(crate) fn observe_diff<'a>(
717    args: &'a [String],
718    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
719) -> CommandOutput {
720    if args.len() < 2 {
721        eprintln!("Usage: lean-ctx diff <file1> <file2>");
722        return CommandOutput::rejected(1);
723    }
724
725    let path1 = args[0].clone();
726    let path2 = args[1].clone();
727    run_local(Box::new(move || local_diff(&path1, &path2)))
728}
729
730/// Both sides of a diff are sources: each is admitted like `lean-ctx read`
731/// admits its file (G01), and the diff is computed from the admitted texts.
732/// The generic unscoped reader is a plain local read outside a request scope,
733/// so it printed both originals here — a value `read` masks appeared in the
734/// diff. A side that is withheld ends the command with its content-free
735/// reason; no partial diff is printed.
736fn admitted_diff_sides(path1: &str, path2: &str) -> Result<(String, String), String> {
737    let side = |path: &str| {
738        crate::tools::ctx_read::read_file_lossy_admitted_for_cli(path)
739            .map(|source| source.text)
740            .map_err(|e| format!("Error reading {path}: {e}"))
741    };
742    Ok((side(path1)?, side(path2)?))
743}
744
745fn local_diff(path1: &str, path2: &str) -> CommandOutput {
746    let (content1, content2) = match admitted_diff_sides(path1, path2) {
747        Ok(sides) => sides,
748        Err(message) => {
749            eprintln!("{message}");
750            return CommandOutput::local(1, None);
751        }
752    };
753
754    let diff = compressor::diff_content(&content1, &content2);
755    let original = count_tokens(&content1) + count_tokens(&content2);
756    let sent = count_tokens(&diff);
757
758    println!(
759        "diff {} {}",
760        protocol::shorten_path(path1),
761        protocol::shorten_path(path2)
762    );
763    println!("{diff}");
764    print_savings(original, sent);
765    CommandOutput::local(
766        0,
767        Some(Recording::Stats {
768            tool: "cli_diff",
769            input_tokens: original,
770            output_tokens: sent,
771        }),
772    )
773}
774
775pub fn cmd_grep(args: &[String]) {
776    let output =
777        super::context_execution::execute(super::context_execution::ContextCommand::Grep, args);
778    if output.exit_code != 0 {
779        std::process::exit(output.exit_code);
780    }
781}
782
783pub(crate) fn observe_grep<'a>(
784    args: &'a [String],
785    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
786) -> CommandOutput {
787    if args.is_empty() {
788        eprintln!("Usage: lean-ctx grep <pattern> [path]");
789        return CommandOutput::rejected(1);
790    }
791
792    let pattern = args[0].clone();
793    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
794    let path = resolve_cli_path(raw_path);
795
796    #[cfg(unix)]
797    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
798        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
799            "ctx_search",
800            Some(serde_json::json!({
801                "pattern": pattern.clone(),
802                "path": path.clone(),
803            })),
804        ) {
805            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
806            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
807                let out = super::common::filter_daemon_output(&text);
808                println!("{out}");
809                let exit_code = if is_error { 2 } else { grep_exit_status(&out) };
810                return CommandOutput::daemon(exit_code);
811            }
812            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
813                eprintln!("Error: daemon result uncertain: {message}");
814                return CommandOutput::daemon(2);
815            }
816        }
817    }
818    super::common::daemon_fallback_hint();
819
820    // The arguments the daemon route sends for the same search: `ctx_search`
821    // decides from them whether this call declares every source.
822    let search_arguments = tool_arguments(serde_json::json!({ "pattern": pattern, "path": path }));
823    run_local(Box::new(move || {
824        let project_root = super::common::detect_project_root(&[]);
825        deliver_carrier(
826            "ctx_search",
827            &project_root,
828            Some(&search_arguments),
829            false,
830            |out| local_grep(pattern, path, out),
831        )
832    }))
833}
834
835fn local_grep(pattern: String, path: String, stdout: &mut Stdout) -> CommandOutput {
836    // Search latency for the Context IR lineage (#566), standalone path only.
837    let search_start = std::time::Instant::now();
838
839    let outcome = crate::tools::ctx_search::handle(
840        &pattern,
841        &path,
842        None,
843        20,
844        crate::tools::CrpMode::effective(),
845        true,
846        roles::active_role().io.allow_secret_paths,
847        false,
848    );
849    let failed = outcome.failed;
850    let out = outcome.text;
851    stdout.line(&out);
852    let output_tokens = count_tokens(&out);
853    let exit_code = if failed { 2 } else { grep_exit_status(&out) };
854    CommandOutput::local(
855        exit_code,
856        Some(Recording::Search {
857            modeled_baseline: outcome.modeled_baseline,
858            observed_tokens: outcome.observed_tokens,
859            output_tokens,
860            pattern,
861            path,
862            elapsed: search_start.elapsed(),
863            excerpt: excerpt(&out),
864        }),
865    )
866}
867
868/// grep-compatible exit status for `lean-ctx grep` output (#1917).
869///
870/// `0` = matches found, `1` = searched everything and found nothing,
871/// `2` = error or an incomplete search (files skipped, time budget hit).
872/// A plain `1` after skipping files would tell scripts and agents "not
873/// present" when the content was never examined.
874fn grep_exit_status(out: &str) -> i32 {
875    let out = out.trim_start();
876    if out.starts_with("ERROR") {
877        return 2;
878    }
879    if !out.starts_with("0 matches") {
880        return 0;
881    }
882    if out.contains("skipped") || out.contains("stopped") {
883        2
884    } else {
885        1
886    }
887}
888
889/// `lean-ctx glob <pattern> [path]` — find files by glob pattern, shares the
890/// exact `ctx_glob` core so the CLI, the MCP tool, and the shadow-mode redirect
891/// (#556) all return identical results. Prefers the daemon (warms its cache),
892/// falling back to an in-process call.
893pub fn cmd_glob(args: &[String]) {
894    let output =
895        super::context_execution::execute(super::context_execution::ContextCommand::Glob, args);
896    if output.exit_code != 0 {
897        std::process::exit(output.exit_code);
898    }
899}
900
901pub(crate) fn observe_glob<'a>(
902    args: &'a [String],
903    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
904) -> CommandOutput {
905    if args.is_empty() {
906        eprintln!("Usage: lean-ctx glob <pattern> [path]");
907        return CommandOutput::rejected(1);
908    }
909
910    let pattern = args[0].clone();
911    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
912    let path = resolve_cli_path(raw_path);
913
914    #[cfg(unix)]
915    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
916        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
917            "ctx_glob",
918            Some(serde_json::json!({
919                "pattern": pattern.clone(),
920                "path": path.clone(),
921            })),
922        ) {
923            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
924            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
925                let out = super::common::filter_daemon_output(&text);
926                println!("{out}");
927                return CommandOutput::daemon(i32::from(is_error));
928            }
929            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
930                eprintln!("Error: daemon result uncertain: {message}");
931                return CommandOutput::daemon(1);
932            }
933        }
934    }
935    super::common::daemon_fallback_hint();
936
937    run_local(Box::new(move || {
938        let project_root = super::common::detect_project_root(&[]);
939        // A listing: released like every carrier, never a delivery record.
940        deliver_carrier("ctx_glob", &project_root, None, true, |out| {
941            local_glob(&pattern, &path, out)
942        })
943    }))
944}
945
946fn local_glob(pattern: &str, path: &str, stdout: &mut Stdout) -> CommandOutput {
947    let (out, _original) = crate::tools::ctx_glob::handle(
948        pattern,
949        path,
950        true,
951        roles::active_role().io.allow_secret_paths,
952        200,
953    );
954    stdout.line(&out);
955    let exit_code = i32::from(out.starts_with("ERROR:"));
956    CommandOutput::local(
957        exit_code,
958        Some(Recording::Stats {
959            tool: "cli_glob",
960            input_tokens: 0,
961            output_tokens: 0,
962        }),
963    )
964}
965
966pub fn cmd_find(args: &[String]) {
967    let output =
968        super::context_execution::execute(super::context_execution::ContextCommand::Find, args);
969    if output.exit_code != 0 {
970        std::process::exit(output.exit_code);
971    }
972}
973
974pub(crate) fn observe_find<'a>(
975    args: &'a [String],
976    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
977) -> CommandOutput {
978    if args.is_empty() {
979        eprintln!("Usage: lean-ctx find <pattern> [path]");
980        return CommandOutput::rejected(1);
981    }
982
983    let raw_pattern = args[0].clone();
984    let path = args
985        .get(1)
986        .map_or(".", std::string::String::as_str)
987        .to_string();
988    run_local(Box::new(move || local_find(&raw_pattern, &path)))
989}
990
991fn local_find(raw_pattern: &str, path: &str) -> CommandOutput {
992    let is_glob = raw_pattern.contains('*') || raw_pattern.contains('?');
993    let glob_matcher = if is_glob {
994        glob::Pattern::new(&raw_pattern.to_lowercase()).ok()
995    } else {
996        None
997    };
998    let substring = raw_pattern.to_lowercase();
999
1000    let mut found = false;
1001    let walk_root = crate::core::walk_filter::explicit_walk_root(Path::new(path));
1002    for entry in ignore::WalkBuilder::new(&walk_root)
1003        // #1792: a tracked dotfile is part of the project. `.gitignore` already
1004        // decides membership, and it is honoured below.
1005        .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
1006        .git_ignore(true)
1007        .git_global(true)
1008        .git_exclude(true)
1009        .require_git(false)
1010        .max_depth(Some(10))
1011        .filter_entry(crate::core::walk_filter::keep_entry)
1012        .build()
1013        .flatten()
1014    {
1015        let name = entry.file_name().to_string_lossy().to_lowercase();
1016        let matches = if let Some(ref g) = glob_matcher {
1017            g.matches(&name)
1018        } else {
1019            name.contains(&substring)
1020        };
1021        if matches {
1022            println!("{}", entry.path().display());
1023            found = true;
1024        }
1025    }
1026
1027    CommandOutput::local(
1028        i32::from(!found),
1029        Some(Recording::Stats {
1030            tool: "cli_find",
1031            input_tokens: 0,
1032            output_tokens: 0,
1033        }),
1034    )
1035}
1036
1037pub fn cmd_ls(args: &[String]) {
1038    let output =
1039        super::context_execution::execute(super::context_execution::ContextCommand::Ls, args);
1040    if output.exit_code != 0 {
1041        std::process::exit(output.exit_code);
1042    }
1043}
1044
1045pub(crate) fn observe_ls<'a>(
1046    args: &'a [String],
1047    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
1048) -> CommandOutput {
1049    let mut raw_path = ".".to_string();
1050    let mut depth = 3usize;
1051    let mut show_hidden = false;
1052    let mut respect_gitignore = true;
1053    let mut i = 0;
1054
1055    while i < args.len() {
1056        let arg = &args[i];
1057        if arg == "--depth" {
1058            i += 1;
1059            if let Some(d) = args.get(i).and_then(|s| s.parse::<usize>().ok()) {
1060                depth = d.min(10);
1061            }
1062        } else if arg == "--all" || arg == "-a" {
1063            show_hidden = true;
1064        } else if arg == "--no-gitignore" {
1065            respect_gitignore = false;
1066        } else if arg.starts_with('-') {
1067            eprintln!("Error: lean-ctx ls does not support flag '{arg}'.\n");
1068            eprintln!(
1069                "lean-ctx ls is a compressed directory tree viewer for AI context, not a drop-in ls replacement."
1070            );
1071            eprintln!(
1072                "The shell hook (lean-ctx -t ls {arg} ...) passes flags to system ls transparently.\n"
1073            );
1074            eprintln!("Usage: lean-ctx ls [path] [--depth N] [--all] [--no-gitignore]");
1075            return CommandOutput::rejected(1);
1076        } else {
1077            raw_path.clone_from(arg);
1078        }
1079        i += 1;
1080    }
1081
1082    let abs_path = resolve_cli_path(&raw_path);
1083    let path = abs_path;
1084
1085    #[cfg(unix)]
1086    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
1087        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
1088            "ctx_tree",
1089            Some(serde_json::json!({
1090                "path": path.clone(),
1091                "depth": depth,
1092                "show_hidden": show_hidden,
1093                "respect_gitignore": respect_gitignore,
1094            })),
1095        ) {
1096            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
1097            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
1098                let out = super::common::filter_daemon_output(&text);
1099                println!("{out}");
1100                return CommandOutput::daemon(i32::from(is_error));
1101            }
1102            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
1103                eprintln!("Error: daemon result uncertain: {message}");
1104                return CommandOutput::daemon(1);
1105            }
1106        }
1107    }
1108    super::common::daemon_fallback_hint();
1109
1110    run_local(Box::new(move || {
1111        let project_root = super::common::detect_project_root(&[]);
1112        // A listing: released like every carrier, never a delivery record.
1113        deliver_carrier("ctx_tree", &project_root, None, true, |out| {
1114            local_ls(&path, depth, show_hidden, respect_gitignore, out)
1115        })
1116    }))
1117}
1118
1119fn local_ls(
1120    path: &str,
1121    depth: usize,
1122    show_hidden: bool,
1123    respect_gitignore: bool,
1124    stdout: &mut Stdout,
1125) -> CommandOutput {
1126    let (out, original) =
1127        crate::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
1128    if out.starts_with("ERROR:") {
1129        eprintln!("{out}");
1130        std::process::exit(1);
1131    }
1132    stdout.line(&out);
1133    CommandOutput::local(
1134        0,
1135        Some(Recording::Tree {
1136            input_tokens: original,
1137            output_tokens: count_tokens(&out),
1138        }),
1139    )
1140}
1141
1142pub fn cmd_deps(args: &[String]) {
1143    let output =
1144        super::context_execution::execute(super::context_execution::ContextCommand::Deps, args);
1145    if output.exit_code != 0 {
1146        std::process::exit(output.exit_code);
1147    }
1148}
1149
1150pub(crate) fn observe_deps<'a>(
1151    args: &'a [String],
1152    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
1153) -> CommandOutput {
1154    let path = args
1155        .first()
1156        .map_or(".", std::string::String::as_str)
1157        .to_string();
1158    run_local(Box::new(move || local_deps(&path)))
1159}
1160
1161fn local_deps(path: &str) -> CommandOutput {
1162    if let Some(result) = deps_cmd::detect_and_compress(path) {
1163        println!("{result}");
1164        CommandOutput::local(
1165            0,
1166            Some(Recording::Stats {
1167                tool: "cli_deps",
1168                input_tokens: 0,
1169                output_tokens: 0,
1170            }),
1171        )
1172    } else {
1173        eprintln!("No dependency file found in {path}");
1174        CommandOutput::local(1, None)
1175    }
1176}
1177
1178#[cfg(test)]
1179#[path = "read_cmd_adapter_tests.rs"]
1180mod adapter_tests;
1181
1182#[cfg(test)]
1183#[path = "read_cmd_tests.rs"]
1184mod tests;