Skip to main content

lean_ctx/cli/
config_cmd.rs

1use crate::core::config;
2use crate::core::theme;
3
4pub fn cmd_config(args: &[String]) {
5    let cfg = config::Config::load();
6
7    if args.is_empty() {
8        println!("{}", cfg.show());
9        return;
10    }
11
12    match args[0].as_str() {
13        "init" | "create" => {
14            let default = config::Config::default();
15            match default.save() {
16                Ok(()) => {
17                    let path = config::Config::path().map_or_else(
18                        || "~/.lean-ctx/config.toml".to_string(),
19                        |p| p.to_string_lossy().to_string(),
20                    );
21                    println!("Created default config at {path}");
22                }
23                Err(e) => eprintln!("Error: {e}"),
24            }
25        }
26        "set" => {
27            if args.len() < 3 {
28                eprintln!("Usage: lean-ctx config set <key> <value>");
29                std::process::exit(1);
30            }
31            let mut cfg = cfg;
32            let key = &args[1];
33            let val = &args[2];
34            match key.as_str() {
35                "ultra_compact" => cfg.ultra_compact = val == "true",
36                "tee_on_error" | "tee_mode" => {
37                    cfg.tee_mode = match val.as_str() {
38                        "true" | "failures" => config::TeeMode::Failures,
39                        "always" => config::TeeMode::Always,
40                        "false" | "never" => config::TeeMode::Never,
41                        _ => {
42                            eprintln!("Valid tee_mode values: always, failures, never");
43                            std::process::exit(1);
44                        }
45                    };
46                }
47                "checkpoint_interval" => {
48                    cfg.checkpoint_interval = val.parse().unwrap_or(15);
49                }
50                "theme" => {
51                    if theme::from_preset(val).is_some() || val == "custom" {
52                        cfg.theme.clone_from(val);
53                    } else {
54                        eprintln!(
55                            "Unknown theme '{val}'. Available: {}",
56                            theme::PRESET_NAMES.join(", ")
57                        );
58                        std::process::exit(1);
59                    }
60                }
61                "slow_command_threshold_ms" => {
62                    cfg.slow_command_threshold_ms = val.parse().unwrap_or(5000);
63                }
64                "passthrough_urls" => {
65                    cfg.passthrough_urls = val.split(',').map(|s| s.trim().to_string()).collect();
66                }
67                "excluded_commands" => {
68                    cfg.excluded_commands = val
69                        .split(',')
70                        .map(|s| s.trim().to_string())
71                        .filter(|s| !s.is_empty())
72                        .collect();
73                }
74                "rules_scope" => match val.as_str() {
75                    "global" | "project" | "both" => {
76                        cfg.rules_scope = Some(val.clone());
77                    }
78                    _ => {
79                        eprintln!("Valid rules_scope values: global, project, both");
80                        std::process::exit(1);
81                    }
82                },
83                _ => {
84                    eprintln!("Unknown config key: {key}");
85                    std::process::exit(1);
86                }
87            }
88            match cfg.save() {
89                Ok(()) => println!("Updated {key} = {val}"),
90                Err(e) => eprintln!("Error saving config: {e}"),
91            }
92        }
93        _ => {
94            eprintln!("Usage: lean-ctx config [init|set <key> <value>]");
95            std::process::exit(1);
96        }
97    }
98}
99
100pub fn cmd_benchmark(args: &[String]) {
101    use crate::core::benchmark;
102
103    let action = args.first().map_or("run", std::string::String::as_str);
104
105    match action {
106        "run" => {
107            let path = args.get(1).map_or(".", std::string::String::as_str);
108            let is_json = args.iter().any(|a| a == "--json");
109
110            let result = benchmark::run_project_benchmark(path);
111            if is_json {
112                println!("{}", benchmark::format_json(&result));
113            } else {
114                println!("{}", benchmark::format_terminal(&result));
115            }
116        }
117        "report" => {
118            let path = args.get(1).map_or(".", std::string::String::as_str);
119            let result = benchmark::run_project_benchmark(path);
120            println!("{}", benchmark::format_markdown(&result));
121        }
122        _ => {
123            if std::path::Path::new(action).exists() {
124                let result = benchmark::run_project_benchmark(action);
125                println!("{}", benchmark::format_terminal(&result));
126            } else {
127                eprintln!("Usage: lean-ctx benchmark run [path] [--json]");
128                eprintln!("       lean-ctx benchmark report [path]");
129                std::process::exit(1);
130            }
131        }
132    }
133}
134
135pub fn cmd_stats(args: &[String]) {
136    match args.first().map(std::string::String::as_str) {
137        Some("reset-cep") => {
138            crate::core::stats::reset_cep();
139            println!("CEP stats reset. Shell hook data preserved.");
140        }
141        Some("json") => {
142            let store = crate::core::stats::load();
143            println!(
144                "{}",
145                serde_json::to_string_pretty(&store).unwrap_or_else(|_| "{}".to_string())
146            );
147        }
148        _ => {
149            let store = crate::core::stats::load();
150            let input_saved = store
151                .total_input_tokens
152                .saturating_sub(store.total_output_tokens);
153            let pct = if store.total_input_tokens > 0 {
154                input_saved as f64 / store.total_input_tokens as f64 * 100.0
155            } else {
156                0.0
157            };
158            println!("Commands:    {}", store.total_commands);
159            println!("Input:       {} tokens", store.total_input_tokens);
160            println!("Output:      {} tokens", store.total_output_tokens);
161            println!("Saved:       {input_saved} tokens ({pct:.1}%)");
162            println!();
163            println!("CEP sessions:  {}", store.cep.sessions);
164            println!(
165                "CEP tokens:    {} → {}",
166                store.cep.total_tokens_original, store.cep.total_tokens_compressed
167            );
168            println!();
169            println!("Subcommands: stats reset-cep | stats json");
170        }
171    }
172}
173
174pub fn cmd_cache(args: &[String]) {
175    use crate::core::cli_cache;
176    match args.first().map(std::string::String::as_str) {
177        Some("clear") => {
178            let count = cli_cache::clear();
179            println!("Cleared {count} cached entries.");
180        }
181        Some("reset") => {
182            let project_flag = args.get(1).map(std::string::String::as_str) == Some("--project");
183            if project_flag {
184                let root =
185                    crate::core::session::SessionState::load_latest().and_then(|s| s.project_root);
186                if let Some(root) = root {
187                    let count = cli_cache::clear_project(&root);
188                    println!("Reset {count} cache entries for project: {root}");
189                } else {
190                    eprintln!("No active project root found. Start a session first.");
191                    std::process::exit(1);
192                }
193            } else {
194                let count = cli_cache::clear();
195                println!("Reset all {count} cache entries.");
196            }
197        }
198        Some("stats") => {
199            let (hits, reads, entries) = cli_cache::stats();
200            let rate = if reads > 0 {
201                (hits as f64 / reads as f64 * 100.0).round() as u32
202            } else {
203                0
204            };
205            println!("CLI Cache Stats:");
206            println!("  Entries:   {entries}");
207            println!("  Reads:     {reads}");
208            println!("  Hits:      {hits}");
209            println!("  Hit Rate:  {rate}%");
210        }
211        Some("invalidate") => {
212            if args.len() < 2 {
213                eprintln!("Usage: lean-ctx cache invalidate <path>");
214                std::process::exit(1);
215            }
216            cli_cache::invalidate(&args[1]);
217            println!("Invalidated cache for {}", args[1]);
218        }
219        _ => {
220            let (hits, reads, entries) = cli_cache::stats();
221            let rate = if reads > 0 {
222                (hits as f64 / reads as f64 * 100.0).round() as u32
223            } else {
224                0
225            };
226            println!("CLI File Cache: {entries} entries, {hits}/{reads} hits ({rate}%)");
227            println!();
228            println!("Subcommands:");
229            println!("  cache stats       Show detailed stats");
230            println!("  cache clear       Clear all cached entries");
231            println!("  cache reset       Reset all cache (or --project for current project only)");
232            println!("  cache invalidate  Remove specific file from cache");
233        }
234    }
235}