Skip to main content

lean_ctx/cli/
explore_cmd.rs

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