Skip to main content

lean_ctx/
setup.rs

1use std::path::PathBuf;
2
3use crate::core::editor_registry::{ConfigType, EditorTarget, WriteAction, WriteOptions};
4use crate::core::portable_binary::resolve_portable_binary;
5use crate::core::setup_report::{PlatformInfo, SetupItem, SetupReport, SetupStepReport};
6use chrono::Utc;
7use std::ffi::OsString;
8
9pub fn claude_config_json_path(home: &std::path::Path) -> PathBuf {
10    crate::core::editor_registry::claude_mcp_json_path(home)
11}
12
13pub fn claude_config_dir(home: &std::path::Path) -> PathBuf {
14    crate::core::editor_registry::claude_state_dir(home)
15}
16
17pub(crate) struct EnvVarGuard {
18    key: &'static str,
19    previous: Option<OsString>,
20}
21
22impl EnvVarGuard {
23    pub(crate) fn set(key: &'static str, value: &str) -> Self {
24        let previous = std::env::var_os(key);
25        std::env::set_var(key, value);
26        Self { key, previous }
27    }
28}
29
30impl Drop for EnvVarGuard {
31    fn drop(&mut self) {
32        if let Some(previous) = &self.previous {
33            std::env::set_var(self.key, previous);
34        } else {
35            std::env::remove_var(self.key);
36        }
37    }
38}
39
40pub fn run_setup() {
41    use crate::terminal_ui;
42
43    if crate::shell::is_non_interactive() {
44        eprintln!("Non-interactive terminal detected (no TTY on stdin).");
45        eprintln!("Running in non-interactive mode (equivalent to: lean-ctx setup --non-interactive --yes)");
46        eprintln!();
47        let opts = SetupOptions {
48            non_interactive: true,
49            yes: true,
50            fix: false,
51            json: false,
52        };
53        match run_setup_with_options(opts) {
54            Ok(report) => {
55                if !report.warnings.is_empty() {
56                    for w in &report.warnings {
57                        eprintln!("  warning: {w}");
58                    }
59                }
60            }
61            Err(e) => eprintln!("Setup error: {e}"),
62        }
63        return;
64    }
65
66    let home = match dirs::home_dir() {
67        Some(h) => h,
68        None => {
69            eprintln!("Cannot determine home directory");
70            std::process::exit(1);
71        }
72    };
73
74    let binary = resolve_portable_binary();
75
76    let home_str = home.to_string_lossy().to_string();
77
78    terminal_ui::print_setup_header();
79
80    // Step 1: Shell hook (legacy aliases + universal shell hook)
81    terminal_ui::print_step_header(1, 7, "Shell Hook");
82    crate::cli::cmd_init(&["--global".to_string()]);
83    crate::shell_hook::install_all(false);
84
85    // Step 2: Editor auto-detection + configuration
86    terminal_ui::print_step_header(2, 7, "AI Tool Detection");
87
88    let targets = crate::core::editor_registry::build_targets(&home);
89    let mut newly_configured: Vec<&str> = Vec::new();
90    let mut already_configured: Vec<&str> = Vec::new();
91    let mut not_installed: Vec<&str> = Vec::new();
92    let mut errors: Vec<&str> = Vec::new();
93
94    for target in &targets {
95        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
96
97        if !target.detect_path.exists() {
98            not_installed.push(target.name);
99            continue;
100        }
101
102        match crate::core::editor_registry::write_config_with_options(
103            target,
104            &binary,
105            WriteOptions {
106                overwrite_invalid: false,
107            },
108        ) {
109            Ok(res) if res.action == WriteAction::Already => {
110                terminal_ui::print_status_ok(&format!(
111                    "{:<20} \x1b[2m{short_path}\x1b[0m",
112                    target.name
113                ));
114                already_configured.push(target.name);
115            }
116            Ok(_) => {
117                terminal_ui::print_status_new(&format!(
118                    "{:<20} \x1b[2m{short_path}\x1b[0m",
119                    target.name
120                ));
121                newly_configured.push(target.name);
122            }
123            Err(e) => {
124                terminal_ui::print_status_warn(&format!("{}: {e}", target.name));
125                errors.push(target.name);
126            }
127        }
128    }
129
130    let total_ok = newly_configured.len() + already_configured.len();
131    if total_ok == 0 && errors.is_empty() {
132        terminal_ui::print_status_warn(
133            "No AI tools detected. Install one and re-run: lean-ctx setup",
134        );
135    }
136
137    if !not_installed.is_empty() {
138        println!(
139            "  \x1b[2m○ {} not detected: {}\x1b[0m",
140            not_installed.len(),
141            not_installed.join(", ")
142        );
143    }
144
145    // Step 3: Agent rules injection
146    terminal_ui::print_step_header(3, 7, "Agent Rules");
147    let rules_result = crate::rules_inject::inject_all_rules(&home);
148    for name in &rules_result.injected {
149        terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules injected\x1b[0m"));
150    }
151    for name in &rules_result.updated {
152        terminal_ui::print_status_new(&format!("{name:<20} \x1b[2mrules updated\x1b[0m"));
153    }
154    for name in &rules_result.already {
155        terminal_ui::print_status_ok(&format!("{name:<20} \x1b[2mrules up-to-date\x1b[0m"));
156    }
157    for err in &rules_result.errors {
158        terminal_ui::print_status_warn(err);
159    }
160    if rules_result.injected.is_empty()
161        && rules_result.updated.is_empty()
162        && rules_result.already.is_empty()
163        && rules_result.errors.is_empty()
164    {
165        terminal_ui::print_status_skip("No agent rules needed");
166    }
167
168    // Legacy agent hooks
169    for target in &targets {
170        if !target.detect_path.exists() || target.agent_key.is_empty() {
171            continue;
172        }
173        crate::hooks::install_agent_hook(&target.agent_key, true);
174    }
175
176    // Step 4: API Proxy configuration
177    terminal_ui::print_step_header(4, 7, "API Proxy");
178    crate::proxy_setup::install_proxy_env(&home, crate::proxy_setup::default_port(), false);
179    println!();
180    println!("  \x1b[2mStart proxy for maximum token savings:\x1b[0m");
181    println!("    \x1b[1mlean-ctx proxy start\x1b[0m");
182    println!("  \x1b[2mEnable autostart:\x1b[0m");
183    println!("    \x1b[1mlean-ctx proxy start --autostart\x1b[0m");
184
185    // Step 5: Data directory + diagnostics
186    terminal_ui::print_step_header(5, 7, "Environment Check");
187    let lean_dir = home.join(".lean-ctx");
188    if !lean_dir.exists() {
189        let _ = std::fs::create_dir_all(&lean_dir);
190        terminal_ui::print_status_new("Created ~/.lean-ctx/");
191    } else {
192        terminal_ui::print_status_ok("~/.lean-ctx/ ready");
193    }
194    crate::doctor::run_compact();
195
196    // Step 6: Data sharing
197    terminal_ui::print_step_header(6, 7, "Help Improve lean-ctx");
198    println!("  Share anonymous compression stats to make lean-ctx better.");
199    println!("  \x1b[1mNo code, no file names, no personal data — ever.\x1b[0m");
200    println!();
201    print!("  Enable anonymous data sharing? \x1b[1m[Y/n]\x1b[0m ");
202    use std::io::Write;
203    std::io::stdout().flush().ok();
204
205    let mut input = String::new();
206    let contribute = if std::io::stdin().read_line(&mut input).is_ok() {
207        let answer = input.trim().to_lowercase();
208        answer.is_empty() || answer == "y" || answer == "yes"
209    } else {
210        false
211    };
212
213    if contribute {
214        let config_dir = home.join(".lean-ctx");
215        let _ = std::fs::create_dir_all(&config_dir);
216        let config_path = config_dir.join("config.toml");
217        let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
218        if !config_content.contains("[cloud]") {
219            if !config_content.is_empty() && !config_content.ends_with('\n') {
220                config_content.push('\n');
221            }
222            config_content.push_str("\n[cloud]\ncontribute_enabled = true\n");
223            let _ = std::fs::write(&config_path, config_content);
224        }
225        terminal_ui::print_status_ok("Enabled — thank you!");
226    } else {
227        terminal_ui::print_status_skip("Skipped — enable later with: lean-ctx config");
228    }
229
230    // Step 7: Premium Features Configuration
231    terminal_ui::print_step_header(7, 7, "Premium Features");
232    configure_premium_features(&home);
233
234    // Summary
235    println!();
236    println!(
237        "  \x1b[1;32m✓ Setup complete!\x1b[0m  \x1b[1m{}\x1b[0m configured, \x1b[2m{} already set, {} skipped\x1b[0m",
238        newly_configured.len(),
239        already_configured.len(),
240        not_installed.len()
241    );
242
243    if !errors.is_empty() {
244        println!(
245            "  \x1b[33m⚠ {} error{}: {}\x1b[0m",
246            errors.len(),
247            if errors.len() != 1 { "s" } else { "" },
248            errors.join(", ")
249        );
250    }
251
252    // Next steps
253    let shell = std::env::var("SHELL").unwrap_or_default();
254    let source_cmd = if shell.contains("zsh") {
255        "source ~/.zshrc"
256    } else if shell.contains("fish") {
257        "source ~/.config/fish/config.fish"
258    } else if shell.contains("bash") {
259        "source ~/.bashrc"
260    } else {
261        "Restart your shell"
262    };
263
264    let dim = "\x1b[2m";
265    let bold = "\x1b[1m";
266    let cyan = "\x1b[36m";
267    let yellow = "\x1b[33m";
268    let rst = "\x1b[0m";
269
270    println!();
271    println!("  {bold}Next steps:{rst}");
272    println!();
273    println!("  {cyan}1.{rst} Reload your shell:");
274    println!("     {bold}{source_cmd}{rst}");
275    println!();
276
277    let mut tools_to_restart: Vec<String> =
278        newly_configured.iter().map(|s| s.to_string()).collect();
279    for name in rules_result
280        .injected
281        .iter()
282        .chain(rules_result.updated.iter())
283    {
284        if !tools_to_restart.iter().any(|t| t == name) {
285            tools_to_restart.push(name.clone());
286        }
287    }
288
289    if !tools_to_restart.is_empty() {
290        println!("  {cyan}2.{rst} {yellow}{bold}Restart your IDE / AI tool:{rst}");
291        println!("     {bold}{}{rst}", tools_to_restart.join(", "));
292        println!(
293            "     {dim}The MCP connection must be re-established for changes to take effect.{rst}"
294        );
295        println!("     {dim}Close and re-open the application completely.{rst}");
296    } else if !already_configured.is_empty() {
297        println!(
298            "  {cyan}2.{rst} {dim}Your tools are already configured — no restart needed.{rst}"
299        );
300    }
301
302    println!();
303    println!(
304        "  {dim}After restart, lean-ctx will automatically optimize every AI interaction.{rst}"
305    );
306    println!("  {dim}Verify with:{rst} {bold}lean-ctx gain{rst}");
307
308    // Logo + commands
309    println!();
310    terminal_ui::print_logo_animated();
311    terminal_ui::print_command_box();
312}
313
314#[derive(Debug, Clone, Copy, Default)]
315pub struct SetupOptions {
316    pub non_interactive: bool,
317    pub yes: bool,
318    pub fix: bool,
319    pub json: bool,
320}
321
322pub fn run_setup_with_options(opts: SetupOptions) -> Result<SetupReport, String> {
323    let _quiet_guard = opts.json.then(|| EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
324    let started_at = Utc::now();
325    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
326    let binary = resolve_portable_binary();
327    let home_str = home.to_string_lossy().to_string();
328
329    let mut steps: Vec<SetupStepReport> = Vec::new();
330
331    // Step: Shell Hook
332    let mut shell_step = SetupStepReport {
333        name: "shell_hook".to_string(),
334        ok: true,
335        items: Vec::new(),
336        warnings: Vec::new(),
337        errors: Vec::new(),
338    };
339    if !opts.non_interactive || opts.yes {
340        if opts.json {
341            crate::cli::cmd_init_quiet(&["--global".to_string()]);
342        } else {
343            crate::cli::cmd_init(&["--global".to_string()]);
344        }
345        crate::shell_hook::install_all(opts.json);
346        shell_step.items.push(SetupItem {
347            name: "init --global".to_string(),
348            status: "ran".to_string(),
349            path: None,
350            note: None,
351        });
352        shell_step.items.push(SetupItem {
353            name: "universal_shell_hook".to_string(),
354            status: "installed".to_string(),
355            path: None,
356            note: Some("~/.zshenv, ~/.bashenv, agent aliases".to_string()),
357        });
358    } else {
359        shell_step
360            .warnings
361            .push("non_interactive_without_yes: shell hook not installed (use --yes)".to_string());
362        shell_step.ok = false;
363        shell_step.items.push(SetupItem {
364            name: "init --global".to_string(),
365            status: "skipped".to_string(),
366            path: None,
367            note: Some("requires --yes in --non-interactive mode".to_string()),
368        });
369    }
370    steps.push(shell_step);
371
372    // Step: Editor MCP config
373    let mut editor_step = SetupStepReport {
374        name: "editors".to_string(),
375        ok: true,
376        items: Vec::new(),
377        warnings: Vec::new(),
378        errors: Vec::new(),
379    };
380
381    let targets = crate::core::editor_registry::build_targets(&home);
382    for target in &targets {
383        let short_path = shorten_path(&target.config_path.to_string_lossy(), &home_str);
384        if !target.detect_path.exists() {
385            editor_step.items.push(SetupItem {
386                name: target.name.to_string(),
387                status: "not_detected".to_string(),
388                path: Some(short_path),
389                note: None,
390            });
391            continue;
392        }
393
394        let res = crate::core::editor_registry::write_config_with_options(
395            target,
396            &binary,
397            WriteOptions {
398                overwrite_invalid: opts.fix,
399            },
400        );
401        match res {
402            Ok(w) => {
403                editor_step.items.push(SetupItem {
404                    name: target.name.to_string(),
405                    status: match w.action {
406                        WriteAction::Created => "created".to_string(),
407                        WriteAction::Updated => "updated".to_string(),
408                        WriteAction::Already => "already".to_string(),
409                    },
410                    path: Some(short_path),
411                    note: w.note,
412                });
413            }
414            Err(e) => {
415                editor_step.ok = false;
416                editor_step.items.push(SetupItem {
417                    name: target.name.to_string(),
418                    status: "error".to_string(),
419                    path: Some(short_path),
420                    note: Some(e),
421                });
422            }
423        }
424    }
425    steps.push(editor_step);
426
427    // Step: Agent rules
428    let mut rules_step = SetupStepReport {
429        name: "agent_rules".to_string(),
430        ok: true,
431        items: Vec::new(),
432        warnings: Vec::new(),
433        errors: Vec::new(),
434    };
435    let rules_result = crate::rules_inject::inject_all_rules(&home);
436    for n in rules_result.injected {
437        rules_step.items.push(SetupItem {
438            name: n,
439            status: "injected".to_string(),
440            path: None,
441            note: None,
442        });
443    }
444    for n in rules_result.updated {
445        rules_step.items.push(SetupItem {
446            name: n,
447            status: "updated".to_string(),
448            path: None,
449            note: None,
450        });
451    }
452    for n in rules_result.already {
453        rules_step.items.push(SetupItem {
454            name: n,
455            status: "already".to_string(),
456            path: None,
457            note: None,
458        });
459    }
460    for e in rules_result.errors {
461        rules_step.ok = false;
462        rules_step.errors.push(e);
463    }
464    steps.push(rules_step);
465
466    // Step: Agent-specific hooks (Codex, Cursor)
467    let mut hooks_step = SetupStepReport {
468        name: "agent_hooks".to_string(),
469        ok: true,
470        items: Vec::new(),
471        warnings: Vec::new(),
472        errors: Vec::new(),
473    };
474    for target in &targets {
475        if !target.detect_path.exists() {
476            continue;
477        }
478        match target.agent_key.as_str() {
479            "codex" => {
480                crate::hooks::agents::install_codex_hook();
481                hooks_step.items.push(SetupItem {
482                    name: "Codex integration".to_string(),
483                    status: "installed".to_string(),
484                    path: Some("~/.codex/".to_string()),
485                    note: Some(
486                        "Installs AGENTS/MCP guidance and Codex-compatible SessionStart/PreToolUse hooks."
487                            .to_string(),
488                    ),
489                });
490            }
491            "cursor" => {
492                let hooks_path = home.join(".cursor/hooks.json");
493                if !hooks_path.exists() {
494                    crate::hooks::agents::install_cursor_hook(true);
495                    hooks_step.items.push(SetupItem {
496                        name: "Cursor hooks".to_string(),
497                        status: "installed".to_string(),
498                        path: Some("~/.cursor/hooks.json".to_string()),
499                        note: None,
500                    });
501                }
502            }
503            _ => {}
504        }
505    }
506    if !hooks_step.items.is_empty() {
507        steps.push(hooks_step);
508    }
509
510    // Step: Proxy env vars
511    let mut proxy_step = SetupStepReport {
512        name: "proxy_env".to_string(),
513        ok: true,
514        items: Vec::new(),
515        warnings: Vec::new(),
516        errors: Vec::new(),
517    };
518    crate::proxy_setup::install_proxy_env(&home, crate::proxy_setup::default_port(), opts.json);
519    proxy_step.items.push(SetupItem {
520        name: "proxy_env".to_string(),
521        status: "configured".to_string(),
522        path: None,
523        note: Some("ANTHROPIC_BASE_URL, OPENAI_BASE_URL, GEMINI_API_BASE_URL".to_string()),
524    });
525    steps.push(proxy_step);
526
527    // Step: Environment / doctor (compact)
528    let mut env_step = SetupStepReport {
529        name: "doctor_compact".to_string(),
530        ok: true,
531        items: Vec::new(),
532        warnings: Vec::new(),
533        errors: Vec::new(),
534    };
535    let (passed, total) = crate::doctor::compact_score();
536    env_step.items.push(SetupItem {
537        name: "doctor".to_string(),
538        status: format!("{passed}/{total}"),
539        path: None,
540        note: None,
541    });
542    if passed != total {
543        env_step.warnings.push(format!(
544            "doctor compact not fully passing: {passed}/{total}"
545        ));
546    }
547    steps.push(env_step);
548
549    let finished_at = Utc::now();
550    let success = steps.iter().all(|s| s.ok);
551    let report = SetupReport {
552        schema_version: 1,
553        started_at,
554        finished_at,
555        success,
556        platform: PlatformInfo {
557            os: std::env::consts::OS.to_string(),
558            arch: std::env::consts::ARCH.to_string(),
559        },
560        steps,
561        warnings: Vec::new(),
562        errors: Vec::new(),
563    };
564
565    let path = SetupReport::default_path()?;
566    let mut content =
567        serde_json::to_string_pretty(&report).map_err(|e| format!("serialize report: {e}"))?;
568    content.push('\n');
569    crate::config_io::write_atomic(&path, &content)?;
570
571    Ok(report)
572}
573
574pub fn configure_agent_mcp(agent: &str) -> Result<(), String> {
575    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
576    let binary = resolve_portable_binary();
577
578    let mut targets = Vec::<EditorTarget>::new();
579
580    let push = |targets: &mut Vec<EditorTarget>,
581                name: &'static str,
582                config_path: PathBuf,
583                config_type: ConfigType| {
584        targets.push(EditorTarget {
585            name,
586            agent_key: agent.to_string(),
587            detect_path: PathBuf::from("/nonexistent"), // not used in direct agent config
588            config_path,
589            config_type,
590        });
591    };
592
593    match agent {
594        "cursor" => push(
595            &mut targets,
596            "Cursor",
597            home.join(".cursor/mcp.json"),
598            ConfigType::McpJson,
599        ),
600        "claude" | "claude-code" => push(
601            &mut targets,
602            "Claude Code",
603            crate::core::editor_registry::claude_mcp_json_path(&home),
604            ConfigType::McpJson,
605        ),
606        "windsurf" => push(
607            &mut targets,
608            "Windsurf",
609            home.join(".codeium/windsurf/mcp_config.json"),
610            ConfigType::McpJson,
611        ),
612        "codex" => push(
613            &mut targets,
614            "Codex CLI",
615            home.join(".codex/config.toml"),
616            ConfigType::Codex,
617        ),
618        "gemini" => {
619            push(
620                &mut targets,
621                "Gemini CLI",
622                home.join(".gemini/settings.json"),
623                ConfigType::GeminiSettings,
624            );
625            push(
626                &mut targets,
627                "Antigravity",
628                home.join(".gemini/antigravity/mcp_config.json"),
629                ConfigType::McpJson,
630            );
631        }
632        "antigravity" => push(
633            &mut targets,
634            "Antigravity",
635            home.join(".gemini/antigravity/mcp_config.json"),
636            ConfigType::McpJson,
637        ),
638        "copilot" => push(
639            &mut targets,
640            "VS Code / Copilot",
641            crate::core::editor_registry::vscode_mcp_path(),
642            ConfigType::VsCodeMcp,
643        ),
644        "crush" => push(
645            &mut targets,
646            "Crush",
647            home.join(".config/crush/crush.json"),
648            ConfigType::Crush,
649        ),
650        "pi" => push(
651            &mut targets,
652            "Pi Coding Agent",
653            home.join(".pi/agent/mcp.json"),
654            ConfigType::McpJson,
655        ),
656        "cline" => push(
657            &mut targets,
658            "Cline",
659            crate::core::editor_registry::cline_mcp_path(),
660            ConfigType::McpJson,
661        ),
662        "roo" => push(
663            &mut targets,
664            "Roo Code",
665            crate::core::editor_registry::roo_mcp_path(),
666            ConfigType::McpJson,
667        ),
668        "kiro" => push(
669            &mut targets,
670            "AWS Kiro",
671            home.join(".kiro/settings/mcp.json"),
672            ConfigType::McpJson,
673        ),
674        "verdent" => push(
675            &mut targets,
676            "Verdent",
677            home.join(".verdent/mcp.json"),
678            ConfigType::McpJson,
679        ),
680        "jetbrains" => {
681            // JetBrains uses servers[] array format, handled by install_jetbrains_hook
682        }
683        "qwen" => push(
684            &mut targets,
685            "Qwen Code",
686            home.join(".qwen/mcp.json"),
687            ConfigType::McpJson,
688        ),
689        "trae" => push(
690            &mut targets,
691            "Trae",
692            home.join(".trae/mcp.json"),
693            ConfigType::McpJson,
694        ),
695        "amazonq" => push(
696            &mut targets,
697            "Amazon Q Developer",
698            home.join(".aws/amazonq/mcp.json"),
699            ConfigType::McpJson,
700        ),
701        "opencode" => {
702            #[cfg(windows)]
703            let opencode_path = if let Ok(appdata) = std::env::var("APPDATA") {
704                std::path::PathBuf::from(appdata)
705                    .join("opencode")
706                    .join("opencode.json")
707            } else {
708                home.join(".config/opencode/opencode.json")
709            };
710            #[cfg(not(windows))]
711            let opencode_path = home.join(".config/opencode/opencode.json");
712            push(
713                &mut targets,
714                "OpenCode",
715                opencode_path,
716                ConfigType::OpenCode,
717            );
718        }
719        "aider" => push(
720            &mut targets,
721            "Aider",
722            home.join(".aider/mcp.json"),
723            ConfigType::McpJson,
724        ),
725        "amp" => {
726            // Amp uses amp.mcpServers in ~/.config/amp/settings.json, handled by install_amp_hook
727        }
728        "hermes" => push(
729            &mut targets,
730            "Hermes Agent",
731            home.join(".hermes/config.yaml"),
732            ConfigType::HermesYaml,
733        ),
734        _ => {
735            return Err(format!("Unknown agent '{agent}'"));
736        }
737    }
738
739    for t in &targets {
740        crate::core::editor_registry::write_config_with_options(
741            t,
742            &binary,
743            WriteOptions {
744                overwrite_invalid: true,
745            },
746        )?;
747    }
748
749    if agent == "kiro" {
750        install_kiro_steering(&home);
751    }
752
753    Ok(())
754}
755
756fn install_kiro_steering(home: &std::path::Path) {
757    let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
758    let steering_dir = cwd.join(".kiro").join("steering");
759    let steering_file = steering_dir.join("lean-ctx.md");
760
761    if steering_file.exists()
762        && std::fs::read_to_string(&steering_file)
763            .unwrap_or_default()
764            .contains("lean-ctx")
765    {
766        println!("  Kiro steering file already exists at .kiro/steering/lean-ctx.md");
767        return;
768    }
769
770    let _ = std::fs::create_dir_all(&steering_dir);
771    let _ = std::fs::write(&steering_file, crate::hooks::KIRO_STEERING_TEMPLATE);
772    println!("  \x1b[32m✓\x1b[0m Created .kiro/steering/lean-ctx.md (Kiro will now prefer lean-ctx tools)");
773}
774
775fn shorten_path(path: &str, home: &str) -> String {
776    if let Some(stripped) = path.strip_prefix(home) {
777        format!("~{stripped}")
778    } else {
779        path.to_string()
780    }
781}
782
783fn configure_premium_features(home: &std::path::Path) {
784    use crate::terminal_ui;
785    use std::io::Write;
786
787    let config_dir = home.join(".lean-ctx");
788    let _ = std::fs::create_dir_all(&config_dir);
789    let config_path = config_dir.join("config.toml");
790    let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
791
792    let dim = "\x1b[2m";
793    let bold = "\x1b[1m";
794    let rst = "\x1b[0m";
795
796    // Terse Agent Mode
797    println!(
798        "\n  {bold}Agent Output Optimization{rst} {dim}(reduces output tokens by 40-70%){rst}"
799    );
800    println!(
801        "  {dim}Levels: lite (concise), full (max density), ultra (expert pair-programmer){rst}"
802    );
803    print!("  Terse agent mode? {bold}[off/lite/full/ultra]{rst} {dim}(default: off){rst} ");
804    std::io::stdout().flush().ok();
805
806    let mut terse_input = String::new();
807    let terse_level = if std::io::stdin().read_line(&mut terse_input).is_ok() {
808        match terse_input.trim().to_lowercase().as_str() {
809            "lite" => "lite",
810            "full" => "full",
811            "ultra" => "ultra",
812            _ => "off",
813        }
814    } else {
815        "off"
816    };
817
818    if terse_level != "off" && !config_content.contains("terse_agent") {
819        if !config_content.is_empty() && !config_content.ends_with('\n') {
820            config_content.push('\n');
821        }
822        config_content.push_str(&format!("terse_agent = \"{terse_level}\"\n"));
823        terminal_ui::print_status_ok(&format!("Terse agent: {terse_level}"));
824    } else if terse_level == "off" {
825        terminal_ui::print_status_skip(
826            "Terse agent: off (change later with: lean-ctx terse <level>)",
827        );
828    }
829
830    // Tool Result Archive
831    println!(
832        "\n  {bold}Tool Result Archive{rst} {dim}(zero-loss: large outputs archived, retrievable via ctx_expand){rst}"
833    );
834    print!("  Enable auto-archive? {bold}[Y/n]{rst} ");
835    std::io::stdout().flush().ok();
836
837    let mut archive_input = String::new();
838    let archive_on = if std::io::stdin().read_line(&mut archive_input).is_ok() {
839        let a = archive_input.trim().to_lowercase();
840        a.is_empty() || a == "y" || a == "yes"
841    } else {
842        true
843    };
844
845    if archive_on && !config_content.contains("[archive]") {
846        if !config_content.is_empty() && !config_content.ends_with('\n') {
847            config_content.push('\n');
848        }
849        config_content.push_str("\n[archive]\nenabled = true\n");
850        terminal_ui::print_status_ok("Tool Result Archive: enabled");
851    } else if !archive_on {
852        terminal_ui::print_status_skip("Archive: off (enable later in config.toml)");
853    }
854
855    // Output Density
856    println!(
857        "\n  {bold}Output Density{rst} {dim}(compresses tool output: normal, terse, ultra){rst}"
858    );
859    print!("  Output density? {bold}[normal/terse/ultra]{rst} {dim}(default: normal){rst} ");
860    std::io::stdout().flush().ok();
861
862    let mut density_input = String::new();
863    let density = if std::io::stdin().read_line(&mut density_input).is_ok() {
864        match density_input.trim().to_lowercase().as_str() {
865            "terse" => "terse",
866            "ultra" => "ultra",
867            _ => "normal",
868        }
869    } else {
870        "normal"
871    };
872
873    if density != "normal" && !config_content.contains("output_density") {
874        if !config_content.is_empty() && !config_content.ends_with('\n') {
875            config_content.push('\n');
876        }
877        config_content.push_str(&format!("output_density = \"{density}\"\n"));
878        terminal_ui::print_status_ok(&format!("Output density: {density}"));
879    } else if density == "normal" {
880        terminal_ui::print_status_skip("Output density: normal (change later in config.toml)");
881    }
882
883    let _ = std::fs::write(&config_path, config_content);
884}