Skip to main content

lean_ctx_cli/cli/
read_cmd.rs

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