Skip to main content

lean_ctx/setup/
agent_selection.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Which AI tools `setup`, `onboard` and the post-update refresh may touch.
3//!
4//! Precedence: an explicit `--agents` list, then the saved `setup.agents`,
5//! then — for the post-update refresh only — the tools that already carry a
6//! lean-ctx entry. A setup with neither keeps the historical default and
7//! offers every detected tool. An update therefore never connects a tool that
8//! was installed after the last setup.
9
10use std::collections::BTreeSet;
11
12use crate::core::editor_registry::EditorTarget;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum AgentScope {
16    /// Every detected tool (no selection recorded, fresh setup).
17    All,
18    /// Only these agent keys.
19    Only(BTreeSet<String>),
20}
21
22impl AgentScope {
23    #[must_use]
24    pub fn allows(&self, agent_key: &str) -> bool {
25        match self {
26            Self::All => true,
27            Self::Only(keys) => keys.contains(agent_key),
28        }
29    }
30}
31
32/// One selectable tool. Several registry targets can share an agent key
33/// (Augment CLI + VS Code, Cline + Cline CLI, Qoder paths); they are one choice.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct DetectedAgent {
36    pub key: String,
37    pub label: String,
38    /// Already carries a lean-ctx entry from an earlier setup.
39    pub connected: bool,
40}
41
42/// `pi` has no MCP target (its integration is the pi-lean-ctx package, see
43/// `editor_registry::detect`) but is an `init --agent` and rules target.
44const PI_KEY: &str = "pi";
45
46/// Agent keys `--agents` and `setup.agents` accept.
47#[must_use]
48pub fn known_agent_keys(targets: &[EditorTarget]) -> BTreeSet<String> {
49    let mut keys: BTreeSet<String> = targets
50        .iter()
51        .filter(|t| !t.agent_key.is_empty())
52        .map(|t| t.agent_key.clone())
53        .collect();
54    keys.insert(PI_KEY.to_string());
55    keys
56}
57
58/// Parse a `--agents` value: comma-separated agent keys, or `none` to connect
59/// no tool at all. Unknown names are an error, never silently dropped.
60pub fn parse_agent_list(raw: &str, known: &BTreeSet<String>) -> Result<BTreeSet<String>, String> {
61    let items: Vec<String> = raw
62        .split(',')
63        .map(|s| s.trim().to_ascii_lowercase())
64        .filter(|s| !s.is_empty())
65        .collect();
66    if items.is_empty() {
67        return Err("--agents needs a comma-separated list of agent keys (or `none`)".to_string());
68    }
69    if items == ["none"] {
70        return Ok(BTreeSet::new());
71    }
72    let unknown: Vec<&str> = items
73        .iter()
74        .filter(|item| !known.contains(*item))
75        .map(String::as_str)
76        .collect();
77    if !unknown.is_empty() {
78        return Err(format!(
79            "unknown agent(s): {}\nKnown agents: {}",
80            unknown.join(", "),
81            known.iter().cloned().collect::<Vec<_>>().join(", ")
82        ));
83    }
84    Ok(items.into_iter().collect())
85}
86
87/// Pull `--agents <list>` / `--agents=<list>` out of CLI args. Returns the
88/// remaining args and the raw list; `Err` when the flag has no value.
89pub fn take_agents_flag(args: &[String]) -> Result<(Vec<String>, Option<String>), String> {
90    let mut rest = Vec::with_capacity(args.len());
91    let mut raw = None;
92    let mut iter = args.iter();
93    while let Some(arg) = iter.next() {
94        if let Some(value) = arg.strip_prefix("--agents=") {
95            raw = Some(value.to_string());
96        } else if arg == "--agents" {
97            match iter.next() {
98                Some(value) if !value.starts_with('-') => raw = Some(value.clone()),
99                _ => {
100                    return Err(
101                        "--agents needs a value, e.g. --agents claude,cursor (or none)".to_string(),
102                    );
103                }
104            }
105        } else {
106            rest.push(arg.clone());
107        }
108    }
109    Ok((rest, raw))
110}
111
112/// Resolve the scope for one run. `connected` is only evaluated for the
113/// post-update refresh without a recorded choice.
114pub fn resolve_scope(
115    explicit: Option<&BTreeSet<String>>,
116    saved: Option<&[String]>,
117    refresh_only: bool,
118    connected: impl FnOnce() -> BTreeSet<String>,
119) -> AgentScope {
120    if let Some(keys) = explicit {
121        return AgentScope::Only(keys.clone());
122    }
123    if let Some(keys) = saved {
124        return AgentScope::Only(keys.iter().map(|k| k.trim().to_ascii_lowercase()).collect());
125    }
126    if refresh_only {
127        return AgentScope::Only(connected());
128    }
129    AgentScope::All
130}
131
132fn has_lean_ctx_entry(path: &std::path::Path) -> bool {
133    std::fs::read_to_string(path).is_ok_and(|content| content.contains("lean-ctx"))
134}
135
136/// Installed tools, one entry per agent key, in registry order.
137#[must_use]
138pub fn detected_agents(home: &std::path::Path, targets: &[EditorTarget]) -> Vec<DetectedAgent> {
139    let mut agents: Vec<DetectedAgent> = Vec::new();
140    for target in targets {
141        if target.agent_key.is_empty() || !target.detect_path.exists() {
142            continue;
143        }
144        let connected = has_lean_ctx_entry(&target.config_path);
145        if let Some(existing) = agents.iter_mut().find(|a| a.key == target.agent_key) {
146            if !existing.label.split(" / ").any(|l| l == target.name) {
147                existing.label = format!("{} / {}", existing.label, target.name);
148            }
149            existing.connected |= connected;
150        } else {
151            agents.push(DetectedAgent {
152                key: target.agent_key.clone(),
153                label: target.name.to_string(),
154                connected,
155            });
156        }
157    }
158    let pi_dir = home.join(".pi");
159    if pi_dir.exists() {
160        agents.push(DetectedAgent {
161            key: PI_KEY.to_string(),
162            label: "Pi Coding Agent".to_string(),
163            connected: has_lean_ctx_entry(&pi_dir.join("rules/lean-ctx.md")),
164        });
165    }
166    agents
167}
168
169/// Agent keys an earlier setup connected (a lean-ctx entry is present).
170#[must_use]
171pub fn connected_agent_keys(home: &std::path::Path, targets: &[EditorTarget]) -> BTreeSet<String> {
172    detected_agents(home, targets)
173        .into_iter()
174        .filter(|a| a.connected)
175        .map(|a| a.key)
176        .collect()
177}
178
179/// Scope for a setup run: `--agents`, then `setup.agents`, then (refresh only)
180/// the already-connected tools, else every detected tool.
181#[must_use]
182pub fn scope_for_run(
183    home: &std::path::Path,
184    targets: &[EditorTarget],
185    explicit: Option<&BTreeSet<String>>,
186    refresh_only: bool,
187) -> AgentScope {
188    let saved = crate::core::config::Config::load_global().setup.agents;
189    resolve_scope(explicit, saved.as_deref(), refresh_only, || {
190        connected_agent_keys(home, targets)
191    })
192}
193
194/// Record the choice so later updates refresh exactly these tools.
195pub fn save_selection(keys: &BTreeSet<String>) -> Result<(), String> {
196    crate::core::config::Config::update_global(|cfg| {
197        cfg.setup.agents = Some(keys.iter().cloned().collect());
198    })
199    .map(|_| ())
200    .map_err(|e| format!("could not save the agent selection: {e}"))
201}
202
203/// `init --agent <key>` connects a tool on purpose: add it to a recorded
204/// selection so later updates keep it current. Without a recorded selection
205/// nothing is written — updates already follow the connected tools.
206pub fn remember_connected_agent(agent_key: &str) -> Result<(), String> {
207    let key = agent_key.trim().to_ascii_lowercase();
208    let Some(mut saved) = crate::core::config::Config::load_global().setup.agents else {
209        return Ok(());
210    };
211    if saved.iter().any(|k| k.eq_ignore_ascii_case(&key)) {
212        return Ok(());
213    }
214    let Some(home) = crate::core::home::resolve_home_dir() else {
215        return Ok(());
216    };
217    if !known_agent_keys(&crate::core::editor_registry::build_targets(&home)).contains(&key) {
218        return Ok(());
219    }
220    saved.push(key);
221    save_selection(&saved.into_iter().collect())
222}
223
224/// Interpret the answer to the selection prompt. Empty keeps `default`;
225/// otherwise `all`, `none`, or numbers / agent keys separated by commas or
226/// spaces select exactly those tools.
227pub fn parse_selection_answer(
228    answer: &str,
229    agents: &[DetectedAgent],
230    default: &BTreeSet<String>,
231) -> Result<BTreeSet<String>, String> {
232    let answer = answer.trim().to_ascii_lowercase();
233    match answer.as_str() {
234        "" => return Ok(default.clone()),
235        "all" | "a" => return Ok(agents.iter().map(|a| a.key.clone()).collect()),
236        "none" | "n" => return Ok(BTreeSet::new()),
237        _ => {}
238    }
239    let mut selected = BTreeSet::new();
240    for token in answer
241        .split(|c: char| c == ',' || c.is_whitespace())
242        .filter(|t| !t.is_empty())
243    {
244        let agent = match token.parse::<usize>() {
245            Ok(n) => n.checked_sub(1).and_then(|i| agents.get(i)),
246            Err(_) => agents.iter().find(|a| a.key == token),
247        };
248        match agent {
249            Some(agent) => {
250                selected.insert(agent.key.clone());
251            }
252            None => return Err(format!("'{token}' is not in the list")),
253        }
254    }
255    Ok(selected)
256}
257
258/// Default for the prompt: the recorded choice, else the connected tools,
259/// else (first setup) every detected tool.
260#[must_use]
261pub fn prompt_default(agents: &[DetectedAgent], saved: Option<&[String]>) -> BTreeSet<String> {
262    let detected: BTreeSet<String> = agents.iter().map(|a| a.key.clone()).collect();
263    if let Some(saved) = saved {
264        return saved
265            .iter()
266            .map(|k| k.trim().to_ascii_lowercase())
267            .filter(|k| detected.contains(k))
268            .collect();
269    }
270    let connected: BTreeSet<String> = agents
271        .iter()
272        .filter(|a| a.connected)
273        .map(|a| a.key.clone())
274        .collect();
275    if connected.is_empty() {
276        detected
277    } else {
278        connected
279    }
280}
281
282/// Ask which detected tools lean-ctx should connect. Reads stdin; callers
283/// must only use it on an interactive terminal.
284#[must_use]
285pub fn prompt_agent_selection(
286    agents: &[DetectedAgent],
287    default: &BTreeSet<String>,
288) -> BTreeSet<String> {
289    use std::io::Write;
290
291    let dim = "\x1b[2m";
292    let bold = "\x1b[1m";
293    let rst = "\x1b[0m";
294    println!("  Which AI tools should lean-ctx connect to?");
295    for (i, agent) in agents.iter().enumerate() {
296        let mark = if default.contains(&agent.key) {
297            "x"
298        } else {
299            " "
300        };
301        let state = if agent.connected { " (connected)" } else { "" };
302        println!(
303            "    [{mark}] {:>2}. {:<28} {dim}{}{state}{rst}",
304            i + 1,
305            agent.label,
306            agent.key
307        );
308    }
309    println!(
310        "  {dim}Enter = keep [x] · numbers or names (e.g. 1,3 or claude cursor) · all · none{rst}"
311    );
312    for _ in 0..3 {
313        print!("  {bold}>{rst} ");
314        std::io::stdout().flush().ok();
315        let mut input = String::new();
316        if std::io::stdin().read_line(&mut input).unwrap_or(0) == 0 {
317            return default.clone();
318        }
319        match parse_selection_answer(&input, agents, default) {
320            Ok(selected) => return selected,
321            Err(e) => println!("  \x1b[33m{e}{rst} — try again"),
322        }
323    }
324    println!("  {dim}Keeping the marked selection.{rst}");
325    default.clone()
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    fn keys(items: &[&str]) -> BTreeSet<String> {
333        items.iter().map(ToString::to_string).collect()
334    }
335
336    fn agents() -> Vec<DetectedAgent> {
337        ["claude", "cursor", "codex"]
338            .iter()
339            .enumerate()
340            .map(|(i, key)| DetectedAgent {
341                key: (*key).to_string(),
342                label: key.to_uppercase(),
343                connected: i == 0,
344            })
345            .collect()
346    }
347
348    #[test]
349    fn agents_flag_validates_names() {
350        let known = keys(&["claude", "cursor", "codex", "pi"]);
351        assert_eq!(
352            parse_agent_list("Claude, cursor", &known).unwrap(),
353            keys(&["claude", "cursor"])
354        );
355        assert_eq!(parse_agent_list("none", &known).unwrap(), keys(&[]));
356        let err = parse_agent_list("claude,vscodee", &known).unwrap_err();
357        assert!(err.contains("unknown agent(s): vscodee"), "{err}");
358        assert!(
359            err.contains("Known agents: claude, codex, cursor, pi"),
360            "{err}"
361        );
362        assert!(parse_agent_list(" , ", &known).is_err());
363    }
364
365    #[test]
366    fn agents_flag_is_extracted_in_both_spellings() {
367        let args: Vec<String> = ["--yes", "--agents", "claude,cursor", "--json"]
368            .iter()
369            .map(ToString::to_string)
370            .collect();
371        let (rest, raw) = take_agents_flag(&args).unwrap();
372        assert_eq!(rest, ["--yes", "--json"]);
373        assert_eq!(raw.as_deref(), Some("claude,cursor"));
374
375        let (rest, raw) = take_agents_flag(&["--agents=codex".to_string()]).unwrap();
376        assert!(rest.is_empty());
377        assert_eq!(raw.as_deref(), Some("codex"));
378
379        assert!(take_agents_flag(&["--agents".to_string()]).is_err());
380        assert!(take_agents_flag(&["--agents".to_string(), "--yes".to_string()]).is_err());
381    }
382
383    #[test]
384    fn explicit_beats_saved_beats_connected() {
385        let explicit = keys(&["codex"]);
386        let saved = vec!["Cursor".to_string()];
387        let never = || -> BTreeSet<String> { panic!("connected must not be evaluated") };
388
389        assert_eq!(
390            resolve_scope(Some(&explicit), Some(&saved), true, never),
391            AgentScope::Only(explicit.clone())
392        );
393        assert_eq!(
394            resolve_scope(None, Some(&saved), true, never),
395            AgentScope::Only(keys(&["cursor"]))
396        );
397    }
398
399    #[test]
400    fn update_refresh_never_adds_newly_detected_tools() {
401        let scope = resolve_scope(None, None, true, || keys(&["claude"]));
402        assert!(scope.allows("claude"));
403        assert!(
404            !scope.allows("cursor"),
405            "a tool installed later stays untouched"
406        );
407
408        let nothing_connected = resolve_scope(None, None, true, BTreeSet::new);
409        assert!(!nothing_connected.allows("claude"));
410    }
411
412    #[test]
413    fn fresh_setup_without_choice_keeps_all_detected() {
414        assert_eq!(
415            resolve_scope(None, None, false, BTreeSet::new),
416            AgentScope::All
417        );
418        assert!(AgentScope::All.allows("anything"));
419    }
420
421    #[test]
422    fn selection_answer_forms() {
423        let agents = agents();
424        let default = keys(&["claude"]);
425        assert_eq!(
426            parse_selection_answer("\n", &agents, &default).unwrap(),
427            default
428        );
429        assert_eq!(
430            parse_selection_answer("all", &agents, &default).unwrap(),
431            keys(&["claude", "cursor", "codex"])
432        );
433        assert_eq!(
434            parse_selection_answer("none", &agents, &default).unwrap(),
435            keys(&[])
436        );
437        assert_eq!(
438            parse_selection_answer("2 3", &agents, &default).unwrap(),
439            keys(&["cursor", "codex"])
440        );
441        assert_eq!(
442            parse_selection_answer("codex,1", &agents, &default).unwrap(),
443            keys(&["claude", "codex"])
444        );
445        assert!(parse_selection_answer("4", &agents, &default).is_err());
446        assert!(parse_selection_answer("0", &agents, &default).is_err());
447        assert!(parse_selection_answer("vim", &agents, &default).is_err());
448    }
449
450    #[test]
451    fn prompt_default_prefers_saved_then_connected_then_all() {
452        let agents = agents();
453        let saved = vec!["codex".to_string(), "gone".to_string()];
454        assert_eq!(prompt_default(&agents, Some(&saved)), keys(&["codex"]));
455        assert_eq!(prompt_default(&agents, None), keys(&["claude"]));
456
457        let fresh: Vec<DetectedAgent> = agents
458            .into_iter()
459            .map(|a| DetectedAgent {
460                connected: false,
461                ..a
462            })
463            .collect();
464        assert_eq!(
465            prompt_default(&fresh, None),
466            keys(&["claude", "cursor", "codex"])
467        );
468    }
469
470    #[test]
471    fn detection_groups_targets_by_key_and_reads_connection_state() {
472        let tmp = tempfile::tempdir().unwrap();
473        let home = tmp.path();
474        let mk = |name: &'static str, key: &str, dir: &str, content: Option<&str>| {
475            let detect = home.join(dir);
476            std::fs::create_dir_all(&detect).unwrap();
477            let config = detect.join("mcp.json");
478            if let Some(content) = content {
479                std::fs::write(&config, content).unwrap();
480            }
481            EditorTarget {
482                name,
483                agent_key: key.to_string(),
484                config_path: config,
485                detect_path: detect,
486                config_type: crate::core::editor_registry::ConfigType::McpJson,
487            }
488        };
489        let targets = vec![
490            mk("Cline", "cline", "cline-ext", None),
491            mk(
492                "Cline CLI",
493                "cline",
494                "cline-cli",
495                Some(r#"{"mcpServers":{"lean-ctx":{}}}"#),
496            ),
497            mk("Cursor", "cursor", "cursor", Some("{}")),
498            EditorTarget {
499                name: "Zed",
500                agent_key: "zed".to_string(),
501                config_path: home.join("missing/settings.json"),
502                detect_path: home.join("missing"),
503                config_type: crate::core::editor_registry::ConfigType::Zed,
504            },
505        ];
506
507        let detected = detected_agents(home, &targets);
508        assert_eq!(
509            detected,
510            vec![
511                DetectedAgent {
512                    key: "cline".to_string(),
513                    label: "Cline / Cline CLI".to_string(),
514                    connected: true,
515                },
516                DetectedAgent {
517                    key: "cursor".to_string(),
518                    label: "Cursor".to_string(),
519                    connected: false,
520                },
521            ]
522        );
523        assert_eq!(connected_agent_keys(home, &targets), keys(&["cline"]));
524    }
525}