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_agent_dir = lean_ctx::core::editor_registry::pi_agent_dir(home);
144    if pi_agent_dir.exists() || home.join(".pi").exists() {
145        agents.push(DetectedAgent {
146            key: PI_KEY.to_string(),
147            label: "Pi Coding Agent".to_string(),
148            connected: pi_rules_connected(home),
149        });
150    }
151    agents
152}
153
154/// Pi loads its rules from `<agent dir>/AGENTS.md` (`~/.pi/agent`, or
155/// `PI_CODING_AGENT_DIR`); a lean-ctx block there marks Pi as connected.
156/// `~/.pi/rules/lean-ctx.md` is what releases before that wrote: it still
157/// counts until setup has rewritten it (fallback for one release).
158fn pi_rules_connected(home: &std::path::Path) -> bool {
159    let agents_md = lean_ctx::core::editor_registry::pi_agents_path(home);
160    std::fs::read_to_string(agents_md).is_ok_and(|content| {
161        lean_ctx::marked_block::contains_marker_line(
162            &content,
163            lean_ctx::core::rules_canonical::START_MARK,
164        )
165    }) || has_lean_ctx_entry(&home.join(".pi/rules/lean-ctx.md"))
166}
167
168/// Agent keys an earlier setup connected (a lean-ctx entry is present).
169#[must_use]
170pub fn connected_agent_keys(home: &std::path::Path, targets: &[EditorTarget]) -> BTreeSet<String> {
171    detected_agents(home, targets)
172        .into_iter()
173        .filter(|a| a.connected)
174        .map(|a| a.key)
175        .collect()
176}
177
178/// Scope for a setup run: `--agents`, then `setup.agents`, then (refresh only)
179/// the already-connected tools, else every detected tool.
180#[must_use]
181pub fn scope_for_run(
182    home: &std::path::Path,
183    targets: &[EditorTarget],
184    explicit: Option<&BTreeSet<String>>,
185    refresh_only: bool,
186) -> AgentScope {
187    let saved = lean_ctx::core::config::Config::load_global().setup.agents;
188    resolve_scope(explicit, saved.as_deref(), refresh_only, || {
189        connected_agent_keys(home, targets)
190    })
191}
192
193/// Record the choice so later updates refresh exactly these tools.
194pub fn save_selection(keys: &BTreeSet<String>) -> Result<(), String> {
195    lean_ctx::core::config::Config::update_global(|cfg| {
196        cfg.setup.agents = Some(keys.iter().cloned().collect());
197    })
198    .map(|_| ())
199    .map_err(|e| format!("could not save the agent selection: {e}"))
200}
201
202/// `init --agent <key>` connects a tool on purpose: add it to a recorded
203/// selection so later updates keep it current. Without a recorded selection
204/// nothing is written — updates already follow the connected tools.
205pub fn remember_connected_agent(agent_key: &str) -> Result<(), String> {
206    let key = agent_key.trim().to_ascii_lowercase();
207    let Some(mut saved) = lean_ctx::core::config::Config::load_global().setup.agents else {
208        return Ok(());
209    };
210    if saved.iter().any(|k| k.eq_ignore_ascii_case(&key)) {
211        return Ok(());
212    }
213    let Some(home) = lean_ctx::core::home::resolve_home_dir() else {
214        return Ok(());
215    };
216    if !known_agent_keys(&lean_ctx::core::editor_registry::build_targets(&home)).contains(&key) {
217        return Ok(());
218    }
219    saved.push(key);
220    save_selection(&saved.into_iter().collect())
221}
222
223/// Interpret the answer to the selection prompt. Empty keeps `default`;
224/// otherwise `all`, `none`, or numbers / agent keys separated by commas or
225/// spaces select exactly those tools.
226pub fn parse_selection_answer(
227    answer: &str,
228    agents: &[DetectedAgent],
229    default: &BTreeSet<String>,
230) -> Result<BTreeSet<String>, String> {
231    let answer = answer.trim().to_ascii_lowercase();
232    match answer.as_str() {
233        "" => return Ok(default.clone()),
234        "all" | "a" => return Ok(agents.iter().map(|a| a.key.clone()).collect()),
235        "none" | "n" => return Ok(BTreeSet::new()),
236        _ => {}
237    }
238    let mut selected = BTreeSet::new();
239    for token in answer
240        .split(|c: char| c == ',' || c.is_whitespace())
241        .filter(|t| !t.is_empty())
242    {
243        let agent = match token.parse::<usize>() {
244            Ok(n) => n.checked_sub(1).and_then(|i| agents.get(i)),
245            Err(_) => agents.iter().find(|a| a.key == token),
246        };
247        match agent {
248            Some(agent) => {
249                selected.insert(agent.key.clone());
250            }
251            None => return Err(format!("'{token}' is not in the list")),
252        }
253    }
254    Ok(selected)
255}
256
257/// Default for the prompt: the recorded choice, else the connected tools,
258/// else (first setup) every detected tool.
259#[must_use]
260pub fn prompt_default(agents: &[DetectedAgent], saved: Option<&[String]>) -> BTreeSet<String> {
261    let detected: BTreeSet<String> = agents.iter().map(|a| a.key.clone()).collect();
262    if let Some(saved) = saved {
263        return saved
264            .iter()
265            .map(|k| k.trim().to_ascii_lowercase())
266            .filter(|k| detected.contains(k))
267            .collect();
268    }
269    let connected: BTreeSet<String> = agents
270        .iter()
271        .filter(|a| a.connected)
272        .map(|a| a.key.clone())
273        .collect();
274    if connected.is_empty() {
275        detected
276    } else {
277        connected
278    }
279}
280
281/// Ask which detected tools lean-ctx should connect. Reads stdin; callers
282/// must only use it on an interactive terminal.
283#[must_use]
284pub fn prompt_agent_selection(
285    agents: &[DetectedAgent],
286    default: &BTreeSet<String>,
287) -> BTreeSet<String> {
288    use std::io::Write;
289
290    let dim = "\x1b[2m";
291    let bold = "\x1b[1m";
292    let rst = "\x1b[0m";
293    println!("  Which AI tools should lean-ctx connect to?");
294    for (i, agent) in agents.iter().enumerate() {
295        let mark = if default.contains(&agent.key) {
296            "x"
297        } else {
298            " "
299        };
300        let state = if agent.connected { " (connected)" } else { "" };
301        println!(
302            "    [{mark}] {:>2}. {:<28} {dim}{}{state}{rst}",
303            i + 1,
304            agent.label,
305            agent.key
306        );
307    }
308    println!(
309        "  {dim}Enter = keep [x] · numbers or names (e.g. 1,3 or claude cursor) · all · none{rst}"
310    );
311    for _ in 0..3 {
312        print!("  {bold}>{rst} ");
313        std::io::stdout().flush().ok();
314        let mut input = String::new();
315        if std::io::stdin().read_line(&mut input).unwrap_or(0) == 0 {
316            return default.clone();
317        }
318        match parse_selection_answer(&input, agents, default) {
319            Ok(selected) => return selected,
320            Err(e) => println!("  \x1b[33m{e}{rst} — try again"),
321        }
322    }
323    println!("  {dim}Keeping the marked selection.{rst}");
324    default.clone()
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    fn keys(items: &[&str]) -> BTreeSet<String> {
332        items.iter().map(ToString::to_string).collect()
333    }
334
335    fn agents() -> Vec<DetectedAgent> {
336        ["claude", "cursor", "codex"]
337            .iter()
338            .enumerate()
339            .map(|(i, key)| DetectedAgent {
340                key: (*key).to_string(),
341                label: key.to_uppercase(),
342                connected: i == 0,
343            })
344            .collect()
345    }
346
347    #[test]
348    fn agents_flag_validates_names() {
349        let known = keys(&["claude", "cursor", "codex", "pi"]);
350        assert_eq!(
351            parse_agent_list("Claude, cursor", &known).unwrap(),
352            keys(&["claude", "cursor"])
353        );
354        assert_eq!(parse_agent_list("none", &known).unwrap(), keys(&[]));
355        let err = parse_agent_list("claude,vscodee", &known).unwrap_err();
356        assert!(err.contains("unknown agent(s): vscodee"), "{err}");
357        assert!(
358            err.contains("Known agents: claude, codex, cursor, pi"),
359            "{err}"
360        );
361        assert!(parse_agent_list(" , ", &known).is_err());
362    }
363
364    #[test]
365    fn agents_flag_is_extracted_in_both_spellings() {
366        let args: Vec<String> = ["--yes", "--agents", "claude,cursor", "--json"]
367            .iter()
368            .map(ToString::to_string)
369            .collect();
370        let (rest, raw) = take_agents_flag(&args).unwrap();
371        assert_eq!(rest, ["--yes", "--json"]);
372        assert_eq!(raw.as_deref(), Some("claude,cursor"));
373
374        let (rest, raw) = take_agents_flag(&["--agents=codex".to_string()]).unwrap();
375        assert!(rest.is_empty());
376        assert_eq!(raw.as_deref(), Some("codex"));
377
378        assert!(take_agents_flag(&["--agents".to_string()]).is_err());
379        assert!(take_agents_flag(&["--agents".to_string(), "--yes".to_string()]).is_err());
380    }
381
382    #[test]
383    fn explicit_beats_saved_beats_connected() {
384        let explicit = keys(&["codex"]);
385        let saved = vec!["Cursor".to_string()];
386        let never = || -> BTreeSet<String> { panic!("connected must not be evaluated") };
387
388        assert_eq!(
389            resolve_scope(Some(&explicit), Some(&saved), true, never),
390            AgentScope::Only(explicit.clone())
391        );
392        assert_eq!(
393            resolve_scope(None, Some(&saved), true, never),
394            AgentScope::Only(keys(&["cursor"]))
395        );
396    }
397
398    #[test]
399    fn update_refresh_never_adds_newly_detected_tools() {
400        let scope = resolve_scope(None, None, true, || keys(&["claude"]));
401        assert!(scope.allows("claude"));
402        assert!(
403            !scope.allows("cursor"),
404            "a tool installed later stays untouched"
405        );
406
407        let nothing_connected = resolve_scope(None, None, true, BTreeSet::new);
408        assert!(!nothing_connected.allows("claude"));
409    }
410
411    #[test]
412    fn fresh_setup_without_choice_keeps_all_detected() {
413        assert_eq!(
414            resolve_scope(None, None, false, BTreeSet::new),
415            AgentScope::All
416        );
417        assert!(AgentScope::All.allows("anything"));
418    }
419
420    #[test]
421    fn selection_answer_forms() {
422        let agents = agents();
423        let default = keys(&["claude"]);
424        assert_eq!(
425            parse_selection_answer("\n", &agents, &default).unwrap(),
426            default
427        );
428        assert_eq!(
429            parse_selection_answer("all", &agents, &default).unwrap(),
430            keys(&["claude", "cursor", "codex"])
431        );
432        assert_eq!(
433            parse_selection_answer("none", &agents, &default).unwrap(),
434            keys(&[])
435        );
436        assert_eq!(
437            parse_selection_answer("2 3", &agents, &default).unwrap(),
438            keys(&["cursor", "codex"])
439        );
440        assert_eq!(
441            parse_selection_answer("codex,1", &agents, &default).unwrap(),
442            keys(&["claude", "codex"])
443        );
444        assert!(parse_selection_answer("4", &agents, &default).is_err());
445        assert!(parse_selection_answer("0", &agents, &default).is_err());
446        assert!(parse_selection_answer("vim", &agents, &default).is_err());
447    }
448
449    #[test]
450    fn prompt_default_prefers_saved_then_connected_then_all() {
451        let agents = agents();
452        let saved = vec!["codex".to_string(), "gone".to_string()];
453        assert_eq!(prompt_default(&agents, Some(&saved)), keys(&["codex"]));
454        assert_eq!(prompt_default(&agents, None), keys(&["claude"]));
455
456        let fresh: Vec<DetectedAgent> = agents
457            .into_iter()
458            .map(|a| DetectedAgent {
459                connected: false,
460                ..a
461            })
462            .collect();
463        assert_eq!(
464            prompt_default(&fresh, None),
465            keys(&["claude", "cursor", "codex"])
466        );
467    }
468
469    #[test]
470    fn detection_groups_targets_by_key_and_reads_connection_state() {
471        // Pi detection reads `PI_CODING_AGENT_DIR`, which other tests set.
472        let _env = lean_ctx::core::data_dir::test_env_lock();
473        let tmp = tempfile::tempdir().unwrap();
474        let home = tmp.path();
475        let mk = |name: &'static str, key: &str, dir: &str, content: Option<&str>| {
476            let detect = home.join(dir);
477            std::fs::create_dir_all(&detect).unwrap();
478            let config = detect.join("mcp.json");
479            if let Some(content) = content {
480                std::fs::write(&config, content).unwrap();
481            }
482            EditorTarget {
483                name,
484                agent_key: key.to_string(),
485                config_path: config,
486                detect_path: detect,
487                config_type: lean_ctx::core::editor_registry::ConfigType::McpJson,
488            }
489        };
490        let targets = vec![
491            mk("Cline", "cline", "cline-ext", None),
492            mk(
493                "Cline CLI",
494                "cline",
495                "cline-cli",
496                Some(r#"{"mcpServers":{"lean-ctx":{}}}"#),
497            ),
498            mk("Cursor", "cursor", "cursor", Some("{}")),
499            EditorTarget {
500                name: "Zed",
501                agent_key: "zed".to_string(),
502                config_path: home.join("missing/settings.json"),
503                detect_path: home.join("missing"),
504                config_type: lean_ctx::core::editor_registry::ConfigType::Zed,
505            },
506        ];
507
508        let detected = detected_agents(home, &targets);
509        assert_eq!(
510            detected,
511            vec![
512                DetectedAgent {
513                    key: "cline".to_string(),
514                    label: "Cline / Cline CLI".to_string(),
515                    connected: true,
516                },
517                DetectedAgent {
518                    key: "cursor".to_string(),
519                    label: "Cursor".to_string(),
520                    connected: false,
521                },
522            ]
523        );
524        assert_eq!(connected_agent_keys(home, &targets), keys(&["cline"]));
525    }
526
527    /// Setup moved Pi's rules into `<agent dir>/AGENTS.md` and deletes
528    /// `~/.pi/rules/lean-ctx.md`; the post-update refresh must still see Pi as
529    /// connected, also under `PI_CODING_AGENT_DIR`.
530    #[test]
531    fn pi_counts_as_connected_through_its_agents_md() {
532        let _lock = lean_ctx::core::data_dir::test_env_lock();
533        let tmp = tempfile::tempdir().unwrap();
534        let home = tmp.path();
535        let pi_dir = home.join("custom-pi");
536        let _pi = lean_ctx::test_env::EnvVarGuard::set(
537            "PI_CODING_AGENT_DIR",
538            pi_dir.to_string_lossy().as_ref(),
539        );
540        std::fs::create_dir_all(&pi_dir).unwrap();
541        std::fs::write(pi_dir.join("AGENTS.md"), "# Mine\n").unwrap();
542        assert!(connected_agent_keys(home, &[]).is_empty());
543
544        std::fs::write(
545            pi_dir.join("AGENTS.md"),
546            format!(
547                "# Mine\n\n{}\nrules\n{}\n",
548                lean_ctx::core::rules_canonical::START_MARK,
549                lean_ctx::core::rules_canonical::END_MARK
550            ),
551        )
552        .unwrap();
553        assert_eq!(connected_agent_keys(home, &[]), keys(&["pi"]));
554    }
555}