Skip to main content

lean_ctx_cli/setup/
helpers.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Setup helper routines (skill install, TOML key upserts, profile + premium
3//! feature configuration). Split out of `setup/mod.rs` for focus.
4#![allow(clippy::items_after_test_module)]
5
6#[allow(clippy::wildcard_imports)]
7use super::*;
8
9pub fn install_skill_files(home: &std::path::Path) -> Vec<(String, bool)> {
10    lean_ctx::rules_inject::install_all_skills(home)
11}
12
13pub(crate) fn install_kiro_steering(home: &std::path::Path) {
14    let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
15    let steering_dir = cwd.join(".kiro").join("steering");
16    let steering_file = steering_dir.join("lean-ctx.md");
17
18    if steering_file.exists()
19        && std::fs::read_to_string(&steering_file)
20            .unwrap_or_default()
21            .contains("lean-ctx")
22    {
23        println!("  Kiro steering file already exists at .kiro/steering/lean-ctx.md");
24        return;
25    }
26
27    let _ = std::fs::create_dir_all(&steering_dir);
28    let _ = std::fs::write(
29        &steering_file,
30        lean_ctx_hooks::hooks::kiro_steering_content(),
31    );
32    println!(
33        "  \x1b[32m✓\x1b[0m Created .kiro/steering/lean-ctx.md (Kiro will now prefer lean-ctx tools)"
34    );
35}
36
37pub(crate) fn configure_plan_mode_settings(newly_configured: &[&str], already_configured: &[&str]) {
38    use lean_ctx::terminal_ui;
39
40    let all_configured: Vec<&str> = newly_configured
41        .iter()
42        .chain(already_configured.iter())
43        .copied()
44        .collect();
45
46    let has_vscode = all_configured.contains(&"VS Code");
47    let has_claude = all_configured.contains(&"Claude Code");
48    let has_codebuddy = all_configured.contains(&"CodeBuddy");
49
50    if !has_vscode && !has_claude && !has_codebuddy {
51        return;
52    }
53
54    if has_vscode {
55        match lean_ctx::core::editor_registry::plan_mode::write_vscode_plan_settings() {
56            Ok(r) if r.action == WriteAction::Already => {
57                terminal_ui::print_status_ok(
58                    "VS Code            \x1b[2mplan mode already configured\x1b[0m",
59                );
60            }
61            Ok(_) => {
62                terminal_ui::print_status_new(
63                    "VS Code            \x1b[2mplan mode tools configured\x1b[0m",
64                );
65            }
66            Err(e) => {
67                terminal_ui::print_status_warn(&format!("VS Code plan mode: {e}"));
68            }
69        }
70    }
71
72    if has_claude {
73        match lean_ctx::core::editor_registry::plan_mode::write_claude_code_plan_permissions() {
74            Ok(r) if r.action == WriteAction::Already => {
75                terminal_ui::print_status_ok(
76                    "Claude Code        \x1b[2mplan mode permissions present\x1b[0m",
77                );
78            }
79            Ok(_) => {
80                terminal_ui::print_status_new(
81                    "Claude Code        \x1b[2mplan mode permissions added\x1b[0m",
82                );
83            }
84            Err(e) => {
85                terminal_ui::print_status_warn(&format!("Claude Code plan mode: {e}"));
86            }
87        }
88    }
89
90    if has_codebuddy {
91        match lean_ctx::core::editor_registry::plan_mode::write_claude_code_plan_permissions() {
92            Ok(r) if r.action == WriteAction::Already => {
93                terminal_ui::print_status_ok(
94                    "CodeBuddy          \x1b[2mplan mode permissions present\x1b[0m",
95                );
96            }
97            Ok(_) => {
98                terminal_ui::print_status_new(
99                    "CodeBuddy          \x1b[2mplan mode permissions added\x1b[0m",
100                );
101            }
102            Err(e) => {
103                terminal_ui::print_status_warn(&format!("CodeBuddy plan mode: {e}"));
104            }
105        }
106    }
107}
108
109pub(crate) fn shorten_path(path: &str, home: &str) -> String {
110    if let Some(stripped) = path.strip_prefix(home) {
111        format!("~{stripped}")
112    } else {
113        path.to_string()
114    }
115}
116
117/// Returns the byte offset where the root (top-level) section ends — i.e. the
118/// start of the first `[table]` / `[[array-of-tables]]` header line. Keys
119/// inserted before this offset live in the root section. Inserting at the end
120/// of the file instead would wrongly place a root key inside whatever table
121/// happens to be last (e.g. `[updates]`). If no section header is present,
122/// returns `content.len()`.
123fn root_section_end(content: &str) -> usize {
124    let mut offset = 0;
125    for line in content.lines() {
126        if line.trim_start().starts_with('[') {
127            return offset;
128        }
129        // `lines()` strips the terminator; account for the consumed `\n`.
130        offset += line.len() + 1;
131    }
132    content.len()
133}
134
135fn upsert_toml_key(content: &mut String, key: &str, value: &str) {
136    let pattern = format!("{key} = ");
137    let root_end = root_section_end(content);
138    // Only touch a root-section occurrence so we never clobber a same-named key
139    // inside a table (e.g. `compression_level` under `[profiles.cloud]`).
140    if let Some(start) = content[..root_end].find(&pattern) {
141        let line_end = content[start..]
142            .find('\n')
143            .map_or(content.len(), |p| start + p);
144        content.replace_range(start..line_end, &format!("{key} = \"{value}\""));
145    } else {
146        // Insert into the root section — before the first `[section]` header —
147        // never at the end of the file (which would land the key in the last
148        // table, e.g. `[updates]`).
149        let insert_at = root_end;
150        let mut prefix = String::new();
151        if insert_at > 0 && !content[..insert_at].ends_with('\n') {
152            prefix.push('\n');
153        }
154        let new_line = format!("{prefix}{key} = \"{value}\"\n");
155        content.insert_str(insert_at, &new_line);
156    }
157}
158
159fn remove_toml_key(content: &mut String, key: &str) {
160    let pattern = format!("{key} = ");
161    let root_end = root_section_end(content);
162    if let Some(start) = content[..root_end].find(&pattern) {
163        let line_end = content[start..]
164            .find('\n')
165            .map_or(content.len(), |p| start + p + 1);
166        content.replace_range(start..line_end, "");
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn upsert_inserts_new_key_into_root_before_section() {
176        let mut content =
177            String::from("memory_profile = \"balanced\"\n\n[updates]\nauto_update = true\n");
178        upsert_toml_key(&mut content, "compression_level", "lite");
179        let updates_pos = content.find("[updates]").unwrap();
180        let key_pos = content.find("compression_level").unwrap();
181        assert!(key_pos < updates_pos, "root key must precede [updates]");
182        assert!(
183            !content[updates_pos..].contains("compression_level"),
184            "key must not leak into [updates]"
185        );
186        assert!(content.contains("compression_level = \"lite\""));
187    }
188
189    #[test]
190    fn upsert_inserts_root_key_when_section_is_first_line() {
191        let mut content = String::from("[updates]\nauto_update = true\n");
192        upsert_toml_key(&mut content, "compression_level", "standard");
193        assert!(
194            content.starts_with("compression_level = \"standard\"\n"),
195            "root key should be inserted before the leading section header"
196        );
197    }
198
199    #[test]
200    fn upsert_updates_only_root_occurrence() {
201        let mut content = String::from(
202            "compression_level = \"off\"\n\n[profiles.cloud]\ncompression_level = \"max\"\n",
203        );
204        upsert_toml_key(&mut content, "compression_level", "lite");
205        assert!(content.starts_with("compression_level = \"lite\""));
206        assert!(
207            content.contains("[profiles.cloud]\ncompression_level = \"max\""),
208            "profile-scoped value must be left untouched"
209        );
210    }
211
212    #[test]
213    fn upsert_inserts_into_empty_content() {
214        let mut content = String::new();
215        upsert_toml_key(&mut content, "compression_level", "lite");
216        assert_eq!(content, "compression_level = \"lite\"\n");
217    }
218
219    #[test]
220    fn remove_only_deletes_root_occurrence() {
221        let mut content =
222            String::from("terse_agent = true\n\n[profiles.local]\nterse_agent = true\n");
223        remove_toml_key(&mut content, "terse_agent");
224        assert!(
225            !content.starts_with("terse_agent"),
226            "root key should be removed"
227        );
228        assert!(
229            content.contains("[profiles.local]\nterse_agent = true"),
230            "profile-scoped value must remain"
231        );
232    }
233
234    #[test]
235    fn root_section_end_handles_no_section() {
236        assert_eq!(root_section_end("a = 1\nb = 2\n"), 12);
237        assert_eq!(root_section_end(""), 0);
238    }
239
240    #[test]
241    fn root_section_end_finds_first_header() {
242        let _home = lean_ctx::core::data_dir::test_env_lock();
243        assert_eq!(root_section_end("a = 1\n[updates]\nb = 2\n"), 6);
244        assert_eq!(root_section_end("[updates]\n"), 0);
245        assert_eq!(root_section_end("a = 1\n[[items]]\n"), 6);
246    }
247}
248
249pub(crate) fn configure_tool_profile() {
250    use lean_ctx::terminal_ui;
251    use std::io::Write;
252
253    let cfg = lean_ctx::core::config::Config::load();
254    let current = cfg.tool_profile_effective();
255    let pinned = cfg.tool_profile.is_some() || std::env::var("LEAN_CTX_TOOL_PROFILE").is_ok();
256
257    // An explicitly pinned non-power profile is a deliberate, bounded choice —
258    // don't re-nag. Power (pinned or legacy fallback) re-prompts because it
259    // advertises every tool schema, the single largest fixed cost (#575).
260    if pinned && !matches!(current, lean_ctx::core::tool_profiles::ToolProfile::Power) {
261        terminal_ui::print_status_ok(&format!(
262            "Tool profile: {} ({} tools)",
263            current.as_str(),
264            current.tool_count()
265        ));
266        return;
267    }
268
269    let dim = "\x1b[2m";
270    let bold = "\x1b[1m";
271    let cyan = "\x1b[36m";
272    let rst = "\x1b[0m";
273
274    let registry_count = lean_ctx_server::server::registry::tool_count();
275    let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
276
277    println!("  {dim}Control how many MCP tool schemas your AI agent sees.{rst}");
278    println!("  {dim}Fewer advertised tools = less context overhead. Every tool stays{rst}");
279    println!("  {dim}callable through ctx_call, even when its schema is not advertised.{rst}");
280    println!();
281    println!(
282        "  {cyan}lean{rst}      — {lazy_count} tools  {dim}(lazy core, recommended — lowest token overhead){rst}"
283    );
284    println!(
285        "  {cyan}minimal{rst}   — 5 tools  {dim}(ctx_read, ctx_shell, ctx_search, ctx_glob, ctx_tree){rst}"
286    );
287    println!("  {cyan}standard{rst}  — 16 tools  {dim}(balanced set for most workflows){rst}");
288    println!(
289        "  {cyan}power{rst}     — {registry_count} tools  {dim}(everything advertised, costs the most context){rst}"
290    );
291    println!();
292    print!("  Tool profile? {bold}[lean/minimal/standard/power]{rst} {dim}(default: lean){rst} ");
293    std::io::stdout().flush().ok();
294
295    let mut profile_input = String::new();
296    let profile_name = if std::io::stdin().read_line(&mut profile_input).is_ok() {
297        let trimmed = profile_input.trim().to_lowercase();
298        match trimmed.as_str() {
299            "minimal" | "min" => "minimal",
300            "standard" | "std" => "standard",
301            "power" | "full" | "all" => "power",
302            _ => "lean",
303        }
304    } else {
305        "lean"
306    };
307
308    if profile_name == "lean" {
309        match lean_ctx::core::tool_profiles::clear_profile_in_config() {
310            Ok(()) => terminal_ui::print_status_ok(&format!(
311                "Tool profile: lean ({lazy_count} tools advertised, all reachable via ctx_call)"
312            )),
313            Err(e) => terminal_ui::print_status_warn(&format!("Could not save tool profile: {e}")),
314        }
315        return;
316    }
317
318    match lean_ctx::core::tool_profiles::set_profile_in_config(profile_name) {
319        Ok(()) => {
320            let profile = lean_ctx::core::tool_profiles::ToolProfile::parse(profile_name)
321                .unwrap_or(lean_ctx::core::tool_profiles::ToolProfile::Standard);
322            let count = match &profile {
323                lean_ctx::core::tool_profiles::ToolProfile::Power => registry_count,
324                other => other.tool_count(),
325            };
326            terminal_ui::print_status_ok(&format!("Tool profile: {profile_name} ({count} tools)"));
327        }
328        Err(e) => {
329            terminal_ui::print_status_warn(&format!("Could not save tool profile: {e}"));
330        }
331    }
332}
333
334pub(crate) fn configure_premium_features(home: &std::path::Path) {
335    use lean_ctx::terminal_ui;
336    use std::io::Write;
337
338    let config_path = lean_ctx::core::config::Config::path()
339        .unwrap_or_else(|| home.join(".config/lean-ctx").join("config.toml"));
340    if let Some(dir) = config_path.parent() {
341        let _ = std::fs::create_dir_all(dir);
342    }
343    let mut config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
344
345    let dim = "\x1b[2m";
346    let bold = "\x1b[1m";
347    let cyan = "\x1b[36m";
348    let rst = "\x1b[0m";
349
350    // Unified Compression Level (replaces terse_agent + output_density)
351    println!("\n  {bold}Compression Level{rst} {dim}(controls all token optimization layers){rst}");
352    println!("  {dim}Applies to tool output, agent prompts, and protocol mode.{rst}");
353    println!();
354    println!("  {cyan}off{rst}      — No compression (full verbose output)");
355    println!(
356        "  {cyan}lite{rst}     — Light: concise output, basic terse filtering {dim}(~25% savings){rst}"
357    );
358    println!(
359        "  {cyan}standard{rst} — Dense output + compact protocol + pattern-aware {dim}(~45% savings){rst}"
360    );
361    println!(
362        "  {cyan}max{rst}      — Expert mode: TDD protocol, all layers active {dim}(~65% savings){rst}"
363    );
364    println!();
365    print!("  Compression level? {bold}[off/lite/standard/max]{rst} {dim}(default: off){rst} ");
366    std::io::stdout().flush().ok();
367
368    let mut level_input = String::new();
369    let level = if std::io::stdin().read_line(&mut level_input).is_ok() {
370        match level_input.trim().to_lowercase().as_str() {
371            "lite" => "lite",
372            "standard" | "std" => "standard",
373            "max" => "max",
374            _ => "off",
375        }
376    } else {
377        "off"
378    };
379
380    // Stage the compression change in the config text; the success line is only
381    // emitted after the write below actually persists (#415).
382    let (effective_level, compression_status) = if level != "off" {
383        upsert_toml_key(&mut config_content, "compression_level", level);
384        remove_toml_key(&mut config_content, "terse_agent");
385        remove_toml_key(&mut config_content, "output_density");
386        (
387            lean_ctx::core::config::CompressionLevel::from_str_label(level),
388            StatusLine::ok(format!("Compression: {level}")),
389        )
390    } else if config_content.contains("compression_level") {
391        upsert_toml_key(&mut config_content, "compression_level", "off");
392        (
393            Some(lean_ctx::core::config::CompressionLevel::Off),
394            StatusLine::ok("Compression: off".to_string()),
395        )
396    } else {
397        (
398            Some(lean_ctx::core::config::CompressionLevel::Off),
399            StatusLine::skip(
400                "Compression: off (change later with: lean-ctx compression <level>)".to_string(),
401            ),
402        )
403    };
404
405    // Tool Result Archive
406    println!(
407        "\n  {bold}Tool Result Archive{rst} {dim}(zero-loss: large outputs archived, retrievable via ctx_expand){rst}"
408    );
409    print!("  Enable auto-archive? {bold}[Y/n]{rst} ");
410    std::io::stdout().flush().ok();
411
412    let mut archive_input = String::new();
413    let archive_on = if std::io::stdin().read_line(&mut archive_input).is_ok() {
414        let a = archive_input.trim().to_lowercase();
415        a.is_empty() || a == "y" || a == "yes"
416    } else {
417        true
418    };
419
420    let archive_status = if archive_on && !config_content.contains("[archive]") {
421        if !config_content.is_empty() && !config_content.ends_with('\n') {
422            config_content.push('\n');
423        }
424        config_content.push_str("\n[archive]\nenabled = true\n");
425        Some(StatusLine::ok("Tool Result Archive: enabled".to_string()))
426    } else if !archive_on {
427        Some(StatusLine::skip(
428            "Archive: off (enable later in config.toml)".to_string(),
429        ))
430    } else {
431        None
432    };
433
434    // Single atomic write. Only claim success — and only inject the rules prompt —
435    // once the config has genuinely been persisted; a swallowed write error here
436    // is exactly what made setup report settings it never applied (#415).
437    match lean_ctx::config_io::write_atomic_with_backup(&config_path, &config_content) {
438        Ok(()) => {
439            compression_status.emit();
440            if effective_level.is_some() {
441                let home = dirs::home_dir().unwrap_or_default();
442                let result = lean_ctx::rules_inject::inject_all_rules(&home);
443                if !result.updated.is_empty() {
444                    terminal_ui::print_status_ok(&format!(
445                        "Updated {} rules file(s) with compression prompt",
446                        result.updated.len()
447                    ));
448                }
449            }
450            if let Some(status) = archive_status {
451                status.emit();
452            }
453        }
454        Err(e) => {
455            terminal_ui::print_status_warn(&format!(
456                "Could not save settings to {}: {e}",
457                config_path.display()
458            ));
459            terminal_ui::print_status_warn(
460                "Premium features were not applied — re-run `lean-ctx setup` or edit config.toml manually",
461            );
462        }
463    }
464}
465
466/// A setup status line whose emission is deferred until the underlying config
467/// write succeeds, so the wizard never reports a setting it failed to persist.
468struct StatusLine {
469    skip: bool,
470    msg: String,
471}
472
473impl StatusLine {
474    fn ok(msg: String) -> Self {
475        Self { skip: false, msg }
476    }
477    fn skip(msg: String) -> Self {
478        Self { skip: true, msg }
479    }
480    fn emit(&self) {
481        if self.skip {
482            lean_ctx::terminal_ui::print_status_skip(&self.msg);
483        } else {
484            lean_ctx::terminal_ui::print_status_ok(&self.msg);
485        }
486    }
487}