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/// Detect legacy daemon read failures for the exit status. A completed daemon
20/// request must not fall through to standalone and dispatch the operation twice.
21/// Catches: `"file.rs 0L"` stubs and `"Cannot read file:"` handler errors.
22#[cfg(unix)]
23fn is_failed_daemon_result(output: &str) -> bool {
24    let first_line = output.lines().next().unwrap_or("");
25    if first_line.starts_with("ERROR:") {
26        return true;
27    }
28    if first_line.starts_with("Cannot read file:") || first_line.starts_with("File is empty:") {
29        return true;
30    }
31    if !first_line.ends_with(" 0L") {
32        return false;
33    }
34    let body: String = output
35        .lines()
36        .skip(1)
37        .filter(|l| {
38            let t = l.trim();
39            !t.is_empty()
40                && !t.starts_with("[no extractable structure")
41                && !t.starts_with("[lean-ctx]")
42                && !t.starts_with('[')
43        })
44        .collect();
45    body.is_empty()
46}
47
48fn resolve_cli_path(raw: &str) -> String {
49    if let Ok(abs) = std::path::Path::new(raw).canonicalize() {
50        return abs.to_string_lossy().to_string();
51    }
52    if Path::new(raw).is_relative()
53        && let Ok(cwd) = std::env::current_dir()
54    {
55        return cwd.join(raw).to_string_lossy().into_owned();
56    }
57    raw.to_string()
58}
59use crate::core::tokens::count_tokens;
60
61use super::common::print_savings;
62
63/// #361 anti-inflation guarantee for the additive one-shot CLI path (the pi
64/// default an independent benchmark measured). Mirrors the MCP `cap_to_raw`
65/// invariant: a read must never cost more tokens than the raw file, so when the
66/// framing (`short [NL]` header, deps/API summary, savings footer) would push
67/// the payload past the bare content we ship the content verbatim. Empty files
68/// keep their framing so the reader still gets a signal.
69fn cap_cli_to_raw(framed: String, raw_content: &str, raw_tokens: usize) -> String {
70    if raw_tokens > 0 && count_tokens(&framed) > raw_tokens {
71        raw_content.to_string()
72    } else {
73        framed
74    }
75}
76
77/// Whether the read must bypass all caches and return verbatim content. True for
78/// explicit `--fresh`/`--no-cache` and for hook children (`hook_child`), whose
79/// `-m full` output is piped into a temp file the host reads back as the file's
80/// content and must never be a `cached … [NL]` stub (#1037).
81fn should_force_fresh(args: &[String], hook_child: bool) -> bool {
82    hook_child || args.iter().any(|a| a == "--fresh" || a == "--no-cache")
83}
84
85/// Resolve the read mode from CLI args. `--mode`/`-m` wins; otherwise the
86/// first positional after the path that parses as a known mode counts — a bare
87/// `lean-ctx read f.ps1 map` used to silently serve the `auto` default instead
88/// of the requested view (limitations audit 2026-07-03). Unknown positionals
89/// and flags are left alone so existing invocations keep their meaning.
90fn resolve_cli_read_mode(args: &[String]) -> String {
91    if let Some(m) = args
92        .iter()
93        .position(|a| a == "--mode" || a == "-m")
94        .and_then(|i| args.get(i + 1))
95    {
96        // #1813: `--mode -3` is the documented tail spelling; canonicalize it
97        // here too, or the CLI keeps answering with the head while MCP does not.
98        return crate::tools::ctx_read::canonicalize_tail_mode(m).unwrap_or_else(|| m.clone());
99    }
100    args.iter()
101        .skip(1)
102        .find(|a| !a.starts_with('-') && a.parse::<crate::tools::ctx_read::ReadMode>().is_ok())
103        .map_or_else(|| "auto".to_string(), std::clone::Clone::clone)
104}
105
106/// Env vars that change how a read is rendered but only exist in the caller's
107/// process — a long-lived daemon never sees them (#1889). The daemon path is
108/// Unix-only, so these are too.
109#[cfg(unix)]
110const CALLER_OUTPUT_OVERRIDES: [&str; 3] = [
111    "LEAN_CTX_CRP_MODE",
112    "LEAN_CTX_COMPRESSION",
113    "LEAN_CTX_PROFILE",
114];
115
116#[cfg(unix)]
117fn has_caller_output_override() -> bool {
118    CALLER_OUTPUT_OVERRIDES
119        .iter()
120        .any(|k| std::env::var(k).is_ok_and(|v| !v.trim().is_empty()))
121}
122
123/// Appends the API symbol lines the same way the MCP renderer does
124/// (`ctx_read::render`): TDD notation plus its one-line legend under
125/// `CrpMode::Tdd`, compact notation otherwise (#1889). `legend_inline` puts the
126/// legend on the current line (map's `API:` header) instead of its own line.
127fn push_signature_lines(
128    out: &mut String,
129    sigs: &[&signatures::Signature],
130    crp: crate::tools::CrpMode,
131    indent: &str,
132    legend_inline: bool,
133) {
134    if crp.is_tdd() {
135        let legend = signatures::tdd_legend(sigs);
136        if !legend.is_empty() {
137            out.push(if legend_inline { ' ' } else { '\n' });
138            out.push_str(&legend);
139        }
140    }
141    for sig in sigs {
142        out.push('\n');
143        out.push_str(indent);
144        if crp.is_tdd() {
145            out.push_str(&sig.to_tdd_located());
146        } else {
147            out.push_str(&sig.to_compact_located());
148        }
149    }
150}
151
152/// #1903: `lean-ctx read` enforces the same boundary as MCP `ctx_read` — the
153/// PathJail (project root + `allow_paths`/`extra_roots`/`read_only_roots` + the
154/// lean-ctx state dir) and the secret-path policy — with the same error text.
155/// A relative path is resolved against the process CWD (a shell user's
156/// intent), never re-anchored at the project root. A broad root (home, `/`,
157/// agent config dir) is refused like `lean-ctx call` does, unless the jail is
158/// disabled (`path_jail = false`), because jailing to `~` would admit every
159/// file the user owns.
160pub(crate) fn jail_cli_read_path(raw: &str, project_root: &str) -> Result<String, String> {
161    let candidate = if Path::new(raw).is_relative() {
162        std::env::current_dir().map_or_else(
163            |_| raw.to_string(),
164            |cwd| cwd.join(raw).to_string_lossy().into_owned(),
165        )
166    } else {
167        raw.to_string()
168    };
169    let jail_disabled = crate::core::config::Config::load().path_jail == Some(false);
170    if !jail_disabled && crate::core::pathutil::is_broad_or_unsafe_root(Path::new(project_root)) {
171        return Err(format!(
172            "path escapes project root: {candidate} (root: {project_root}). Access denied: \
173             no project detected — run inside a project, or pass --root <dir> \
174             (or set LEAN_CTX_PROJECT_ROOT)"
175        ));
176    }
177    crate::core::path_resolve::resolve_tool_path(Some(project_root), None, &candidate)
178}
179
180/// Whether `lean-ctx read <raw>` from this process would be refused (#1903).
181/// Shell-hook rewriters keep such reads on the native command instead of
182/// turning a working `cat` into an access-denied error.
183pub(crate) fn cli_read_is_refused(raw: &str) -> bool {
184    jail_cli_read_path(raw, &super::common::detect_project_root(&[])).is_err()
185}
186
187pub fn cmd_read(args: &[String]) -> bool {
188    super::context_execution::execute(super::context_execution::ContextCommand::Read, args)
189        .exit_code
190        == 0
191}
192
193pub(crate) fn observe_read<'a>(
194    args: &'a [String],
195    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
196) -> CommandOutput {
197    if args.is_empty() {
198        eprintln!(
199            "Usage: lean-ctx read <file> [--mode auto|full|map|signatures|aggressive|entropy|lines:N-M|lines:-N] [--fresh]"
200        );
201        return CommandOutput::rejected(1);
202    }
203
204    // The PathJail is the outermost boundary: it runs before protected reads,
205    // the secret-path policy, the daemon and the local renderer (#1903).
206    let raw_path = &args[0];
207    let project_root = super::common::detect_project_root(args);
208    let path = match jail_cli_read_path(raw_path, &project_root) {
209        Ok(p) => p,
210        Err(e) => {
211            eprintln!("{e}");
212            return CommandOutput::rejected(1);
213        }
214    };
215    let mode = resolve_cli_read_mode(args);
216    // #1037: hook children must bypass cache and receive verbatim content.
217    let force_fresh = should_force_fresh(args, crate::core::runtime_flags::hook_child_enabled());
218
219    // Active project protection must precede the legacy daemon/cache routes.
220    // The prepared value is released only after its source authority is rechecked.
221    match policy_read::prepare(&path, &mode) {
222        Ok(Some(prepared)) => {
223            return super::context_execution::run_protected(
224                super::context_execution::ContextCommand::Read,
225                Box::new(move || prepared.publish()),
226            );
227        }
228        Ok(None) => {}
229        Err(()) => {
230            eprintln!("Content withheld by the active context policy.");
231            return CommandOutput::rejected(1);
232        }
233    }
234
235    // Apply the same secret-path policy in CLI mode as in MCP tools.
236    // Default is warn; enforce depends on active role/policy.
237    if let Ok(abs) = std::fs::canonicalize(&path) {
238        match io_boundary::check_secret_path_for_tool("cli_read", &abs) {
239            Ok(Some(w)) => eprintln!("{w}"),
240            Ok(None) => {}
241            Err(e) => {
242                eprintln!("{e}");
243                return CommandOutput::rejected(1);
244            }
245        }
246    } else {
247        // Best-effort: still check the raw path string.
248        match io_boundary::check_secret_path_for_tool("cli_read", Path::new(&path)) {
249            Ok(Some(w)) => eprintln!("{w}"),
250            Ok(None) => {}
251            Err(e) => {
252                eprintln!("{e}");
253                return CommandOutput::rejected(1);
254            }
255        }
256    }
257
258    // The shared daemon renders with *its* environment, so a caller-scoped
259    // output override (#1889) must be served by the standalone path.
260    #[cfg(unix)]
261    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path))
262        && !has_caller_output_override()
263    {
264        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
265            "ctx_read",
266            Some(serde_json::json!({
267                "path": path.clone(),
268                "mode": mode.clone(),
269                "fresh": force_fresh,
270            })),
271        ) {
272            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
273            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
274                let filtered = super::common::filter_daemon_output(&text);
275                if !filtered.trim().is_empty() {
276                    println!("{filtered}");
277                }
278                let exit_code = i32::from(is_error || is_failed_daemon_result(&filtered));
279                return CommandOutput::daemon(exit_code);
280            }
281            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
282                eprintln!("Error: daemon result uncertain: {message}");
283                return CommandOutput::daemon(1);
284            }
285        }
286    }
287    super::common::daemon_fallback_hint();
288
289    let requested_auto = mode == "auto";
290    run_local(Box::new(move || {
291        local_read(&path, &mode, force_fresh, requested_auto)
292    }))
293}
294
295fn local_read(path: &str, mode: &str, force_fresh: bool, requested_auto: bool) -> CommandOutput {
296    let short = protocol::shorten_path(path);
297    let read_start = std::time::Instant::now();
298
299    if !force_fresh && mode == "full" {
300        use crate::core::cli_cache::{self, CacheResult};
301        match cli_cache::check_and_read(path) {
302            CacheResult::Hit { entry, file_ref } => {
303                let msg = cli_cache::format_hit(&entry, &file_ref, &short);
304                println!("{msg}");
305                let sent = count_tokens(&msg);
306                return CommandOutput::local(
307                    0,
308                    Some(Recording::Read {
309                        path: path.to_string(),
310                        mode: "full".to_string(),
311                        input_tokens: entry.original_tokens,
312                        output_tokens: sent,
313                        cache_hit: true,
314                        elapsed: read_start.elapsed(),
315                        excerpt: excerpt(&msg),
316                    }),
317                );
318            }
319            CacheResult::Miss { content } if content.is_empty() => {
320                eprintln!("Error: could not read {path}");
321                return CommandOutput::local(1, None);
322            }
323            CacheResult::Miss { content } => {
324                let line_count = content.lines().count();
325                let raw_tokens = count_tokens(&content);
326                let framed = format!("{short} [{line_count}L]\n{content}");
327                let output = cap_cli_to_raw(framed, &content, raw_tokens);
328                println!("{output}");
329                let sent = count_tokens(&output);
330                return CommandOutput::local(
331                    0,
332                    Some(Recording::Read {
333                        path: path.to_string(),
334                        mode: "full".to_string(),
335                        input_tokens: raw_tokens,
336                        output_tokens: sent,
337                        cache_hit: false,
338                        elapsed: read_start.elapsed(),
339                        excerpt: excerpt(&output),
340                    }),
341                );
342            }
343        }
344    }
345
346    let content = match crate::tools::ctx_read::read_file_lossy(path) {
347        Ok(c) => c,
348        Err(e) => {
349            eprintln!("Error: {e}");
350            return CommandOutput::local(1, None);
351        }
352    };
353
354    let ext = Path::new(path)
355        .extension()
356        .and_then(|e| e.to_str())
357        .unwrap_or("");
358    let line_count = content.lines().count();
359    let original_tokens = count_tokens(&content);
360
361    let mode = if mode == "auto" {
362        // Unified resolver — the single source of truth shared with the MCP
363        // path. The old CLI-local predictor lacked the small-file / config /
364        // instruction guards, so auto could pick a compressing mode that
365        // inflated a tiny file. Routing through `resolve` fixes that at the
366        // source (#361).
367        crate::core::auto_mode_resolver::resolve(
368            &crate::core::auto_mode_resolver::AutoModeContext {
369                path,
370                token_count: original_tokens,
371                line_count: None,
372                task: None,
373                cache: None,
374            },
375        )
376        .mode
377    } else if mode != "full" && crate::tools::ctx_read::is_instruction_file(path) {
378        "full".to_string()
379    } else {
380        mode.to_string()
381    };
382    let mode = if (mode == "map" || mode == "signatures") && original_tokens <= 400 {
383        "full".to_string()
384    } else {
385        mode
386    };
387    let mode = mode.as_str();
388
389    match mode {
390        "map" => {
391            let structured = match ext {
392                "md" | "mdx" | "rst" => {
393                    crate::core::structured_read::extract_markdown_outline(&content)
394                }
395                "json" => crate::core::structured_read::extract_json_structure(&content),
396                "yaml" | "yml" => crate::core::structured_read::extract_yaml_structure(&content),
397                "toml" => crate::core::structured_read::extract_toml_structure(&content),
398                _ if path.to_lowercase().ends_with(".lock")
399                    || path.to_lowercase().ends_with("go.sum") =>
400                {
401                    crate::core::structured_read::extract_lock_summary(&content, path)
402                }
403                _ => String::new(),
404            };
405
406            let mut output_buf = if structured.is_empty() {
407                let sigs = signatures::extract_signatures(&content, ext);
408                let dep_info = dep_extract::extract_deps(&content, ext);
409                let mut buf = format!("{short} [{line_count}L]");
410                if !dep_info.imports.is_empty() {
411                    buf.push_str(&format!("\n  deps: {}", dep_info.imports.join(", ")));
412                }
413                let key_sigs: Vec<&signatures::Signature> = sigs
414                    .iter()
415                    .filter(|s| s.is_exported || s.indent == 0)
416                    .collect();
417                // Drop exports the API section already lists (same symbol in a
418                // fuller form) so map drops the duplicate names — mirrors the
419                // MCP map renderer in ctx_read::render (#361).
420                let extra_exports =
421                    signatures::exports_not_in_signatures(&dep_info.exports, &key_sigs);
422                if !extra_exports.is_empty() {
423                    buf.push_str(&format!("\n  exports: {}", extra_exports.join(", ")));
424                }
425                if !key_sigs.is_empty() {
426                    buf.push_str("\n  API:");
427                    push_signature_lines(
428                        &mut buf,
429                        &key_sigs,
430                        crate::tools::CrpMode::effective(),
431                        "    ",
432                        true,
433                    );
434                }
435                // Same honesty rule as the MCP renderer: an information-free
436                // map must say so (limitations audit, #4).
437                if key_sigs.is_empty() && dep_info.imports.is_empty() && extra_exports.is_empty() {
438                    buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
439                }
440                buf
441            } else {
442                format!("{short} [{line_count}L]\n{structured}")
443            };
444
445            let sent = count_tokens(&output_buf);
446            output_buf = protocol::append_savings(&output_buf, original_tokens, sent);
447            if requested_auto {
448                output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
449            }
450            let sent = count_tokens(&output_buf);
451            println!("{output_buf}");
452            CommandOutput::local(
453                0,
454                Some(Recording::Read {
455                    path: path.to_string(),
456                    mode: "map".to_string(),
457                    input_tokens: original_tokens,
458                    output_tokens: sent,
459                    cache_hit: false,
460                    elapsed: read_start.elapsed(),
461                    excerpt: excerpt(&output_buf),
462                }),
463            )
464        }
465        "signatures" => {
466            let sigs = signatures::extract_signatures(&content, ext);
467            let mut output_buf = format!("{short} [{line_count}L]");
468            let refs: Vec<&signatures::Signature> = sigs.iter().collect();
469            push_signature_lines(
470                &mut output_buf,
471                &refs,
472                crate::tools::CrpMode::effective(),
473                "",
474                false,
475            );
476            // Same honesty rule as the MCP renderer (limitations audit, #4).
477            if sigs.is_empty() {
478                output_buf.push_str(&crate::tools::ctx_read::no_structure_marker(ext));
479            }
480            if requested_auto {
481                output_buf = cap_cli_to_raw(output_buf, &content, original_tokens);
482            }
483            println!("{output_buf}");
484            let sent = count_tokens(&output_buf);
485            print_savings(original_tokens, sent);
486            CommandOutput::local(
487                0,
488                Some(Recording::Read {
489                    path: path.to_string(),
490                    mode: "signatures".to_string(),
491                    input_tokens: original_tokens,
492                    output_tokens: sent,
493                    cache_hit: false,
494                    elapsed: read_start.elapsed(),
495                    excerpt: excerpt(&output_buf),
496                }),
497            )
498        }
499        "aggressive" => {
500            let compressed = compressor::aggressive_compress(&content, Some(ext));
501            println!("{short} [{line_count}L]");
502            println!("{compressed}");
503            let sent = count_tokens(&compressed);
504            print_savings(original_tokens, sent);
505            CommandOutput::local(
506                0,
507                Some(Recording::Read {
508                    path: path.to_string(),
509                    mode: "aggressive".to_string(),
510                    input_tokens: original_tokens,
511                    output_tokens: sent,
512                    cache_hit: false,
513                    elapsed: read_start.elapsed(),
514                    excerpt: excerpt(&compressed),
515                }),
516            )
517        }
518        "entropy" => {
519            let result = entropy::entropy_compress(&content);
520            let avg_h = entropy::analyze_entropy(&content).avg_entropy;
521            println!("{short} [{line_count}L] (H̄={avg_h:.1})");
522            for tech in &result.techniques {
523                println!("{tech}");
524            }
525            println!("{}", result.output);
526            let sent = count_tokens(&result.output);
527            print_savings(original_tokens, sent);
528            CommandOutput::local(
529                0,
530                Some(Recording::Read {
531                    path: path.to_string(),
532                    mode: "entropy".to_string(),
533                    input_tokens: original_tokens,
534                    output_tokens: sent,
535                    cache_hit: false,
536                    elapsed: read_start.elapsed(),
537                    excerpt: excerpt(&result.output),
538                }),
539            )
540        }
541        m if m.starts_with("lines:") => {
542            // The CLI used to drop the window and print the whole file — a
543            // `lines:` read must return the requested selection, with the same
544            // comma-multi-select hint as the MCP renderer (limitations #7).
545            let range_str = &m[6..];
546            let extracted = crate::tools::ctx_read::extract_line_range(&content, range_str);
547            let multi_hint = if range_str.contains(',') {
548                crate::tools::ctx_read::LINES_COMMA_HINT
549            } else {
550                ""
551            };
552            let output =
553                format!("{short} [{line_count}L] lines:{range_str}\n{extracted}{multi_hint}");
554            println!("{output}");
555            let sent = count_tokens(&output);
556            print_savings(original_tokens, sent);
557            CommandOutput::local(
558                0,
559                Some(Recording::Read {
560                    path: path.to_string(),
561                    mode: "lines".to_string(),
562                    input_tokens: original_tokens,
563                    output_tokens: sent,
564                    cache_hit: false,
565                    elapsed: read_start.elapsed(),
566                    excerpt: excerpt(&output),
567                }),
568            )
569        }
570        "cognitive" | "mdl" => {
571            let (output, _) = crate::tools::ctx_read::process_mode(
572                &content,
573                mode,
574                "",
575                &short,
576                ext,
577                original_tokens,
578                crate::core::protocol::CrpMode::Off,
579                path,
580                None,
581            );
582            let output = if requested_auto {
583                cap_cli_to_raw(output, &content, original_tokens)
584            } else {
585                output
586            };
587            let sent = count_tokens(&output);
588            println!("{output}");
589            print_savings(original_tokens, sent);
590            CommandOutput::local(
591                0,
592                Some(Recording::Read {
593                    path: path.to_string(),
594                    mode: mode.to_string(),
595                    input_tokens: original_tokens,
596                    output_tokens: sent,
597                    cache_hit: false,
598                    elapsed: read_start.elapsed(),
599                    excerpt: excerpt(&output),
600                }),
601            )
602        }
603        _ => {
604            // `full` and any unrecognized mode land here. These are
605            // verbatim reads — the prose terse pipeline would mangle source
606            // (dictionary substitutions, line-drop dedup) and break a `full`
607            // read's "complete content" contract, so it must never run here
608            // (#404). Intentionally-lossy modes (map/signatures/aggressive/
609            // entropy/lines) have their own arms above.
610            let mut output = format!("{short} [{line_count}L]\n{content}");
611            if !crate::core::terse::is_verbatim_read("ctx_read", Some(mode)) {
612                let config = crate::core::config::Config::load();
613                let level = crate::core::config::CompressionLevel::effective(&config);
614                if level.is_active() {
615                    let terse_result =
616                        crate::core::terse::pipeline::compress(&output, &level, None);
617                    if terse_result.quality_passed && terse_result.savings_pct >= 3.0 {
618                        output = terse_result.output;
619                    }
620                }
621            }
622            // Full/verbatim reads never beat raw via framing — if terse didn't
623            // compress below the bare file, ship the file itself (#361).
624            let output = cap_cli_to_raw(output, &content, original_tokens);
625            println!("{output}");
626            let sent = count_tokens(&output);
627            CommandOutput::local(
628                0,
629                Some(Recording::Read {
630                    path: path.to_string(),
631                    mode: "full".to_string(),
632                    input_tokens: original_tokens,
633                    output_tokens: sent,
634                    cache_hit: false,
635                    elapsed: read_start.elapsed(),
636                    excerpt: excerpt(&output),
637                }),
638            )
639        }
640    }
641}
642
643pub fn cmd_diff(args: &[String]) {
644    let output =
645        super::context_execution::execute(super::context_execution::ContextCommand::Diff, args);
646    if output.exit_code != 0 {
647        std::process::exit(output.exit_code);
648    }
649}
650
651pub(crate) fn observe_diff<'a>(
652    args: &'a [String],
653    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
654) -> CommandOutput {
655    if args.len() < 2 {
656        eprintln!("Usage: lean-ctx diff <file1> <file2>");
657        return CommandOutput::rejected(1);
658    }
659
660    let path1 = args[0].clone();
661    let path2 = args[1].clone();
662    run_local(Box::new(move || local_diff(&path1, &path2)))
663}
664
665fn local_diff(path1: &str, path2: &str) -> CommandOutput {
666    let content1 = match crate::tools::ctx_read::read_file_lossy(path1) {
667        Ok(c) => c,
668        Err(e) => {
669            eprintln!("Error reading {path1}: {e}");
670            return CommandOutput::local(1, None);
671        }
672    };
673
674    let content2 = match crate::tools::ctx_read::read_file_lossy(path2) {
675        Ok(c) => c,
676        Err(e) => {
677            eprintln!("Error reading {path2}: {e}");
678            return CommandOutput::local(1, None);
679        }
680    };
681
682    let diff = compressor::diff_content(&content1, &content2);
683    let original = count_tokens(&content1) + count_tokens(&content2);
684    let sent = count_tokens(&diff);
685
686    println!(
687        "diff {} {}",
688        protocol::shorten_path(path1),
689        protocol::shorten_path(path2)
690    );
691    println!("{diff}");
692    print_savings(original, sent);
693    CommandOutput::local(
694        0,
695        Some(Recording::Stats {
696            tool: "cli_diff",
697            input_tokens: original,
698            output_tokens: sent,
699        }),
700    )
701}
702
703pub fn cmd_grep(args: &[String]) {
704    let output =
705        super::context_execution::execute(super::context_execution::ContextCommand::Grep, args);
706    if output.exit_code != 0 {
707        std::process::exit(output.exit_code);
708    }
709}
710
711pub(crate) fn observe_grep<'a>(
712    args: &'a [String],
713    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
714) -> CommandOutput {
715    if args.is_empty() {
716        eprintln!("Usage: lean-ctx grep <pattern> [path]");
717        return CommandOutput::rejected(1);
718    }
719
720    let pattern = args[0].clone();
721    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
722    let path = resolve_cli_path(raw_path);
723
724    #[cfg(unix)]
725    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
726        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
727            "ctx_search",
728            Some(serde_json::json!({
729                "pattern": pattern.clone(),
730                "path": path.clone(),
731            })),
732        ) {
733            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
734            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
735                let out = super::common::filter_daemon_output(&text);
736                println!("{out}");
737                let exit_code = if is_error { 2 } else { grep_exit_status(&out) };
738                return CommandOutput::daemon(exit_code);
739            }
740            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
741                eprintln!("Error: daemon result uncertain: {message}");
742                return CommandOutput::daemon(2);
743            }
744        }
745    }
746    super::common::daemon_fallback_hint();
747
748    run_local(Box::new(move || local_grep(pattern, path)))
749}
750
751fn local_grep(pattern: String, path: String) -> CommandOutput {
752    // Search latency for the Context IR lineage (#566), standalone path only.
753    let search_start = std::time::Instant::now();
754
755    let outcome = crate::tools::ctx_search::handle(
756        &pattern,
757        &path,
758        None,
759        20,
760        crate::tools::CrpMode::effective(),
761        true,
762        roles::active_role().io.allow_secret_paths,
763        false,
764    );
765    let out = outcome.text;
766    println!("{out}");
767    let output_tokens = count_tokens(&out);
768    let exit_code = grep_exit_status(&out);
769    CommandOutput::local(
770        exit_code,
771        Some(Recording::Search {
772            modeled_baseline: outcome.modeled_baseline,
773            observed_tokens: outcome.observed_tokens,
774            output_tokens,
775            pattern,
776            path,
777            elapsed: search_start.elapsed(),
778            excerpt: excerpt(&out),
779        }),
780    )
781}
782
783/// grep-compatible exit status for `lean-ctx grep` output (#1917).
784///
785/// `0` = matches found, `1` = searched everything and found nothing,
786/// `2` = error or an incomplete search (files skipped, time budget hit).
787/// A plain `1` after skipping files would tell scripts and agents "not
788/// present" when the content was never examined.
789fn grep_exit_status(out: &str) -> i32 {
790    let out = out.trim_start();
791    if out.starts_with("ERROR") {
792        return 2;
793    }
794    if !out.starts_with("0 matches") {
795        return 0;
796    }
797    if out.contains("skipped") || out.contains("stopped") {
798        2
799    } else {
800        1
801    }
802}
803
804/// `lean-ctx glob <pattern> [path]` — find files by glob pattern, shares the
805/// exact `ctx_glob` core so the CLI, the MCP tool, and the shadow-mode redirect
806/// (#556) all return identical results. Prefers the daemon (warms its cache),
807/// falling back to an in-process call.
808pub fn cmd_glob(args: &[String]) {
809    let output =
810        super::context_execution::execute(super::context_execution::ContextCommand::Glob, args);
811    if output.exit_code != 0 {
812        std::process::exit(output.exit_code);
813    }
814}
815
816pub(crate) fn observe_glob<'a>(
817    args: &'a [String],
818    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
819) -> CommandOutput {
820    if args.is_empty() {
821        eprintln!("Usage: lean-ctx glob <pattern> [path]");
822        return CommandOutput::rejected(1);
823    }
824
825    let pattern = args[0].clone();
826    let raw_path = args.get(1).map_or(".", std::string::String::as_str);
827    let path = resolve_cli_path(raw_path);
828
829    #[cfg(unix)]
830    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
831        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
832            "ctx_glob",
833            Some(serde_json::json!({
834                "pattern": pattern.clone(),
835                "path": path.clone(),
836            })),
837        ) {
838            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
839            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
840                let out = super::common::filter_daemon_output(&text);
841                println!("{out}");
842                return CommandOutput::daemon(i32::from(is_error));
843            }
844            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
845                eprintln!("Error: daemon result uncertain: {message}");
846                return CommandOutput::daemon(1);
847            }
848        }
849    }
850    super::common::daemon_fallback_hint();
851
852    run_local(Box::new(move || local_glob(&pattern, &path)))
853}
854
855fn local_glob(pattern: &str, path: &str) -> CommandOutput {
856    let (out, _original) = crate::tools::ctx_glob::handle(
857        pattern,
858        path,
859        true,
860        roles::active_role().io.allow_secret_paths,
861        200,
862    );
863    println!("{out}");
864    let exit_code = i32::from(out.starts_with("ERROR:"));
865    CommandOutput::local(
866        exit_code,
867        Some(Recording::Stats {
868            tool: "cli_glob",
869            input_tokens: 0,
870            output_tokens: 0,
871        }),
872    )
873}
874
875pub fn cmd_find(args: &[String]) {
876    let output =
877        super::context_execution::execute(super::context_execution::ContextCommand::Find, args);
878    if output.exit_code != 0 {
879        std::process::exit(output.exit_code);
880    }
881}
882
883pub(crate) fn observe_find<'a>(
884    args: &'a [String],
885    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
886) -> CommandOutput {
887    if args.is_empty() {
888        eprintln!("Usage: lean-ctx find <pattern> [path]");
889        return CommandOutput::rejected(1);
890    }
891
892    let raw_pattern = args[0].clone();
893    let path = args
894        .get(1)
895        .map_or(".", std::string::String::as_str)
896        .to_string();
897    run_local(Box::new(move || local_find(&raw_pattern, &path)))
898}
899
900fn local_find(raw_pattern: &str, path: &str) -> CommandOutput {
901    let is_glob = raw_pattern.contains('*') || raw_pattern.contains('?');
902    let glob_matcher = if is_glob {
903        glob::Pattern::new(&raw_pattern.to_lowercase()).ok()
904    } else {
905        None
906    };
907    let substring = raw_pattern.to_lowercase();
908
909    let mut found = false;
910    let walk_root = crate::core::walk_filter::explicit_walk_root(Path::new(path));
911    for entry in ignore::WalkBuilder::new(&walk_root)
912        // #1792: a tracked dotfile is part of the project. `.gitignore` already
913        // decides membership, and it is honoured below.
914        .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
915        .git_ignore(true)
916        .git_global(true)
917        .git_exclude(true)
918        .require_git(false)
919        .max_depth(Some(10))
920        .filter_entry(crate::core::walk_filter::keep_entry)
921        .build()
922        .flatten()
923    {
924        let name = entry.file_name().to_string_lossy().to_lowercase();
925        let matches = if let Some(ref g) = glob_matcher {
926            g.matches(&name)
927        } else {
928            name.contains(&substring)
929        };
930        if matches {
931            println!("{}", entry.path().display());
932            found = true;
933        }
934    }
935
936    CommandOutput::local(
937        i32::from(!found),
938        Some(Recording::Stats {
939            tool: "cli_find",
940            input_tokens: 0,
941            output_tokens: 0,
942        }),
943    )
944}
945
946pub fn cmd_ls(args: &[String]) {
947    let output =
948        super::context_execution::execute(super::context_execution::ContextCommand::Ls, args);
949    if output.exit_code != 0 {
950        std::process::exit(output.exit_code);
951    }
952}
953
954pub(crate) fn observe_ls<'a>(
955    args: &'a [String],
956    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
957) -> CommandOutput {
958    let mut raw_path = ".".to_string();
959    let mut depth = 3usize;
960    let mut show_hidden = false;
961    let mut respect_gitignore = true;
962    let mut i = 0;
963
964    while i < args.len() {
965        let arg = &args[i];
966        if arg == "--depth" {
967            i += 1;
968            if let Some(d) = args.get(i).and_then(|s| s.parse::<usize>().ok()) {
969                depth = d.min(10);
970            }
971        } else if arg == "--all" || arg == "-a" {
972            show_hidden = true;
973        } else if arg == "--no-gitignore" {
974            respect_gitignore = false;
975        } else if arg.starts_with('-') {
976            eprintln!("Error: lean-ctx ls does not support flag '{arg}'.\n");
977            eprintln!(
978                "lean-ctx ls is a compressed directory tree viewer for AI context, not a drop-in ls replacement."
979            );
980            eprintln!(
981                "The shell hook (lean-ctx -t ls {arg} ...) passes flags to system ls transparently.\n"
982            );
983            eprintln!("Usage: lean-ctx ls [path] [--depth N] [--all] [--no-gitignore]");
984            return CommandOutput::rejected(1);
985        } else {
986            raw_path.clone_from(arg);
987        }
988        i += 1;
989    }
990
991    let abs_path = resolve_cli_path(&raw_path);
992    let path = abs_path;
993
994    #[cfg(unix)]
995    if !crate::core::pathutil::is_under_tcc_protected_dir(Path::new(&path)) {
996        match crate::daemon_client::try_daemon_tool_call_blocking_observed(
997            "ctx_tree",
998            Some(serde_json::json!({
999                "path": path.clone(),
1000                "depth": depth,
1001                "show_hidden": show_hidden,
1002                "respect_gitignore": respect_gitignore,
1003            })),
1004        ) {
1005            crate::daemon_client::DaemonToolCallOutcome::Unavailable => {}
1006            crate::daemon_client::DaemonToolCallOutcome::Completed { text, is_error } => {
1007                let out = super::common::filter_daemon_output(&text);
1008                println!("{out}");
1009                return CommandOutput::daemon(i32::from(is_error));
1010            }
1011            crate::daemon_client::DaemonToolCallOutcome::Uncertain { message } => {
1012                eprintln!("Error: daemon result uncertain: {message}");
1013                return CommandOutput::daemon(1);
1014            }
1015        }
1016    }
1017    super::common::daemon_fallback_hint();
1018
1019    run_local(Box::new(move || {
1020        local_ls(&path, depth, show_hidden, respect_gitignore)
1021    }))
1022}
1023
1024fn local_ls(path: &str, depth: usize, show_hidden: bool, respect_gitignore: bool) -> CommandOutput {
1025    let (out, original) =
1026        crate::tools::ctx_tree::handle(path, depth, show_hidden, respect_gitignore);
1027    if out.starts_with("ERROR:") {
1028        eprintln!("{out}");
1029        std::process::exit(1);
1030    }
1031    println!("{out}");
1032    CommandOutput::local(
1033        0,
1034        Some(Recording::Tree {
1035            input_tokens: original,
1036            output_tokens: count_tokens(&out),
1037        }),
1038    )
1039}
1040
1041pub fn cmd_deps(args: &[String]) {
1042    let output =
1043        super::context_execution::execute(super::context_execution::ContextCommand::Deps, args);
1044    if output.exit_code != 0 {
1045        std::process::exit(output.exit_code);
1046    }
1047}
1048
1049pub(crate) fn observe_deps<'a>(
1050    args: &'a [String],
1051    run_local: impl FnOnce(LocalOperation<'a>) -> CommandOutput,
1052) -> CommandOutput {
1053    let path = args
1054        .first()
1055        .map_or(".", std::string::String::as_str)
1056        .to_string();
1057    run_local(Box::new(move || local_deps(&path)))
1058}
1059
1060fn local_deps(path: &str) -> CommandOutput {
1061    if let Some(result) = deps_cmd::detect_and_compress(path) {
1062        println!("{result}");
1063        CommandOutput::local(
1064            0,
1065            Some(Recording::Stats {
1066                tool: "cli_deps",
1067                input_tokens: 0,
1068                output_tokens: 0,
1069            }),
1070        )
1071    } else {
1072        eprintln!("No dependency file found in {path}");
1073        CommandOutput::local(1, None)
1074    }
1075}
1076
1077#[cfg(test)]
1078#[path = "read_cmd_adapter_tests.rs"]
1079mod adapter_tests;
1080
1081#[cfg(all(test, unix))]
1082mod empty_daemon_tests {
1083    use super::is_failed_daemon_result;
1084
1085    #[test]
1086    fn detects_tcc_empty_stub() {
1087        assert!(is_failed_daemon_result(
1088            "file.rs 0L
1089"
1090        ));
1091        assert!(is_failed_daemon_result(
1092            "F1=file.rs 0L
1093[lean-ctx: 0 tok saved]"
1094        ));
1095    }
1096
1097    #[test]
1098    fn accepts_real_content() {
1099        assert!(!is_failed_daemon_result(
1100            "file.rs 10L
1101fn main() {}
1102"
1103        ));
1104    }
1105
1106    #[test]
1107    fn accepts_nonzero_line_count() {
1108        assert!(!is_failed_daemon_result(
1109            "file.rs 1L
1110"
1111        ));
1112    }
1113
1114    #[test]
1115    fn ignores_structure_markers_in_body() {
1116        assert!(is_failed_daemon_result(
1117            "file.rs 0L
1118[no extractable structure for .rs]
1119"
1120        ));
1121    }
1122
1123    #[test]
1124    fn detects_tcc_restricted_marker() {
1125        assert!(is_failed_daemon_result(
1126            "ERROR:TCC_RESTRICTED: daemon cannot access /Users/me/Documents/proj (sandboxed)"
1127        ));
1128    }
1129
1130    #[test]
1131    fn detects_daemon_project_root_denial() {
1132        assert!(is_failed_daemon_result(
1133            "ERROR: path escapes project root: /work/current/scripts (root: /work/stale)"
1134        ));
1135    }
1136}
1137
1138#[cfg(test)]
1139mod cap_tests {
1140    use super::{cap_cli_to_raw, count_tokens};
1141
1142    #[test]
1143    fn caps_to_raw_when_framing_inflates() {
1144        // A tiny file: the `path [NL]` header (+ any footer) pushes the framed
1145        // payload past the bare content, so the cap must ship the content
1146        // verbatim — the additive CLI default must never inflate a read (#361).
1147        let raw = "x = 1\n";
1148        let raw_tokens = count_tokens(raw);
1149        let framed = format!("some/very/long/path/header.rs [1L]\n{raw}\n[lean-ctx: 0 tok saved]");
1150        assert!(count_tokens(&framed) > raw_tokens, "fixture must inflate");
1151        assert_eq!(cap_cli_to_raw(framed, raw, raw_tokens), raw);
1152    }
1153
1154    #[test]
1155    fn keeps_framing_when_it_saves() {
1156        // A genuinely compressed payload (fewer tokens than raw) is kept as-is.
1157        let raw = "fn a() {}\n".repeat(300);
1158        let raw_tokens = count_tokens(&raw);
1159        let framed = "f.rs [300L]\nfn a() {} …".to_string();
1160        assert!(count_tokens(&framed) < raw_tokens);
1161        assert_eq!(cap_cli_to_raw(framed.clone(), &raw, raw_tokens), framed);
1162    }
1163
1164    #[test]
1165    fn keeps_framing_for_empty_file() {
1166        // raw_tokens == 0 disables the cap so an empty file still gets a signal.
1167        let framed = "empty.rs [0L]\n".to_string();
1168        assert_eq!(cap_cli_to_raw(framed.clone(), "", 0), framed);
1169    }
1170
1171    #[test]
1172    fn break_even_is_not_inflation() {
1173        // Equal token counts use strict `>`, so framing is preserved at break-even.
1174        let raw = "alpha beta gamma delta";
1175        let raw_tokens = count_tokens(raw);
1176        let framed = raw.to_string();
1177        assert_eq!(count_tokens(&framed), raw_tokens);
1178        assert_eq!(cap_cli_to_raw(framed.clone(), raw, raw_tokens), framed);
1179    }
1180
1181    #[test]
1182    fn emitted_never_exceeds_raw_across_sizes() {
1183        // The invariant itself: for any bloated framing over a non-empty file the
1184        // emitted token count is ≤ the raw token count.
1185        for n in [1usize, 5, 50, 500] {
1186            let raw = "data line here\n".repeat(n);
1187            let raw_tokens = count_tokens(&raw);
1188            let framed = format!("a/b/c/path.txt [{n}L]\n{raw}\n[lean-ctx: {n} tok saved ({n}%)]");
1189            let out = cap_cli_to_raw(framed, &raw, raw_tokens);
1190            assert!(
1191                count_tokens(&out) <= raw_tokens,
1192                "n={n}: emitted {} tok exceeds raw {raw_tokens}",
1193                count_tokens(&out)
1194            );
1195        }
1196    }
1197}
1198
1199#[cfg(test)]
1200mod fresh_tests {
1201    use super::{cmd_read, should_force_fresh};
1202
1203    #[test]
1204    fn invalid_request_returns_control_to_lifecycle_caller() {
1205        assert!(!cmd_read(&[]));
1206    }
1207
1208    #[test]
1209    fn hook_child_forces_fresh_even_without_flags() {
1210        // #1037: a hook child must always read verbatim (no `cached … [NL]` stub),
1211        // even when the caller passed no `--fresh`/`--no-cache` flag.
1212        assert!(should_force_fresh(&[], true));
1213        assert!(!should_force_fresh(&[], false));
1214    }
1215
1216    #[test]
1217    fn explicit_flags_force_fresh() {
1218        assert!(should_force_fresh(&["--fresh".to_string()], false));
1219        assert!(should_force_fresh(&["--no-cache".to_string()], false));
1220        assert!(!should_force_fresh(&["file.rs".to_string()], false));
1221    }
1222}
1223
1224/// #1903: the CLI read boundary must match MCP `ctx_read` (same resolver,
1225/// same verdict, same error text).
1226#[cfg(test)]
1227mod jail_parity_tests {
1228    use super::jail_cli_read_path;
1229    use crate::core::path_resolve::resolve_tool_path;
1230
1231    fn project() -> (tempfile::TempDir, String) {
1232        let tmp = tempfile::tempdir().unwrap();
1233        let root = tmp.path().join("proj");
1234        std::fs::create_dir_all(&root).unwrap();
1235        std::fs::write(root.join("inside.txt"), "in").unwrap();
1236        std::fs::write(tmp.path().join("outside.txt"), "out").unwrap();
1237        (tmp, root.to_string_lossy().into_owned())
1238    }
1239
1240    // Parity holds in every build: with the `no-jail` feature both paths admit
1241    // the read, otherwise both refuse it with the same text.
1242    #[test]
1243    fn out_of_root_read_is_denied_like_mcp() {
1244        // Both paths render the effective config location into the denial, so
1245        // a concurrent test must not move LEAN_CTX_CONFIG_DIR between them.
1246        let _env = crate::core::data_dir::test_env_lock();
1247        let (_tmp, root) = project();
1248        for raw in [
1249            format!("{root}/../outside.txt"),
1250            format!("{root}/../../../../../../etc/hosts"),
1251        ] {
1252            let cli = jail_cli_read_path(&raw, &root);
1253            let mcp = resolve_tool_path(Some(&root), None, &raw);
1254            assert_eq!(cli, mcp, "CLI and MCP must decide {raw} alike");
1255            if !cfg!(feature = "no-jail") {
1256                let err = cli.expect_err("CLI must deny out-of-root");
1257                assert!(err.contains("path escapes project root"), "{err}");
1258            }
1259        }
1260    }
1261
1262    #[test]
1263    fn in_root_read_resolves_like_mcp() {
1264        let (_tmp, root) = project();
1265        let raw = format!("{root}/inside.txt");
1266        let cli = jail_cli_read_path(&raw, &root).unwrap();
1267        assert_eq!(cli, resolve_tool_path(Some(&root), None, &raw).unwrap());
1268        assert_eq!(std::fs::read_to_string(&cli).unwrap(), "in");
1269    }
1270
1271    #[test]
1272    fn broad_root_is_refused() {
1273        let Some(home) = dirs::home_dir() else { return };
1274        let home = home.to_string_lossy().into_owned();
1275        let err = jail_cli_read_path(&format!("{home}/.profile"), &home).unwrap_err();
1276        assert!(err.contains("no project detected"), "{err}");
1277    }
1278
1279    #[test]
1280    fn secret_path_enforcement_matches_mcp() {
1281        let _env = crate::core::data_dir::test_env_lock();
1282        let (_tmp, root) = project();
1283        let secret = format!("{root}/.env");
1284        std::fs::write(&secret, "TOKEN=x").unwrap();
1285        let prev = std::env::var("LEAN_CTX_IO_BOUNDARY_MODE").ok();
1286        crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", "enforce");
1287        let cli = jail_cli_read_path(&secret, &root);
1288        let mcp = resolve_tool_path(Some(&root), None, &secret);
1289        match prev {
1290            Some(v) => crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", v),
1291            None => crate::test_env::remove_var("LEAN_CTX_IO_BOUNDARY_MODE"),
1292        }
1293        let cli = cli.expect_err("enforce mode must refuse a secret path");
1294        assert_eq!(cli, mcp.unwrap_err());
1295        assert!(cli.contains("Secret-like path"), "{cli}");
1296    }
1297}
1298
1299#[cfg(test)]
1300mod mode_arg_tests {
1301    use super::resolve_cli_read_mode;
1302
1303    fn args(list: &[&str]) -> Vec<String> {
1304        list.iter().map(ToString::to_string).collect()
1305    }
1306
1307    // `lean-ctx read f.ps1 map` used to silently IGNORE the positional mode and
1308    // serve the `auto` default — reads must honour it like `--mode map`
1309    // (limitations audit 2026-07-03).
1310    #[test]
1311    fn positional_mode_is_honoured() {
1312        assert_eq!(resolve_cli_read_mode(&args(&["f.ps1", "map"])), "map");
1313        assert_eq!(
1314            resolve_cli_read_mode(&args(&["f.rs", "lines:5-10"])),
1315            "lines:5-10"
1316        );
1317    }
1318
1319    #[test]
1320    fn mode_flag_wins_over_positional() {
1321        assert_eq!(
1322            resolve_cli_read_mode(&args(&["f.rs", "map", "--mode", "signatures"])),
1323            "signatures"
1324        );
1325        assert_eq!(
1326            resolve_cli_read_mode(&args(&["f.rs", "-m", "full"])),
1327            "full"
1328        );
1329    }
1330
1331    #[test]
1332    fn defaults_to_auto_and_skips_flags_and_junk() {
1333        assert_eq!(resolve_cli_read_mode(&args(&["f.rs"])), "auto");
1334        assert_eq!(resolve_cli_read_mode(&args(&["f.rs", "--fresh"])), "auto");
1335        // An unknown positional is not silently treated as a mode.
1336        assert_eq!(resolve_cli_read_mode(&args(&["f.rs", "banana"])), "auto");
1337    }
1338}
1339
1340/// #1889: the CLI and the MCP server must render the same symbol lines (and
1341/// the same TDD legend) for map/signatures under every CRP mode.
1342#[cfg(test)]
1343mod crp_parity_tests {
1344    use super::push_signature_lines;
1345    use crate::core::cache::SessionCache;
1346    use crate::core::signatures;
1347    use crate::tools::CrpMode;
1348
1349    /// Bodies are long so map/signatures are clearly smaller than the file —
1350    /// otherwise the MCP never-inflate guard serves the raw file instead.
1351    fn src() -> String {
1352        use std::fmt::Write as _;
1353        let body = (0..60).fold(String::new(), |mut acc, i| {
1354            let _ = writeln!(acc, "    let v{i} = source.len() as u64 + {i};");
1355            acc
1356        });
1357        format!(
1358            "pub struct Totals {{ pub n: u64 }}\n\n\
1359             pub fn count_source(source: &'static str) -> u64 {{\n{body}    0\n}}\n\n\
1360             pub fn source_counts() -> Vec<(&'static str, u64)> {{\n    let source = \"\";\n{body}    Vec::new()\n}}\n\n\
1361             fn private_helper(x: i32) -> i32 {{\n    let source = \"\";\n{body}    x + 1\n}}\n"
1362        )
1363    }
1364
1365    fn mcp(mode: &str, crp: CrpMode) -> String {
1366        let dir = tempfile::tempdir().unwrap();
1367        let file = dir.path().join("parity.rs");
1368        std::fs::write(&file, src()).unwrap();
1369        let mut cache = SessionCache::new();
1370        crate::tools::ctx_read::handle_fresh(&mut cache, &file.to_string_lossy(), mode, crp)
1371    }
1372
1373    fn assert_lines_in(cli: &str, mcp: &str, what: &str) {
1374        for line in cli.lines().map(str::trim).filter(|l| !l.is_empty()) {
1375            assert!(
1376                mcp.lines()
1377                    .any(|m| m.trim_start().starts_with(line) || m.contains(line)),
1378                "{what}: CLI line `{line}` missing from MCP output:\n{mcp}"
1379            );
1380        }
1381    }
1382
1383    #[test]
1384    fn signatures_match_mcp_for_every_crp_mode() {
1385        let sigs = signatures::extract_signatures(&src(), "rs");
1386        let refs: Vec<&signatures::Signature> = sigs.iter().collect();
1387        for crp in [CrpMode::Off, CrpMode::Compact, CrpMode::Tdd] {
1388            let mut cli = String::new();
1389            push_signature_lines(&mut cli, &refs, crp, "", false);
1390            assert_lines_in(&cli, &mcp("signatures", crp), crp.as_str());
1391            assert_eq!(
1392                cli.contains("λ=fn"),
1393                crp.is_tdd(),
1394                "legend iff tdd ({crp:?})"
1395            );
1396        }
1397    }
1398
1399    #[test]
1400    fn map_api_matches_mcp_for_every_crp_mode() {
1401        let sigs = signatures::extract_signatures(&src(), "rs");
1402        let key: Vec<&signatures::Signature> = sigs
1403            .iter()
1404            .filter(|s| s.is_exported || s.indent == 0)
1405            .collect();
1406        for crp in [CrpMode::Off, CrpMode::Compact, CrpMode::Tdd] {
1407            let mut cli = String::from("  API:");
1408            push_signature_lines(&mut cli, &key, crp, "    ", true);
1409            let out = mcp("map", crp);
1410            let api_header = cli.lines().next().unwrap();
1411            assert!(
1412                out.contains(api_header),
1413                "{crp:?}: header `{api_header}` in\n{out}"
1414            );
1415            assert_lines_in(&cli, &out, crp.as_str());
1416        }
1417    }
1418
1419    #[test]
1420    fn tdd_uses_symbol_notation_not_compact() {
1421        let sigs = signatures::extract_signatures(&src(), "rs");
1422        let refs: Vec<&signatures::Signature> = sigs.iter().collect();
1423        let mut tdd = String::new();
1424        push_signature_lines(&mut tdd, &refs, CrpMode::Tdd, "", false);
1425        assert!(tdd.contains("λ+count_source"), "{tdd}");
1426        assert!(!tdd.contains("fn pub count_source"), "{tdd}");
1427    }
1428}
1429
1430/// #1917: `lean-ctx grep` must not report "not found" (exit 1) when it never
1431/// looked at part of the corpus.
1432#[cfg(test)]
1433mod grep_exit_status_tests {
1434    use super::grep_exit_status;
1435
1436    #[test]
1437    fn matches_exit_zero() {
1438        assert_eq!(grep_exit_status("3 matches in 1 files:\nsrc/a.rs:1 x"), 0);
1439    }
1440
1441    #[test]
1442    fn complete_miss_exits_one() {
1443        assert_eq!(grep_exit_status("0 matches for 'x' (scanned 12 files)"), 1);
1444    }
1445
1446    #[test]
1447    fn incomplete_miss_exits_two() {
1448        for out in [
1449            "0 matches for 'x' (scanned 1 files) (1 large files skipped: big.log)",
1450            "0 matches for 'x' (scanned 4 files)\n(2 files skipped: binary/encoding)",
1451            "0 matches for 'x' (scanned 9 files) (search stopped at the time budget)",
1452        ] {
1453            assert_eq!(grep_exit_status(out), 2, "{out}");
1454        }
1455    }
1456
1457    #[test]
1458    fn errors_exit_two() {
1459        assert_eq!(grep_exit_status("ERROR: /nope does not exist"), 2);
1460        assert_eq!(grep_exit_status("  ERROR: refusing to scan /"), 2);
1461    }
1462}