Skip to main content

lean_ctx/wrap/
mod.rs

1//! `lean-ctx wrap <agent>` — one-command setup for any supported agent.
2//!
3//! Orchestrates shell hooks, MCP registration, agent hooks, daemon, and
4//! optional IDE launch into a single idempotent operation.  Every file
5//! mutation is recorded in a snapshot so `lean-ctx unwrap <agent>` can
6//! restore the pre-wrap state byte-for-byte.
7
8mod launch;
9mod snapshot;
10mod unwrap;
11mod verify;
12
13use crate::core::editor_registry::{self, EditorTarget, WriteOptions};
14use crate::core::portable_binary::resolve_portable_binary;
15use crate::hooks::{self, HookMode};
16
17use snapshot::WrapSnapshot;
18
19pub use unwrap::run_unwrap;
20
21/// Entry point for `lean-ctx wrap <agent>`.
22pub fn run_wrap(args: &[String]) {
23    if args.iter().any(|a| a == "--help" || a == "-h") {
24        print_help();
25        return;
26    }
27
28    let agent_key = match args.first() {
29        Some(a) if !a.starts_with('-') => a.as_str(),
30        _ => {
31            let detected = detect_single_agent();
32            if let Some(agent) = detected {
33                eprintln!("Detected: {agent}");
34                run_wrap_for_agent(&agent);
35                return;
36            }
37            eprintln!("Usage: lean-ctx wrap <agent>");
38            eprintln!();
39            eprintln!("Supported agents:");
40            for name in available_agent_keys() {
41                eprintln!("  {name}");
42            }
43            eprintln!();
44            eprintln!("Example: lean-ctx wrap cursor");
45            std::process::exit(1);
46        }
47    };
48
49    run_wrap_for_agent(agent_key);
50}
51
52fn run_wrap_for_agent(agent_key: &str) {
53    let Some(home) = dirs::home_dir() else {
54        eprintln!("Cannot determine home directory");
55        std::process::exit(1);
56    };
57
58    let targets = editor_registry::build_targets(&home);
59    let matching: Vec<&EditorTarget> = targets
60        .iter()
61        .filter(|t| t.agent_key == agent_key)
62        .collect();
63
64    if matching.is_empty() {
65        eprintln!("Unknown agent: '{agent_key}'");
66        eprintln!();
67        eprintln!("Supported agents:");
68        for name in available_agent_keys() {
69            eprintln!("  {name}");
70        }
71        std::process::exit(1);
72    }
73
74    let binary = resolve_portable_binary();
75    let mut snap = WrapSnapshot::new(agent_key);
76
77    // --- Step 1: Snapshot existing configs ---
78    for target in &matching {
79        snap.record_file(&target.config_path);
80    }
81
82    // --- Step 2: Shell hooks ---
83    eprintln!("  Installing shell hooks...");
84    crate::shell_hook::install_all(true);
85
86    // --- Step 3: MCP config ---
87    eprintln!("  Registering MCP server...");
88    let mut mcp_ok = false;
89    for target in &matching {
90        if !target.detect_path.exists() {
91            eprintln!(
92                "    {}: not installed ({})",
93                target.name,
94                target.detect_path.display()
95            );
96            continue;
97        }
98        match editor_registry::write_config_with_options(
99            target,
100            &binary,
101            WriteOptions {
102                overwrite_invalid: true,
103            },
104        ) {
105            Ok(result) => {
106                let action = match result.action {
107                    editor_registry::WriteAction::Created => "created",
108                    editor_registry::WriteAction::Updated => "updated",
109                    editor_registry::WriteAction::Already => "already configured",
110                };
111                eprintln!("    {}: {action}", target.name);
112                mcp_ok = true;
113            }
114            Err(e) => eprintln!("    {}: error: {e}", target.name),
115        }
116    }
117
118    if !mcp_ok {
119        eprintln!();
120        eprintln!(
121            "No installed instance of '{agent_key}' found. \
122             Install {agent_key}, then re-run: lean-ctx wrap {agent_key}"
123        );
124        std::process::exit(1);
125    }
126
127    // --- Step 4: Agent hooks ---
128    let mode = hooks::recommend_hook_mode(agent_key);
129    eprintln!(
130        "  Installing agent hooks ({})...",
131        match mode {
132            HookMode::Mcp => "MCP",
133            HookMode::Hybrid => "Hybrid",
134            HookMode::Replace => "Replace",
135        }
136    );
137    hooks::install_agent_hook_respecting_rules_off(agent_key, true, mode);
138
139    // Re-render managed rule files on every wrap so [solution] changes add or
140    // remove the canonical solution block instead of leaving stale guidance.
141    for status in crate::rules_inject::collect_rules_status(&home) {
142        snap.record_file(std::path::Path::new(&status.path));
143    }
144    let rules = crate::rules_inject::inject_rules_for_agent(&home, agent_key);
145    for error in rules.errors {
146        eprintln!("  Rules: {error}");
147    }
148
149    // --- Step 4b: Consolidate split data dirs ---
150    if let Some(report) = crate::core::data_consolidate::consolidate() {
151        if report.files_moved > 0 {
152            eprintln!(
153                "  Consolidated {} files from {} split data dir(s)",
154                report.files_moved,
155                report.merged_from.len()
156            );
157        }
158    }
159
160    // --- Step 5: Daemon ---
161    eprintln!("  Starting daemon...");
162    if !crate::daemon::is_daemon_running() {
163        let _ = crate::daemon::start_daemon(&[]);
164    }
165
166    // --- Step 6: Save snapshot for unwrap ---
167    if let Err(e) = snap.save() {
168        eprintln!("  Warning: could not save wrap snapshot: {e}");
169    }
170
171    // --- Step 7: Verify MCP ---
172    let mcp_verified = verify::probe_mcp_server(&binary);
173
174    // --- Step 8: Launch / restart hint ---
175    let launch_result = launch::handle_agent_launch(agent_key);
176
177    // --- Step 9: Self-test ---
178    run_self_test(agent_key, &home);
179
180    // --- Step 10: Summary ---
181    print_summary(agent_key, mcp_verified, &launch_result);
182}
183
184fn run_self_test(agent_key: &str, home: &std::path::Path) {
185    let mut issues: Vec<String> = Vec::new();
186
187    // 1. Hook coverage
188    if !crate::core::rules_channel::client_hook_covered(agent_key, home) {
189        issues.push(format!(
190            "Hook coverage not detected for {agent_key}.              Native tool calls may be visible in chat.              Re-run: lean-ctx wrap {agent_key}"
191        ));
192    }
193
194    // 2. Stats split
195    let dirs = crate::core::data_dir::all_data_dirs_with_stats();
196    if dirs.len() > 1 {
197        issues.push(format!(
198            "Stats data found in {} locations (should be 1).              Run: lean-ctx doctor --fix",
199            dirs.len()
200        ));
201    }
202
203    // 3. Daemon running
204    if !crate::daemon::is_daemon_running() {
205        issues.push(
206            "Daemon is not running. Context caching and live stats              will be unavailable until it starts."
207                .to_string(),
208        );
209    }
210
211    if issues.is_empty() {
212        eprintln!("  Self-test: all checks passed");
213    } else {
214        eprintln!();
215        eprintln!("  Self-test: {} issue(s) detected:", issues.len());
216        for issue in &issues {
217            eprintln!("    - {issue}");
218        }
219    }
220}
221
222fn print_summary(agent_key: &str, mcp_ok: bool, launch_hint: &str) {
223    let tool_count = crate::server::registry::tool_count();
224
225    eprintln!();
226    eprintln!("\x1b[1;32mlean-ctx wrapped {agent_key} successfully.\x1b[0m");
227    eprintln!();
228
229    let mcp_status = if mcp_ok {
230        format!(
231            "\x1b[32m{tool_count} tools verified\x1b[0m (ctx_read, ctx_search, ctx_shell + more)"
232        )
233    } else {
234        format!("{tool_count} tools \x1b[33m(pending IDE restart)\x1b[0m")
235    };
236    eprintln!("  MCP server:  {mcp_status}");
237    eprintln!("  Shell hooks: \x1b[32minstalled\x1b[0m (git, cargo, npm, docker + 90 patterns)");
238    eprintln!("  Agent hooks: \x1b[32minstalled\x1b[0m");
239    eprintln!();
240
241    if !launch_hint.is_empty() {
242        eprintln!("  \x1b[33m{launch_hint}\x1b[0m");
243        eprintln!();
244    }
245
246    eprintln!("  Undo:   \x1b[2mlean-ctx unwrap {agent_key}\x1b[0m");
247    eprintln!("  Verify: \x1b[2mlean-ctx doctor\x1b[0m");
248    eprintln!("  Stats:  \x1b[2mlean-ctx gain\x1b[0m (after first use)");
249}
250
251fn print_help() {
252    println!("Usage: lean-ctx wrap <agent>");
253    println!();
254    println!("One-command setup: installs shell hooks, MCP server registration,");
255    println!("agent hooks, and starts the daemon. Everything needed to use lean-ctx");
256    println!("with the specified agent.");
257    println!();
258    println!("Supported agents:");
259    for name in available_agent_keys() {
260        println!("  {name}");
261    }
262    println!();
263    println!("Examples:");
264    println!("  lean-ctx wrap cursor     # Set up lean-ctx for Cursor");
265    println!("  lean-ctx wrap claude     # Set up lean-ctx for Claude Code");
266    println!("  lean-ctx wrap codex      # Set up lean-ctx for Codex CLI");
267    println!();
268    println!("Undo:  lean-ctx unwrap <agent>");
269    println!("Full:  lean-ctx setup  (interactive wizard with all options)");
270}
271
272fn available_agent_keys() -> Vec<String> {
273    let home = dirs::home_dir().unwrap_or_default();
274    let targets = editor_registry::build_targets(&home);
275    let mut keys: Vec<String> = targets.into_iter().map(|t| t.agent_key).collect();
276    keys.sort_unstable();
277    keys.dedup();
278    keys
279}
280
281fn detect_single_agent() -> Option<String> {
282    let home = dirs::home_dir()?;
283    let targets = editor_registry::build_targets(&home);
284    let installed: Vec<String> = targets
285        .iter()
286        .filter(|t| t.detect_path.exists())
287        .map(|t| t.agent_key.clone())
288        .collect::<std::collections::BTreeSet<_>>()
289        .into_iter()
290        .collect();
291
292    if installed.len() == 1 {
293        installed.into_iter().next()
294    } else {
295        None
296    }
297}