Skip to main content

lean_ctx_cli/cli/
explore_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx explore` — FastContext-style iterative code exploration (CLI).
3//!
4//! Exposes the same deterministic loop as the `ctx_explore` MCP tool: a bounded
5//! multi-turn search (BM25 + static call/import graph + AST symbols) that returns
6//! compact `path:start-end` citations rather than file bodies. `--json` emits the
7//! citation list for editor/script consumption; `--citation` prints only the
8//! `<final_answer>` block.
9
10use lean_ctx_server::tools::CrpMode;
11use lean_ctx_server::tools::ctx_explore::{self, Citation, ExploreOptions};
12
13/// Parsed `explore` invocation. Separated from execution so flag handling is
14/// unit-testable without running a real search.
15#[derive(Debug, PartialEq)]
16struct Args {
17    query: Option<String>,
18    path: String,
19    max_turns: Option<usize>,
20    citation: bool,
21    json: bool,
22    help: bool,
23}
24
25impl Default for Args {
26    fn default() -> Self {
27        Self {
28            query: None,
29            path: ".".to_string(),
30            max_turns: None,
31            citation: false,
32            json: false,
33            help: false,
34        }
35    }
36}
37
38fn parse_args(args: &[String]) -> Args {
39    let mut parsed = Args::default();
40    let mut i = 0;
41    while i < args.len() {
42        match args[i].as_str() {
43            "--json" => parsed.json = true,
44            "--citation" | "--citations" => parsed.citation = true,
45            "--help" | "-h" => parsed.help = true,
46            "--query" | "-q" => {
47                i += 1;
48                parsed.query = args.get(i).cloned();
49            }
50            "--path" | "-p" => {
51                i += 1;
52                if let Some(v) = args.get(i) {
53                    parsed.path.clone_from(v);
54                }
55            }
56            "--max-turns" | "-t" => {
57                i += 1;
58                parsed.max_turns = args.get(i).and_then(|s| s.parse::<usize>().ok());
59            }
60            // First bare token is the query; later bare tokens are ignored.
61            other if !other.starts_with('-') && parsed.query.is_none() => {
62                parsed.query = Some(other.to_string());
63            }
64            _ => {}
65        }
66        i += 1;
67    }
68    parsed
69}
70
71pub(crate) fn cmd_explore(args: &[String]) {
72    let parsed = parse_args(args);
73
74    if parsed.help {
75        print_help();
76        return;
77    }
78
79    let Some(query) = parsed.query.filter(|q| !q.trim().is_empty()) else {
80        eprintln!(
81            "usage: lean-ctx explore <query> [--citation] [--json] [--max-turns N] [--path DIR]"
82        );
83        std::process::exit(2);
84    };
85
86    let opts = ExploreOptions::new(parsed.max_turns, parsed.citation);
87    // One tool run for the CLI (request scope, capture, release, redaction,
88    // lineage — see `CliToolRun`). The printed text is the released one; a
89    // tool error is reported on stderr and is never a carrier.
90    let json = parsed.json;
91    let run = super::common::CliToolRun::new("ctx_explore", &parsed.path, None);
92    let run = if json { run.human_facing() } else { run };
93    let printed = run.deliver(|| {
94        let outcome = ctx_explore::handle(&query, &parsed.path, CrpMode::Off, &opts);
95        if outcome.text.starts_with("ERROR") {
96            return Err(outcome.text.trim_start_matches("ERROR: ").to_string());
97        }
98        Ok(if json {
99            to_json(&outcome.citations)
100        } else {
101            outcome.text
102        })
103    });
104    match printed {
105        Ok(text) => super::common::print_released(&text),
106        Err(error) => {
107            eprintln!("explore: {error}");
108            std::process::exit(1);
109        }
110    }
111}
112
113/// Serialize citations with stable field names for editors/scripts.
114fn to_json(citations: &[Citation]) -> String {
115    #[derive(serde::Serialize)]
116    struct Cite<'a> {
117        file: &'a str,
118        start: usize,
119        end: usize,
120        label: &'a str,
121    }
122    let out: Vec<Cite> = citations
123        .iter()
124        .map(|c| Cite {
125            file: &c.file,
126            start: c.start,
127            end: c.end,
128            label: &c.label,
129        })
130        .collect();
131    serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
132}
133
134fn print_help() {
135    println!(
136        "lean-ctx explore — iterative code exploration → file:line citations\n\n\
137         USAGE:\n  lean-ctx explore <query> [OPTIONS]\n\n\
138         OPTIONS:\n\
139         \x20 -q, --query <text>     Question or symbol names (or pass as the first argument)\n\
140         \x20 -t, --max-turns <N>    Exploration depth (1-8, default 3)\n\
141         \x20 -p, --path <dir>       Project root to explore (default: cwd)\n\
142         \x20     --citation         Print only the <final_answer> block\n\
143         \x20     --json             Emit JSON array [{{file,start,end,label}}]\n\
144         \x20 -h, --help             Show this help\n\n\
145         vs semantic-search: explore follows the call/import graph over multiple turns;\n\
146         vs compose: explore returns citations (cheap), compose inlines bodies (one shot)."
147    );
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn args(parts: &[&str]) -> Vec<String> {
155        parts.iter().map(|s| (*s).to_string()).collect()
156    }
157
158    #[test]
159    fn parses_positional_query_with_defaults() {
160        let a = parse_args(&args(&["how does caching work"]));
161        assert_eq!(a.query.as_deref(), Some("how does caching work"));
162        assert_eq!(a.path, ".");
163        assert_eq!(a.max_turns, None);
164        assert!(!a.citation);
165        assert!(!a.json);
166    }
167
168    #[test]
169    fn parses_flags() {
170        let a = parse_args(&args(&[
171            "--query",
172            "auth flow",
173            "--max-turns",
174            "5",
175            "--path",
176            "/tmp/p",
177            "--citation",
178            "--json",
179        ]));
180        assert_eq!(a.query.as_deref(), Some("auth flow"));
181        assert_eq!(a.max_turns, Some(5));
182        assert_eq!(a.path, "/tmp/p");
183        assert!(a.citation);
184        assert!(a.json);
185    }
186
187    #[test]
188    fn explicit_query_flag_beats_bare_token() {
189        let a = parse_args(&args(&["--query", "real", "ignored"]));
190        assert_eq!(a.query.as_deref(), Some("real"));
191    }
192
193    #[test]
194    fn json_serializes_citation_fields() {
195        let cites = vec![Citation {
196            file: "src/main.rs".to_string(),
197            start: 12,
198            end: 20,
199            label: "main (fn)".to_string(),
200        }];
201        let v: serde_json::Value = serde_json::from_str(&to_json(&cites)).unwrap();
202        assert_eq!(v[0]["file"], "src/main.rs");
203        assert_eq!(v[0]["start"], 12);
204        assert_eq!(v[0]["end"], 20);
205        assert_eq!(v[0]["label"], "main (fn)");
206    }
207
208    #[test]
209    fn empty_citations_serialize_as_empty_array() {
210        assert_eq!(to_json(&[]), "[]");
211    }
212}