Skip to main content

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