Skip to main content

lean_ctx_cli/setup/
onboard.rs

1// SPDX-License-Identifier: Apache-2.0
2use super::options::SetupOptions;
3use super::with_options::run_setup_with_options;
4
5/// Friendly, non-interactive "golden path" onboarding.
6///
7/// Unlike `run_setup` (the full 12-step interactive wizard), `onboard` makes
8/// every decision for the user with sensible defaults — connect detected AI
9/// tools, install the shell hook, set the `standard` tool profile — then prints
10/// one clear "you're all set" message with a single obvious next step. This is
11/// the recommended first-run path: time-to-value in seconds. Its one question,
12/// on a terminal and only until a choice is recorded, is which of the detected
13/// tools to connect.
14pub fn run_onboard() {
15    run_onboard_with(&OnboardAgents::Unspecified, false, false);
16}
17
18/// Which tools the caller asked `onboard` to connect.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum OnboardAgents {
21    /// No `--agents`, no `--yes`, no `LEAN_CTX_AGENTS`.
22    Unspecified,
23    /// `--agents all` / `LEAN_CTX_AGENTS=all`: every detected tool.
24    AllDetected,
25    /// `--yes`: the recorded choice, else every detected tool (pre-3.12).
26    Yes,
27    /// `--agents a,b` / `LEAN_CTX_AGENTS=a,b` (validated, may be empty).
28    Only(std::collections::BTreeSet<String>),
29}
30
31/// What one onboard run connects.
32#[derive(Debug, Clone, PartialEq, Eq)]
33enum Decision {
34    Explicit(std::collections::BTreeSet<String>),
35    AllDetected,
36    /// The recorded `setup.agents`.
37    Saved,
38    /// Ask on the terminal.
39    Ask,
40    /// No terminal, no choice: never connect a tool nobody picked (npm
41    /// postinstall, CI). Tools that already carry a lean-ctx entry are
42    /// refreshed; everything else waits for `lean-ctx setup`.
43    ConnectedOnly,
44}
45
46fn decide(request: &OnboardAgents, has_saved: bool, interactive: bool) -> Decision {
47    match request {
48        OnboardAgents::Only(keys) => Decision::Explicit(keys.clone()),
49        OnboardAgents::Yes | OnboardAgents::Unspecified if has_saved => Decision::Saved,
50        OnboardAgents::AllDetected | OnboardAgents::Yes => Decision::AllDetected,
51        OnboardAgents::Unspecified if interactive => Decision::Ask,
52        OnboardAgents::Unspecified => Decision::ConnectedOnly,
53    }
54}
55
56/// `dry_run` prints the plan and writes nothing. `no_prompt`
57/// (`--non-interactive`) behaves like a run without a terminal.
58pub fn run_onboard_with(request: &OnboardAgents, dry_run: bool, no_prompt: bool) {
59    use lean_ctx::terminal_ui;
60
61    let dim = "\x1b[2m";
62    let bold = "\x1b[1m";
63    let cyan = "\x1b[36m";
64    let green = "\x1b[1;32m";
65    let yellow = "\x1b[33m";
66    let rst = "\x1b[0m";
67
68    let has_saved = lean_ctx::core::config::Config::load_global()
69        .setup
70        .agents
71        .is_some();
72    let interactive = !no_prompt && !lean_ctx::shell::is_non_interactive();
73    let decision = decide(request, has_saved, interactive);
74    let (agents, refresh_only) = match decision {
75        Decision::Explicit(keys) => (Some(keys), false),
76        // Saved: the setup scope reads setup.agents itself.
77        Decision::Saved => (None, false),
78        // AllDetected must not fall back to a recorded choice.
79        Decision::AllDetected => (Some(all_detected_keys()), false),
80        // A plan does not ask: it shows what the offered default would touch.
81        Decision::Ask if dry_run => (None, false),
82        Decision::Ask => (ask_selection(), false),
83        Decision::ConnectedOnly => (None, true),
84    };
85
86    if !dry_run {
87        println!();
88        println!("  {bold}Connecting lean-ctx to your AI tools…{rst}");
89        println!("  {dim}Recommended defaults. Run `lean-ctx setup` for full control.{rst}");
90        println!();
91    }
92
93    let opts = SetupOptions {
94        non_interactive: true,
95        yes: true,
96        fix: true,
97        agents,
98        refresh_only,
99        dry_run,
100        ..Default::default()
101    };
102
103    let report = match run_setup_with_options(&opts) {
104        Ok(r) if dry_run => {
105            super::print_plan(&r);
106            if refresh_only {
107                print_choose_hint();
108            }
109            return;
110        }
111        Ok(r) => r,
112        Err(e) => {
113            eprintln!("  {yellow}Onboarding could not complete: {e}{rst}");
114            eprintln!("  {dim}Try the guided setup instead: lean-ctx setup{rst}");
115            std::process::exit(1);
116        }
117    };
118
119    let connected: Vec<String> = report
120        .steps
121        .iter()
122        .find(|s| s.name == "editors")
123        .map(|s| {
124            s.items
125                .iter()
126                .filter(|i| matches!(i.status.as_str(), "created" | "updated" | "already"))
127                .map(|i| i.name.clone())
128                .collect()
129        })
130        .unwrap_or_default();
131
132    let data_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()
133        .map_or_else(|_| "~/.lean-ctx".to_string(), |p| p.display().to_string());
134
135    println!();
136    if refresh_only {
137        print_choose_hint();
138    }
139    if connected.is_empty() && refresh_only {
140        println!("  {yellow}No AI tool connected yet.{rst}");
141    } else if connected.is_empty() {
142        println!("  {yellow}No AI tools detected yet.{rst}");
143        println!(
144            "  {dim}Install Cursor, Claude Code, VS Code, etc., then re-run: lean-ctx onboard{rst}"
145        );
146    } else {
147        println!("  {green}✓ lean-ctx is connected.{rst}");
148        println!();
149        println!("  {bold}Connected:{rst} {}", connected.join(", "));
150    }
151    println!("  {dim}Data dir:{rst}  {data_dir}");
152
153    let source_cmd = lean_ctx::shell_hook::shell_source_command().unwrap_or("Restart your shell");
154    println!();
155    println!("  {bold}One last step:{rst}");
156    println!("  {cyan}1.{rst} Reload your shell:  {bold}{source_cmd}{rst}");
157    if !connected.is_empty() {
158        println!(
159            "  {cyan}2.{rst} {yellow}Fully restart your AI tool{rst} {dim}(so it reconnects to lean-ctx){rst}"
160        );
161        println!(
162            "  {cyan}3.{rst} Ask your AI to read a file — lean-ctx optimizes it automatically."
163        );
164    }
165    println!();
166    println!(
167        "  {dim}Check anytime:{rst}  {bold}lean-ctx doctor{rst}  {dim}·{rst}  {bold}lean-ctx cockpit{rst}"
168    );
169    println!();
170    terminal_ui::print_command_box();
171
172    crate::cli::show_first_run_wow();
173}
174
175/// Every installed tool, recorded as the choice so a later update refreshes
176/// exactly these and never one installed afterwards.
177fn all_detected_keys() -> std::collections::BTreeSet<String> {
178    let Some(home) = lean_ctx::core::home::resolve_home_dir() else {
179        return std::collections::BTreeSet::new();
180    };
181    let targets = lean_ctx::core::editor_registry::build_targets(&home);
182    super::agent_selection::detected_agents(&home, &targets)
183        .into_iter()
184        .map(|a| a.key)
185        .collect()
186}
187
188/// Shown when onboard ran without a terminal and without a choice.
189fn print_choose_hint() {
190    let dim = "\x1b[2m";
191    let bold = "\x1b[1m";
192    let rst = "\x1b[0m";
193    eprintln!("  No agent choice recorded and no terminal: only AI tools that already use");
194    eprintln!("  lean-ctx were refreshed; no other tool was configured.");
195    eprintln!("  Choose tools: {bold}lean-ctx setup{rst}");
196    eprintln!(
197        "  {dim}or: lean-ctx onboard --agents claude,cursor  ·  LEAN_CTX_AGENTS=all for every detected tool{rst}"
198    );
199}
200
201/// First onboarding on a terminal: ask which detected tools to connect.
202fn ask_selection() -> Option<std::collections::BTreeSet<String>> {
203    use super::agent_selection as sel;
204
205    let home = lean_ctx::core::home::resolve_home_dir()?;
206    let targets = lean_ctx::core::editor_registry::build_targets(&home);
207    let detected = sel::detected_agents(&home, &targets);
208    if detected.is_empty() {
209        return None;
210    }
211    println!();
212    let default = sel::prompt_default(&detected, None);
213    Some(sel::prompt_agent_selection(&detected, &default))
214}
215
216#[cfg(test)]
217mod tests {
218    use super::{Decision, OnboardAgents, decide};
219
220    #[test]
221    fn without_terminal_or_choice_onboard_connects_no_new_tool() {
222        // npm postinstall / CI: nobody picked anything.
223        assert_eq!(
224            decide(&OnboardAgents::Unspecified, false, false),
225            Decision::ConnectedOnly
226        );
227    }
228
229    #[test]
230    fn explicit_requests_and_records_win() {
231        let keys: std::collections::BTreeSet<String> = ["cursor".to_string()].into();
232        assert_eq!(
233            decide(&OnboardAgents::Only(keys.clone()), true, false),
234            Decision::Explicit(keys)
235        );
236        assert_eq!(
237            decide(&OnboardAgents::AllDetected, false, false),
238            Decision::AllDetected
239        );
240        assert_eq!(
241            decide(&OnboardAgents::Unspecified, true, true),
242            Decision::Saved
243        );
244        assert_eq!(decide(&OnboardAgents::Yes, true, false), Decision::Saved);
245        assert_eq!(
246            decide(&OnboardAgents::Yes, false, false),
247            Decision::AllDetected
248        );
249        assert_eq!(
250            decide(&OnboardAgents::AllDetected, true, false),
251            Decision::AllDetected
252        );
253        assert_eq!(
254            decide(&OnboardAgents::Unspecified, false, true),
255            Decision::Ask
256        );
257    }
258}