Skip to main content

lean_ctx_cli/cli/
config_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use lean_ctx::core::config;
4use lean_ctx::core::theme;
5
6mod cache;
7pub use cache::cmd_cache;
8
9pub fn cmd_config(args: &[String]) {
10    let cfg = config::Config::load();
11
12    if args.is_empty() {
13        println!("{}", cfg.show());
14        println!(
15            "\nTip: this is the full config. For the few knobs most people touch, run\n     `lean-ctx config show` (high-level summary), or change one with\n     `lean-ctx config set <key> <value>`."
16        );
17        return;
18    }
19
20    match args[0].as_str() {
21        "init" | "create" => {
22            let full = args.iter().any(|a| a == "--full");
23            let created = if full {
24                init_full_config()
25            } else {
26                write_simplified_config().map(|path| format!("Created simplified config at {path}"))
27            };
28            // F9c: a config that was not written is an error exit.
29            match created {
30                Ok(message) => println!("{message}"),
31                Err(e) => {
32                    eprintln!("Error: {e}");
33                    std::process::exit(1);
34                }
35            }
36        }
37        "set" => {
38            if args.len() < 3 {
39                eprintln!("Usage: lean-ctx config set <key> <value>");
40                std::process::exit(1);
41            }
42            let key = &args[1];
43            let val = &args[2];
44
45            // Special validation hooks for keys that need custom logic beyond
46            // what the schema type system can express. These either hard-fail
47            // early, or normalize the value/key that is actually persisted —
48            // the resolved (write_key, write_val) then flows through the single
49            // governed write path below so the #852 review covers every route.
50            let (write_key, write_val): (String, String) = match key.as_str() {
51                "theme" if theme::from_preset(val).is_none() && val != "custom" => {
52                    eprintln!(
53                        "Unknown theme '{val}'. Available: {}",
54                        theme::PRESET_NAMES.join(", ")
55                    );
56                    std::process::exit(1);
57                }
58                "tee_on_error" | "tee_mode" => {
59                    let normalized = match val.as_str() {
60                        "true" => "failures",
61                        "false" => "never",
62                        other => other,
63                    };
64                    ("tee_mode".to_string(), normalized.to_string())
65                }
66                "project_root" => {
67                    let path = std::path::Path::new(val.as_str());
68                    if !path.exists() || !path.is_dir() {
69                        eprintln!("Error: '{val}' is not an existing directory.");
70                        std::process::exit(1);
71                    }
72                    (key.clone(), val.clone())
73                }
74                "embedding.model"
75                    if lean_ctx::core::embeddings::model_registry::EmbeddingModel::from_str_name(
76                        val,
77                    )
78                    .is_none() =>
79                {
80                    eprintln!(
81                        "Unknown embedding model '{val}'. Available: minilm, potion-code \
82                         (no ONNX Runtime needed), nomic — or hf:org/repo[@revision] for any \
83                         HuggingFace repo with an \
84                         ONNX export, e.g. hf:jinaai/jina-embeddings-v2-base-code for code \
85                         (see docs/guides/custom-embeddings.md)."
86                    );
87                    std::process::exit(1);
88                }
89                "proxy.anthropic_upstream"
90                | "proxy.openai_upstream"
91                | "proxy.chatgpt_upstream"
92                | "proxy.gemini_upstream" => {
93                    let effective = normalize_optional_upstream(val).unwrap_or_default();
94                    (key.clone(), effective)
95                }
96                _ => (key.clone(), val.clone()),
97            };
98
99            write_config_key(&write_key, &write_val, key, val, args);
100        }
101        "schema" => {
102            let schema = config::schema::ConfigSchema::generate();
103            println!(
104                "{}",
105                serde_json::to_string_pretty(&schema).unwrap_or_else(|_| "{}".to_string())
106            );
107        }
108        "validate" => {
109            cmd_validate();
110        }
111        "show" | "effective" => {
112            cmd_show_effective();
113        }
114        "path" | "which" => {
115            cmd_config_path();
116        }
117        "apply" | "reload" => {
118            cmd_apply();
119        }
120        _ => {
121            eprintln!("Usage: lean-ctx config [init|set|show|schema|validate|apply|path]");
122            std::process::exit(1);
123        }
124    }
125}
126
127/// Single governed write path for `config set` (#852).
128///
129/// `key`/`value` are the resolved pair actually persisted; `display_key`/
130/// `display_val` are what the user typed (kept for messaging, e.g. when a value
131/// was normalized). Behavior:
132/// - **no-op** (current == new): report "unchanged", write nothing.
133/// - **consequential key** ([`config::risk`]): print a before→after review + a
134///   risk note, then require confirmation or `--yes`; abort if declined.
135/// - **routine key**: write directly, as before.
136fn write_config_key(key: &str, value: &str, display_key: &str, display_val: &str, args: &[String]) {
137    const BOLD: &str = "\x1b[1m";
138    const DIM: &str = "\x1b[2m";
139    const YELLOW: &str = "\x1b[33m";
140    const RST: &str = "\x1b[0m";
141
142    let current = config::setter::current_value(key);
143
144    if current.as_deref() == Some(value) {
145        println!("{display_key} is already set to {display_val} — unchanged.");
146        return;
147    }
148
149    if let Some(risk) = config::risk::classify(key) {
150        let before = current.as_deref().unwrap_or("(default)");
151        let after = if value.is_empty() { "(default)" } else { value };
152        println!("{BOLD}Review change to {display_key}{RST}");
153        println!("  {before}  →  {after}");
154        println!("  {YELLOW}{}{RST}", risk.note);
155        if !super::prompt::confirm(
156            &format!("Apply {display_key} = {display_val}?"),
157            super::prompt::wants_yes(args),
158        ) {
159            println!("{DIM}Aborted — {display_key} left unchanged.{RST}");
160            return;
161        }
162    }
163
164    match config::setter::set_by_key(key, value) {
165        Ok(_) => println!("Updated {display_key} = {display_val}"),
166        Err(e) => {
167            eprintln!("{e}");
168            std::process::exit(1);
169        }
170    }
171}
172
173/// Resolves the [`config::Config`] that `config init --full` should persist.
174///
175/// `existing_raw` is the verbatim content of the current GLOBAL `config.toml`
176/// (never the project-local `.lean-ctx.toml` — those overrides must not leak
177/// into the global file). When it holds a non-empty, parseable document we
178/// return its deserialized form so every user value is retained; an empty/absent
179/// file yields defaults, and an unparseable one is surfaced as an error so the
180/// caller can refuse to clobber it.
181///
182/// This is the regression guard for #443: `config init --full` previously wrote
183/// `Config::default()`, and `Config::save()` overwrites any key present in both
184/// the incoming document and the file (see `config_io::merge_table`), which
185/// silently reset customized values like `max_ram_percent` or `compression_level`.
186fn config_for_full_init(existing_raw: Option<&str>) -> Result<config::Config, String> {
187    match existing_raw.map(str::trim).filter(|raw| !raw.is_empty()) {
188        Some(raw) => toml::from_str::<config::Config>(raw).map_err(|e| e.to_string()),
189        None => Ok(config::Config::default()),
190    }
191}
192
193/// Implements `config init --full`: (re)writes the global config as a fully
194/// annotated reference document, seeded with the user's existing values (#443).
195///
196/// Unlike `save()` (which keeps the file minimal), this emits every key with its
197/// documentation. The body is a verbatim serialization of the resolved config,
198/// so no customized value is ever lost; an unparseable existing file is refused
199/// upstream by [`config_for_full_init`] rather than clobbered.
200fn init_full_config() -> Result<String, String> {
201    let path = config::Config::path().ok_or("cannot determine the config path")?;
202
203    let existing_raw = std::fs::read_to_string(&path).ok();
204
205    let cfg = config_for_full_init(existing_raw.as_deref()).map_err(|e| {
206        format!(
207            "refusing to overwrite an unparseable config.toml ({e}).\n  \
208             Fix it manually or run `lean-ctx doctor --fix`, then retry."
209        )
210    })?;
211
212    let schema = config::schema::ConfigSchema::generate();
213    let rendered = config::render_annotated_config(&cfg, &schema);
214
215    lean_ctx::config_io::write_atomic_with_backup(&path, &rendered)?;
216    Ok(format!(
217        "Created full annotated config at {}",
218        path.display()
219    ))
220}
221
222fn cmd_apply() {
223    use lean_ctx::daemon;
224    use lean_ctx::ipc;
225
226    println!("Applying config changes…");
227
228    // 1. Validate config first
229    println!("\n[1/4] Validating config…");
230    let schema = config::schema::ConfigSchema::generate();
231    let known = schema.known_keys();
232    let cfg = config::Config::load();
233
234    if let Some(path) = config::Config::path()
235        && path.exists()
236        && let Ok(raw) = std::fs::read_to_string(&path)
237        && let Ok(table) = raw.parse::<toml::Table>()
238    {
239        let mut user_keys = Vec::new();
240        fn collect_flat(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
241            for (k, v) in table {
242                let full = if prefix.is_empty() {
243                    k.clone()
244                } else {
245                    format!("{prefix}.{k}")
246                };
247                if let toml::Value::Table(sub) = v {
248                    collect_flat(sub, &full, out);
249                } else {
250                    out.push(full);
251                }
252            }
253        }
254        collect_flat(&table, "", &mut user_keys);
255        for key in &user_keys {
256            if let Some(entry) = config::retired::retired_key(key) {
257                eprintln!("  [WARN] Retired key (no effect, {}): {key}", entry.note);
258            }
259        }
260        for hint in config::renamed::hints(&user_keys) {
261            eprintln!("  [INFO] Renamed key: {hint}");
262        }
263        let warnings: Vec<_> = user_keys
264            .iter()
265            .filter(|uk| config::retired::retired_key(uk).is_none())
266            .filter(|uk| config::renamed::renamed_key(uk).is_none())
267            .filter(|uk| {
268                !known.contains(uk) && !known.iter().any(|k| uk.starts_with(&format!("{k}.")))
269            })
270            .collect();
271        if warnings.is_empty() {
272            println!("  ✓ All config keys valid.");
273        } else {
274            for w in &warnings {
275                eprintln!("  [WARN] Unknown key: {w}");
276            }
277            eprintln!(
278                "  {} unknown key(s) found. Continuing anyway…",
279                warnings.len()
280            );
281        }
282    }
283
284    // 2. Restart processes
285    println!("\n[2/4] Restarting processes…");
286    lean_ctx::proxy_autostart::stop();
287
288    if let Err(e) = daemon::stop_daemon() {
289        eprintln!("  Warning: daemon stop: {e}");
290    }
291
292    // Only the services restarted below (daemon, proxy). IDE-owned MCP stdio
293    // servers are never selected: killing one severs the active Codex or
294    // Claude Code connection and can leave the host stuck on "connecting"
295    // until it is restarted (#2176).
296    let report = daemon::stop_owned_services(ipc::process::ServiceSweep::Restartable);
297    if let Some(line) = report.stopped_line() {
298        println!("  {line}");
299    }
300    if let Some(line) = report.survivors_line() {
301        eprintln!("  Warning: {line}");
302    }
303
304    daemon::cleanup_daemon_files();
305    // The proxy runs again: via autostart where installed, otherwise started
306    // with the arguments it ran with (#2176 review #4).
307    let autostart_restarted =
308        lean_ctx::proxy_autostart::is_installed() && lean_ctx::proxy_autostart::start();
309    match daemon::restore_stopped_proxy(&report, autostart_restarted) {
310        Some(Ok(pid)) => println!("  ✓ Proxy restarted (PID {pid})."),
311        Some(Err(e)) => eprintln!("  Warning: proxy start failed: {e}"),
312        None => {}
313    }
314
315    match daemon::start_daemon(&[]) {
316        Ok(()) => println!("  ✓ Daemon restarted."),
317        Err(e) => {
318            eprintln!("  ✗ Daemon start failed: {e}");
319            std::process::exit(1);
320        }
321    }
322
323    // 3. Safety checks
324    println!("\n[3/4] Running safety checks…");
325    println!("  RAM guard: max {}% system", cfg.max_ram_percent);
326
327    if let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() {
328        let sessions_dir = data_dir.join("sessions");
329        let session_count = std::fs::read_dir(&sessions_dir)
330            .map_or(0, |rd| rd.filter_map(std::result::Result::ok).count());
331        println!("  Sessions dir: {session_count} files");
332    }
333
334    // 4. Summary
335    println!("\n[4/4] Config applied successfully.");
336    println!("  Theme:       {}", cfg.theme);
337    println!("  Ultra compact: {}", cfg.ultra_compact);
338    println!("  Checkpoint:  every {} calls", cfg.checkpoint_interval);
339    if let Some(ref root) = cfg.project_root {
340        println!("  Project root: {root}");
341    }
342}
343
344/// Print the absolute path of the resolved global `config.toml` (one line,
345/// scriptable).
346///
347/// This is the canonical way to verify that the CLI and the MCP server resolve
348/// the *same* config file (GH #594): run `lean-ctx config path` in a terminal
349/// and from the editor's MCP context, then compare. Output is the bare path so
350/// it can be diffed/captured in scripts and tests; it exits non-zero only when
351/// no config directory can be resolved at all.
352fn cmd_config_path() {
353    let Some(p) = config::Config::path() else {
354        eprintln!("Error: cannot resolve a config directory");
355        std::process::exit(1);
356    };
357    println!("{}", p.display());
358}
359
360fn cmd_validate() {
361    // GH #450: always surface *where* the effective settings come from first, so
362    // a "no config" result is never a dead end and a silently shadowed value
363    // (env / project-local / parse error) is immediately visible.
364    print_config_provenance();
365
366    let schema = config::schema::ConfigSchema::generate();
367    let known = schema.known_keys();
368
369    let path = match config::Config::path() {
370        Some(p) if p.exists() => p,
371        Some(p) => {
372            println!("[OK] No config.toml at {} — using defaults.", p.display());
373            return;
374        }
375        None => {
376            println!("[OK] No config dir resolved — using defaults.");
377            return;
378        }
379    };
380
381    let raw = match std::fs::read_to_string(&path) {
382        Ok(s) => s,
383        Err(e) => {
384            eprintln!("[ERROR] Cannot read {}: {e}", path.display());
385            std::process::exit(1);
386        }
387    };
388
389    let table: toml::Table = match raw.parse() {
390        Ok(t) => t,
391        Err(e) => {
392            eprintln!("[ERROR] Invalid TOML: {e}");
393            std::process::exit(1);
394        }
395    };
396
397    let mut warnings = 0u32;
398    let mut validated = 0u32;
399
400    fn collect_keys(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
401        for (k, v) in table {
402            let full = if prefix.is_empty() {
403                k.clone()
404            } else {
405                format!("{prefix}.{k}")
406            };
407            match v {
408                toml::Value::Table(sub) => collect_keys(sub, &full, out),
409                toml::Value::Array(arr) => {
410                    out.push(full.clone());
411                    for item in arr {
412                        if let toml::Value::Table(sub) = item {
413                            for sk in sub.keys() {
414                                out.push(format!("{full}[].{sk}"));
415                            }
416                        }
417                    }
418                }
419                _ => out.push(full),
420            }
421        }
422    }
423
424    let mut user_keys = Vec::new();
425    collect_keys(&table, "", &mut user_keys);
426
427    for uk in &user_keys {
428        let base = uk.split("[].").next().unwrap_or(uk);
429        let field = uk.rsplit("[].").next().unwrap_or("");
430        let check_key = if uk.contains("[].") {
431            format!("{base}.{field}")
432        } else {
433            uk.clone()
434        };
435
436        if known.contains(&check_key)
437            || known
438                .iter()
439                .any(|k| check_key.starts_with(&format!("{k}.")))
440        {
441            validated += 1;
442        } else {
443            warnings += 1;
444            let suggestion = find_closest(&check_key, &known);
445            if let Some(sug) = suggestion {
446                eprintln!("[WARN] Unknown key '{uk}' -- did you mean '{sug}'?");
447            } else {
448                eprintln!("[WARN] Unknown key '{uk}' -- this field does not exist");
449            }
450        }
451    }
452
453    // gh-2283: a known key can still carry a value the loader rejects (e.g. an
454    // enum variant it does not know). The loader then drops the whole file and
455    // runs on defaults, so validation must fail on exactly the same check.
456    let mut unreadable = false;
457    if let Err(e) = config::check_config_document(&raw) {
458        unreadable = true;
459        eprintln!(
460            "[ERROR] The loader cannot read this config, lean-ctx would run on defaults: {e}"
461        );
462    }
463
464    let cfg = config::Config::load();
465    let budget = cfg.max_disk_mb_effective();
466    if budget > 0 {
467        let explicit_archive = cfg.archive.max_disk_mb;
468        let explicit_bm25 = cfg.bm25_max_cache_mb;
469        let sum = explicit_archive + explicit_bm25;
470        if sum > budget {
471            warnings += 1;
472            println!(
473                "  ⚠ max_disk_mb={budget} but archive.max_disk_mb({explicit_archive}) + bm25_max_cache_mb({explicit_bm25}) = {sum} exceeds budget"
474            );
475        }
476    }
477
478    let total = validated + warnings;
479    if unreadable {
480        println!(
481            "[RESULT] {} cannot be loaded: fix the value reported above.",
482            path.display()
483        );
484        std::process::exit(1);
485    }
486    if warnings == 0 {
487        println!(
488            "[OK] All {total} keys validated successfully ({}).",
489            path.display()
490        );
491    } else {
492        println!(
493            "[RESULT] {validated} of {total} keys validated, {warnings} unknown ({}).",
494            path.display()
495        );
496        std::process::exit(1);
497    }
498}
499
500/// Print where the editable settings actually come from (GH #450): the resolved
501/// `config.toml` path, the layout pin, any parse error, and the env /
502/// project-local overrides that can silently shadow a saved value. This makes the
503/// "my quick settings keep resetting" reports self-diagnosing — the reporter sees
504/// the exact mechanism instead of an opaque "no config" message.
505fn print_config_provenance() {
506    let prov = config::Config::provenance();
507
508    println!("Config source:");
509    match &prov.config_path {
510        Some(p) if prov.config_exists => println!("  config.toml:    {} (exists)", p.display()),
511        Some(p) => println!(
512            "  config.toml:    {} (missing — using defaults)",
513            p.display()
514        ),
515        None => println!("  config.toml:    <no config dir resolved — using defaults>"),
516    }
517    println!(
518        "  layout pin:     {}",
519        if prov.xdg_pinned { "xdg" } else { "unpinned" }
520    );
521
522    if let Some(err) = &prov.parse_error {
523        println!("  [!] parse error: config.toml is unparseable — running on DEFAULTS:");
524        println!("                  {err}");
525        println!("                  Run `lean-ctx doctor --fix` to repair.");
526    }
527
528    if prov.local_exists && !prov.local_keys.is_empty() {
529        let path = prov
530            .local_path
531            .as_ref()
532            .map(|p| p.display().to_string())
533            .unwrap_or_default();
534        println!(
535            "  [!] project-local: {path} overrides {}",
536            prov.local_keys.join(", ")
537        );
538        println!("                  (these win over the global config for this project)");
539    }
540
541    if !prov.env_overrides.is_empty() {
542        let list = prov
543            .env_overrides
544            .iter()
545            .map(|e| format!("{} ({})", e.var, e.setting))
546            .collect::<Vec<_>>()
547            .join(", ");
548        println!("  [!] env override: {list}");
549        println!(
550            "                  (these win over config.toml; unset them for saved values to apply)"
551        );
552    }
553
554    if prov.has_shadow() {
555        println!(
556            "  -> A saved setting can appear to \"reset\" because a source above shadows it (GH #450)."
557        );
558    }
559    println!();
560}
561
562/// Closest config key: dotted-path match within distance 3, then a
563/// leaf-segment match within distance 2 (`proxy.prt` → `proxy.port`).
564/// Distances come from the shared [`lean_ctx::core::levenshtein`] helper (#712);
565/// the fixed budgets here predate the shared length-scaled one and are kept —
566/// dotted keys are long, so a length-scaled budget would over-suggest.
567fn find_closest(needle: &str, haystack: &[String]) -> Option<String> {
568    use lean_ctx::core::levenshtein::levenshtein;
569    let mut best: Option<(usize, &str)> = None;
570    for candidate in haystack {
571        let d = levenshtein(needle, candidate);
572        if d <= 3 && best.as_ref().is_none_or(|(best_d, _)| d < *best_d) {
573            best = Some((d, candidate));
574        }
575    }
576    if best.is_some() {
577        return best.map(|(_, s)| s.to_string());
578    }
579    let leaf = needle.rsplit('.').next().unwrap_or(needle);
580    let mut leaf_best: Option<(usize, &str)> = None;
581    for candidate in haystack {
582        let cand_leaf = candidate.rsplit('.').next().unwrap_or(candidate);
583        let d = levenshtein(leaf, cand_leaf);
584        if d <= 2 && leaf_best.as_ref().is_none_or(|(best_d, _)| d < *best_d) {
585            leaf_best = Some((d, candidate));
586        }
587    }
588    leaf_best.map(|(_, s)| s.to_string())
589}
590
591fn normalize_optional_upstream(value: &str) -> Option<String> {
592    use lean_ctx::core::config::normalize_url_opt;
593    let trimmed = value.trim();
594    if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("default") {
595        None
596    } else {
597        normalize_url_opt(trimmed)
598    }
599}
600
601pub fn cmd_benchmark(args: &[String]) {
602    use lean_ctx_ext::core::benchmark;
603
604    let action = args.first().map_or("run", std::string::String::as_str);
605
606    // `benchmark --help` is answered by `benchmark_cmd`, whose help lists
607    // these subcommands as well.
608    match action {
609        "dual-arm" => {
610            let is_json = args.iter().any(|a| a == "--json");
611            let output = parse_flag_value(args, "--output");
612            match lean_ctx_ext::core::scorecard::dual_arm::run_dual_arm() {
613                Ok(sc) => {
614                    let rendered = if is_json { sc.to_json() } else { sc.to_human() };
615                    if let Some(path) = output {
616                        if let Err(e) = std::fs::write(&path, &rendered) {
617                            eprintln!("Failed to write dual-arm scorecard to {path}: {e}");
618                            std::process::exit(1);
619                        }
620                        eprintln!("Wrote dual-arm scorecard to {path}");
621                    } else {
622                        print!("{rendered}");
623                    }
624                }
625                Err(e) => {
626                    eprintln!("Dual-arm bench failed: {e}");
627                    std::process::exit(1);
628                }
629            }
630        }
631        "scorecard" => {
632            let is_json = args.iter().any(|a| a == "--json");
633            let output = parse_flag_value(args, "--output");
634            match lean_ctx_ext::core::scorecard::run_scorecard() {
635                Ok(sc) => {
636                    let rendered = if is_json { sc.to_json() } else { sc.to_human() };
637                    if let Some(path) = output {
638                        if let Err(e) = std::fs::write(&path, &rendered) {
639                            eprintln!("Failed to write scorecard to {path}: {e}");
640                            std::process::exit(1);
641                        }
642                        eprintln!("Wrote scorecard to {path}");
643                    } else {
644                        print!("{rendered}");
645                    }
646                }
647                Err(e) => {
648                    eprintln!("Scorecard failed: {e}");
649                    std::process::exit(1);
650                }
651            }
652        }
653        "run" => {
654            let path = args.get(1).map_or(".", std::string::String::as_str);
655            let is_json = args.iter().any(|a| a == "--json");
656
657            let result = benchmark::run_project_benchmark(path);
658            if is_json {
659                println!("{}", benchmark::format_json(&result));
660            } else {
661                println!("{}", benchmark::format_terminal(&result));
662            }
663        }
664        "report" => {
665            let path = args.get(1).map_or(".", std::string::String::as_str);
666            let result = benchmark::run_project_benchmark(path);
667            println!("{}", benchmark::format_markdown(&result));
668        }
669        _ => {
670            if std::path::Path::new(action).exists() {
671                let result = benchmark::run_project_benchmark(action);
672                println!("{}", benchmark::format_terminal(&result));
673            } else {
674                eprintln!("lean-ctx benchmark: unknown subcommand or path '{action}'");
675                eprintln!(
676                    "Usage: lean-ctx benchmark [--format markdown|json|text] [--output <path>] [--share]\n{}",
677                    super::benchmark_cmd::SUBCOMMAND_USAGE
678                );
679                std::process::exit(2);
680            }
681        }
682    }
683}
684
685fn parse_flag_value(args: &[String], flag: &str) -> Option<String> {
686    args.iter()
687        .position(|a| a == flag)
688        .and_then(|i| args.get(i + 1))
689        .cloned()
690}
691
692fn load_mcp_live_stats() -> Option<serde_json::Value> {
693    let path = lean_ctx::core::paths::state_dir()
694        .ok()?
695        .join("mcp-live.json");
696    let content = std::fs::read_to_string(path).ok()?;
697    serde_json::from_str(&content).ok()
698}
699
700fn stats_json_value(
701    store: &lean_ctx::core::stats::StatsStore,
702    mcp_cache: Option<serde_json::Value>,
703) -> serde_json::Value {
704    let mut value = serde_json::to_value(store).unwrap_or_else(|_| serde_json::json!({}));
705    if let (Some(object), Some(mcp_cache)) = (value.as_object_mut(), mcp_cache) {
706        object.insert("mcp_cache".to_string(), mcp_cache);
707    }
708    value
709}
710
711fn mcp_cache_stats_lines(value: &serde_json::Value) -> Vec<String> {
712    let metric = |key| {
713        value
714            .get(key)
715            .and_then(serde_json::Value::as_u64)
716            .unwrap_or(0)
717    };
718    let mcp_reads = metric("total_reads");
719    let mcp_hits = metric("cache_hits");
720    let mcp_rate = if mcp_reads > 0 {
721        (mcp_hits as f64 / mcp_reads as f64 * 100.0).round() as u32
722    } else {
723        0
724    };
725    let updated = value
726        .get("updated_at")
727        .and_then(serde_json::Value::as_str)
728        .unwrap_or("unknown");
729    let mut lines = vec![
730        "MCP Session Cache (ctx_read via AI editor):".to_string(),
731        format!("  Reads:         {mcp_reads}"),
732        format!("  Hits:          {mcp_hits}"),
733        format!("  Hit Rate:      {mcp_rate}%"),
734        format!("  Tokens Saved:  {}", metric("tokens_saved")),
735        format!("  Last Updated:  {updated}"),
736    ];
737
738    let dedup_reads = metric("dedup_reads");
739    if dedup_reads > 0 {
740        let dedup_hits = metric("dedup_hits");
741        let dedup_rate = dedup_hits as f64 / dedup_reads as f64 * 100.0;
742        lines.extend([
743            String::new(),
744            "Content Dedup (repeated ctx_read output):".to_string(),
745            format!("  Reads Checked: {dedup_reads}"),
746            format!("  Hits:          {dedup_hits}"),
747            format!("  Hit Rate:      {dedup_rate:.1}%"),
748            format!("  Tokens Saved:  {}", metric("dedup_tokens_saved")),
749        ]);
750    }
751
752    lines
753}
754
755pub fn cmd_stats(args: &[String]) {
756    match args.first().map(std::string::String::as_str) {
757        Some("reset-cep") => {
758            lean_ctx::core::stats::reset_cep();
759            println!("CEP stats reset. Shell hook data preserved.");
760        }
761        Some("json") => {
762            let store = lean_ctx::core::stats::load();
763            let value = stats_json_value(&store, load_mcp_live_stats());
764            println!(
765                "{}",
766                serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
767            );
768        }
769        _ => {
770            let store = lean_ctx::core::stats::load();
771            let input_saved = store
772                .total_input_tokens
773                .saturating_sub(store.total_output_tokens);
774            let pct = if store.total_input_tokens > 0 {
775                input_saved as f64 / store.total_input_tokens as f64 * 100.0
776            } else {
777                0.0
778            };
779            println!("Commands:    {}", store.total_commands);
780            println!("Input:       {} tokens", store.total_input_tokens);
781            println!("Output:      {} tokens", store.total_output_tokens);
782            // #1284: scope the headline honestly — this ratio covers volume
783            // that flowed THROUGH lean-ctx. Native tool calls that bypassed
784            // lean-ctx are not in the denominator (they are counted separately
785            // as native_shell_passthrough in metering).
786            println!("Saved:       {input_saved} tokens ({pct:.1}% of metered lean-ctx volume)");
787            println!();
788            println!("CEP sessions:  {}", store.cep.sessions);
789            println!(
790                "CEP tokens:    {} → {}",
791                store.cep.total_tokens_original, store.cep.total_tokens_compressed
792            );
793            println!();
794            println!("Subcommands: stats reset-cep | stats json");
795        }
796    }
797}
798
799pub struct PruneResult {
800    pub scanned: u32,
801    pub removed: u32,
802    pub failed: u32,
803    pub bytes_freed: u64,
804}
805
806fn record_removed_file(result: &mut PruneResult, path: &std::path::Path, label: &str) {
807    let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
808
809    match std::fs::remove_file(path) {
810        Ok(()) => {
811            result.bytes_freed += bytes;
812            result.removed += 1;
813            println!("  {label}: {}", path.display());
814        }
815        Err(error) => {
816            result.failed += 1;
817            eprintln!("  Failed to remove {}: {error}", path.display());
818        }
819    }
820}
821
822fn record_removed_dir(
823    result: &mut PruneResult,
824    path: &std::path::Path,
825    bytes: u64,
826    message: impl FnOnce() -> String,
827) {
828    match std::fs::remove_dir_all(path) {
829        Ok(()) => {
830            result.bytes_freed += bytes;
831            result.removed += 1;
832            println!("  {}", message());
833        }
834        Err(error) => {
835            result.failed += 1;
836            eprintln!("  Failed to remove {}: {error}", path.display());
837        }
838    }
839}
840
841/// Files a local (per-checkout) index writes into its directory. Anything
842/// else there, such as `hosted-v2/`, is not the local index's to delete.
843const LOCAL_INDEX_FILES: &[&str] = &[
844    "bm25_index.bin.zst",
845    "bm25_index.bin",
846    "bm25_index.json",
847    "embeddings.json",
848    "embeddings.bin",
849    "bm25_provider_origins.json",
850    "project_root.txt",
851];
852
853pub fn prune_bm25_caches() -> PruneResult {
854    let mut result = PruneResult {
855        scanned: 0,
856        removed: 0,
857        failed: 0,
858        bytes_freed: 0,
859    };
860
861    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
862        return result;
863    };
864    let vectors_dir = data_dir.join("vectors");
865    let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
866        return result;
867    };
868
869    let max_bytes =
870        lean_ctx::core::config::Config::load().bm25_max_cache_mb_effective() * 1024 * 1024;
871
872    for entry in entries.flatten() {
873        let dir = entry.path();
874        if !dir.is_dir() {
875            continue;
876        }
877        result.scanned += 1;
878
879        for q_name in &[
880            "bm25_index.json.quarantined",
881            "bm25_index.bin.quarantined",
882            "bm25_index.bin.zst.quarantined",
883        ] {
884            let quarantined = dir.join(q_name);
885            if quarantined.exists() {
886                record_removed_file(&mut result, &quarantined, "Removed quarantined");
887            }
888        }
889
890        let index_path = if dir.join("bm25_index.bin.zst").exists() {
891            dir.join("bm25_index.bin.zst")
892        } else if dir.join("bm25_index.bin").exists() {
893            dir.join("bm25_index.bin")
894        } else {
895            dir.join("bm25_index.json")
896        };
897        if let Ok(meta) = std::fs::metadata(&index_path)
898            && meta.len() > max_bytes
899        {
900            record_removed_file(&mut result, &index_path, "Removed oversized");
901        }
902
903        let marker = dir.join("project_root.txt");
904        if let Ok(root_str) = std::fs::read_to_string(&marker) {
905            let root_path = std::path::Path::new(root_str.trim());
906            if !root_path.exists() && dir.join("hosted-v2").exists() {
907                // The namespace directory also holds the hosted index of
908                // every checkout of this repository: only the local index
909                // files of the gone checkout go.
910                for name in LOCAL_INDEX_FILES {
911                    let file = dir.join(name);
912                    if file.exists() {
913                        record_removed_file(&mut result, &file, "Removed orphaned");
914                    }
915                }
916            } else if !root_path.exists() {
917                let freed = dir_size(&dir);
918                record_removed_dir(&mut result, &dir, freed, || {
919                    format!(
920                        "Removed orphaned ({:.1} MB, project gone: {}): {}",
921                        freed as f64 / 1_048_576.0,
922                        root_str.trim(),
923                        dir.display()
924                    )
925                });
926            }
927        }
928    }
929
930    result
931}
932
933pub fn prune_graph_caches() -> PruneResult {
934    let mut result = PruneResult {
935        scanned: 0,
936        removed: 0,
937        failed: 0,
938        bytes_freed: 0,
939    };
940
941    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
942        return result;
943    };
944    let graphs_dir = data_dir.join("graphs");
945    let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
946        return result;
947    };
948
949    for entry in entries.flatten() {
950        let dir = entry.path();
951        if !dir.is_dir() {
952            continue;
953        }
954        result.scanned += 1;
955
956        // #696 C4: the property graph (graph.db + graph.meta.json) is the sole
957        // store. The meta carries the absolute project root, so an orphaned
958        // `graphs/<hash>/` dir (project deleted) can still be pruned.
959        let meta_file = dir.join("graph.meta.json");
960        let db_file = dir.join("graph.db");
961        if !meta_file.exists() && !db_file.exists() {
962            continue;
963        }
964
965        let root_from_meta = try_read_project_root_from_graph(&meta_file);
966        if let Some(root) = root_from_meta
967            && !root.is_empty()
968            && !std::path::Path::new(&root).exists()
969        {
970            let freed = dir_size(&dir);
971            record_removed_dir(&mut result, &dir, freed, || {
972                format!(
973                    "Removed orphaned graph ({:.1} MB, project gone: {}): {}",
974                    freed as f64 / 1_048_576.0,
975                    root,
976                    dir.display()
977                )
978            });
979            continue;
980        }
981
982        // Oversized guard: a pathologically large (e.g. corrupt) graph store is
983        // dropped so the next query rebuilds it cleanly — a rebuild cost, not
984        // data loss.
985        if let Ok(meta) = std::fs::metadata(&db_file)
986            && meta.len() > 100 * 1024 * 1024
987        {
988            let freed = dir_size(&dir);
989            record_removed_dir(&mut result, &dir, freed, || {
990                format!(
991                    "Removed oversized graph ({:.1} MB): {}",
992                    freed as f64 / 1_048_576.0,
993                    dir.display()
994                )
995            });
996        }
997    }
998
999    result
1000}
1001
1002/// Read the absolute project root recorded in a `graph.meta.json` file, if
1003/// present (#696 C4 — replaces reading it from the retired JSON index).
1004fn try_read_project_root_from_graph(path: &std::path::Path) -> Option<String> {
1005    let content = std::fs::read_to_string(path).ok()?;
1006    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1007    val.get("project_root")?.as_str().map(String::from)
1008}
1009
1010/// Create the simplified config. An existing one is never replaced: the
1011/// template would reset every setting the person tightened.
1012fn write_simplified_config() -> Result<String, String> {
1013    use std::io::Write as _;
1014    let path = config::Config::path().ok_or_else(|| "Cannot determine config path".to_string())?;
1015    if let Some(dir) = path.parent() {
1016        std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
1017    }
1018    let mut file = std::fs::OpenOptions::new()
1019        .write(true)
1020        .create_new(true)
1021        .open(&path)
1022        .map_err(|e| {
1023            if e.kind() == std::io::ErrorKind::AlreadyExists {
1024                format!(
1025                    "{} exists and stays as it is; `lean-ctx config init --full` merges into it, `lean-ctx config set` changes one key",
1026                    path.display()
1027                )
1028            } else {
1029                format!("{e}")
1030            }
1031        })?;
1032    file.write_all(config::SIMPLIFIED_TEMPLATE.as_bytes())
1033        .map_err(|e| format!("{e}"))?;
1034    Ok(path.to_string_lossy().to_string())
1035}
1036
1037fn cmd_show_effective() {
1038    let cfg = config::Config::load();
1039    let compression = config::CompressionLevel::effective(&cfg);
1040    let policy = cfg.memory_policy_effective().unwrap_or_default();
1041
1042    println!("{}", box_top("Simplified (high-level)"));
1043    box_row(&format!(
1044        " compression_level   = {:10}  {}",
1045        format!("{compression:?}"),
1046        source_hint(
1047            "LEAN_CTX_COMPRESSION",
1048            cfg.compression_level != config::CompressionLevel::Off
1049        )
1050    ));
1051    box_row(&format!(
1052        " max_disk_mb         = {:10}  {}",
1053        cfg.max_disk_mb_effective(),
1054        source_hint("LEAN_CTX_MAX_DISK_MB", cfg.max_disk_mb > 0)
1055    ));
1056    box_row(&format!(
1057        " max_ram_percent     = {:10}  {}",
1058        cfg.max_ram_percent,
1059        source_hint("LEAN_CTX_MAX_RAM_PERCENT", cfg.max_ram_percent != 5)
1060    ));
1061    box_row(&format!(
1062        " mcp_max_rss_mb      = {:10}  {}",
1063        cfg.mcp_max_rss_mb_effective(),
1064        source_hint("LEAN_CTX_MCP_MAX_RSS_MB", cfg.mcp_max_rss_mb != 512)
1065    ));
1066    box_row(&format!(
1067        " daemon_max_rss_mb   = {:10}  {}",
1068        cfg.daemon_max_rss_mb_effective(),
1069        source_hint("LEAN_CTX_DAEMON_MAX_RSS_MB", cfg.daemon_max_rss_mb != 2048)
1070    ));
1071    box_row(&format!(
1072        " mcp_idle_exit_minutes = {:8}  {}",
1073        cfg.mcp_idle_exit_minutes_effective(),
1074        source_hint(
1075            "LEAN_CTX_MCP_IDLE_EXIT_MINUTES",
1076            cfg.mcp_idle_exit_minutes > 0
1077        )
1078    ));
1079    box_row(&format!(
1080        " session_retention_days = {:8}  {}",
1081        cfg.session_retention_days_effective(),
1082        source_hint(
1083            "LEAN_CTX_SESSION_RETENTION_DAYS",
1084            cfg.session_retention_days != 7
1085        )
1086    ));
1087    box_row(&format!(
1088        " max_staleness_days  = {:10}  {}",
1089        cfg.max_staleness_days_effective(),
1090        source_hint("LEAN_CTX_MAX_STALENESS_DAYS", cfg.max_staleness_days > 0)
1091    ));
1092    box_row(&format!(
1093        " memory_profile      = {:10}  {}",
1094        format!("{:?}", cfg.memory_profile),
1095        source_hint("LEAN_CTX_MEMORY_PROFILE", false)
1096    ));
1097    println!("{}", box_bottom());
1098
1099    println!();
1100    println!("{}", box_top("Derived effective limits"));
1101    box_row(&format!(
1102        " archive_max_disk_mb    = {:>6} MB",
1103        cfg.archive_max_disk_mb_effective()
1104    ));
1105    box_row(&format!(
1106        " bm25_max_cache_mb      = {:>6} MB",
1107        cfg.bm25_max_cache_mb_effective()
1108    ));
1109    box_row(&format!(
1110        " archive_max_age_hours  = {:>6} h",
1111        cfg.archive_max_age_hours_effective()
1112    ));
1113    box_row(&format!(
1114        " graph_index_max_files  = {:>6}",
1115        cfg.graph_index_max_files
1116    ));
1117    box_row("");
1118    box_row(" memory.knowledge facts         = no limit");
1119    box_row(&format!(
1120        " memory.knowledge.max_patterns  = {:>6}",
1121        policy.knowledge.max_patterns
1122    ));
1123    println!("{}", box_bottom());
1124
1125    if cfg.max_disk_mb_effective() > 0 {
1126        println!();
1127        println!(
1128            "  ℹ  max_disk_mb={} → limits scaled proportionally (factor: {:.1}x)",
1129            cfg.max_disk_mb_effective(),
1130            (cfg.max_disk_mb_effective() as f64 / 500.0).clamp(0.5, 10.0)
1131        );
1132    }
1133}
1134
1135/// Interior width of the `config show` frames, in terminal columns.
1136const SHOW_BOX_W: usize = 60;
1137
1138/// `╭─── Label ───…───╮`, always `SHOW_BOX_W` columns wide inside the corners.
1139fn box_top(label: &str) -> String {
1140    let head = format!("─── {label} ");
1141    let fill = SHOW_BOX_W.saturating_sub(lean_ctx::core::theme::visual_len(&head));
1142    format!("╭{head}{}╮", "─".repeat(fill))
1143}
1144
1145fn box_bottom() -> String {
1146    format!("╰{}╯", "─".repeat(SHOW_BOX_W))
1147}
1148
1149/// Print one framed row, padded (or truncated) to the frame's interior width so
1150/// the right border lines up regardless of the value's length.
1151fn box_row(content: &str) {
1152    println!(
1153        "│{}│",
1154        lean_ctx::core::theme::pad_right(content, SHOW_BOX_W)
1155    );
1156}
1157
1158fn source_hint(env_var: &str, config_set: bool) -> &'static str {
1159    if std::env::var(env_var).is_ok() {
1160        "← env"
1161    } else if config_set {
1162        "← config"
1163    } else {
1164        "← default"
1165    }
1166}
1167
1168fn dir_size(path: &std::path::Path) -> u64 {
1169    let mut total = 0u64;
1170    if let Ok(entries) = std::fs::read_dir(path) {
1171        for entry in entries.flatten() {
1172            let p = entry.path();
1173            if p.is_file() {
1174                total += std::fs::metadata(&p).map_or(0, |m| m.len());
1175            } else if p.is_dir() {
1176                total += dir_size(&p);
1177            }
1178        }
1179    }
1180    total
1181}
1182
1183#[cfg(test)]
1184mod tests;