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    let cfg = config::Config::load();
454    let budget = cfg.max_disk_mb_effective();
455    if budget > 0 {
456        let explicit_archive = cfg.archive.max_disk_mb;
457        let explicit_bm25 = cfg.bm25_max_cache_mb;
458        let sum = explicit_archive + explicit_bm25;
459        if sum > budget {
460            warnings += 1;
461            println!(
462                "  ⚠ max_disk_mb={budget} but archive.max_disk_mb({explicit_archive}) + bm25_max_cache_mb({explicit_bm25}) = {sum} exceeds budget"
463            );
464        }
465    }
466
467    let total = validated + warnings;
468    if warnings == 0 {
469        println!(
470            "[OK] All {total} keys validated successfully ({}).",
471            path.display()
472        );
473    } else {
474        println!(
475            "[RESULT] {validated} of {total} keys validated, {warnings} unknown ({}).",
476            path.display()
477        );
478        std::process::exit(1);
479    }
480}
481
482/// Print where the editable settings actually come from (GH #450): the resolved
483/// `config.toml` path, the layout pin, any parse error, and the env /
484/// project-local overrides that can silently shadow a saved value. This makes the
485/// "my quick settings keep resetting" reports self-diagnosing — the reporter sees
486/// the exact mechanism instead of an opaque "no config" message.
487fn print_config_provenance() {
488    let prov = config::Config::provenance();
489
490    println!("Config source:");
491    match &prov.config_path {
492        Some(p) if prov.config_exists => println!("  config.toml:    {} (exists)", p.display()),
493        Some(p) => println!(
494            "  config.toml:    {} (missing — using defaults)",
495            p.display()
496        ),
497        None => println!("  config.toml:    <no config dir resolved — using defaults>"),
498    }
499    println!(
500        "  layout pin:     {}",
501        if prov.xdg_pinned { "xdg" } else { "unpinned" }
502    );
503
504    if let Some(err) = &prov.parse_error {
505        println!("  [!] parse error: config.toml is unparseable — running on DEFAULTS:");
506        println!("                  {err}");
507        println!("                  Run `lean-ctx doctor --fix` to repair.");
508    }
509
510    if prov.local_exists && !prov.local_keys.is_empty() {
511        let path = prov
512            .local_path
513            .as_ref()
514            .map(|p| p.display().to_string())
515            .unwrap_or_default();
516        println!(
517            "  [!] project-local: {path} overrides {}",
518            prov.local_keys.join(", ")
519        );
520        println!("                  (these win over the global config for this project)");
521    }
522
523    if !prov.env_overrides.is_empty() {
524        let list = prov
525            .env_overrides
526            .iter()
527            .map(|e| format!("{} ({})", e.var, e.setting))
528            .collect::<Vec<_>>()
529            .join(", ");
530        println!("  [!] env override: {list}");
531        println!(
532            "                  (these win over config.toml; unset them for saved values to apply)"
533        );
534    }
535
536    if prov.has_shadow() {
537        println!(
538            "  -> A saved setting can appear to \"reset\" because a source above shadows it (GH #450)."
539        );
540    }
541    println!();
542}
543
544/// Closest config key: dotted-path match within distance 3, then a
545/// leaf-segment match within distance 2 (`proxy.prt` → `proxy.port`).
546/// Distances come from the shared [`lean_ctx::core::levenshtein`] helper (#712);
547/// the fixed budgets here predate the shared length-scaled one and are kept —
548/// dotted keys are long, so a length-scaled budget would over-suggest.
549fn find_closest(needle: &str, haystack: &[String]) -> Option<String> {
550    use lean_ctx::core::levenshtein::levenshtein;
551    let mut best: Option<(usize, &str)> = None;
552    for candidate in haystack {
553        let d = levenshtein(needle, candidate);
554        if d <= 3 && best.as_ref().is_none_or(|(best_d, _)| d < *best_d) {
555            best = Some((d, candidate));
556        }
557    }
558    if best.is_some() {
559        return best.map(|(_, s)| s.to_string());
560    }
561    let leaf = needle.rsplit('.').next().unwrap_or(needle);
562    let mut leaf_best: Option<(usize, &str)> = None;
563    for candidate in haystack {
564        let cand_leaf = candidate.rsplit('.').next().unwrap_or(candidate);
565        let d = levenshtein(leaf, cand_leaf);
566        if d <= 2 && leaf_best.as_ref().is_none_or(|(best_d, _)| d < *best_d) {
567            leaf_best = Some((d, candidate));
568        }
569    }
570    leaf_best.map(|(_, s)| s.to_string())
571}
572
573fn normalize_optional_upstream(value: &str) -> Option<String> {
574    use lean_ctx::core::config::normalize_url_opt;
575    let trimmed = value.trim();
576    if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("default") {
577        None
578    } else {
579        normalize_url_opt(trimmed)
580    }
581}
582
583pub fn cmd_benchmark(args: &[String]) {
584    use lean_ctx::core::benchmark;
585
586    let action = args.first().map_or("run", std::string::String::as_str);
587
588    // `benchmark --help` is answered by `benchmark_cmd`, whose help lists
589    // these subcommands as well.
590    match action {
591        "dual-arm" => {
592            let is_json = args.iter().any(|a| a == "--json");
593            let output = parse_flag_value(args, "--output");
594            match lean_ctx::core::scorecard::dual_arm::run_dual_arm() {
595                Ok(sc) => {
596                    let rendered = if is_json { sc.to_json() } else { sc.to_human() };
597                    if let Some(path) = output {
598                        if let Err(e) = std::fs::write(&path, &rendered) {
599                            eprintln!("Failed to write dual-arm scorecard to {path}: {e}");
600                            std::process::exit(1);
601                        }
602                        eprintln!("Wrote dual-arm scorecard to {path}");
603                    } else {
604                        print!("{rendered}");
605                    }
606                }
607                Err(e) => {
608                    eprintln!("Dual-arm bench failed: {e}");
609                    std::process::exit(1);
610                }
611            }
612        }
613        "scorecard" => {
614            let is_json = args.iter().any(|a| a == "--json");
615            let output = parse_flag_value(args, "--output");
616            match lean_ctx::core::scorecard::run_scorecard() {
617                Ok(sc) => {
618                    let rendered = if is_json { sc.to_json() } else { sc.to_human() };
619                    if let Some(path) = output {
620                        if let Err(e) = std::fs::write(&path, &rendered) {
621                            eprintln!("Failed to write scorecard to {path}: {e}");
622                            std::process::exit(1);
623                        }
624                        eprintln!("Wrote scorecard to {path}");
625                    } else {
626                        print!("{rendered}");
627                    }
628                }
629                Err(e) => {
630                    eprintln!("Scorecard failed: {e}");
631                    std::process::exit(1);
632                }
633            }
634        }
635        "run" => {
636            let path = args.get(1).map_or(".", std::string::String::as_str);
637            let is_json = args.iter().any(|a| a == "--json");
638
639            let result = benchmark::run_project_benchmark(path);
640            if is_json {
641                println!("{}", benchmark::format_json(&result));
642            } else {
643                println!("{}", benchmark::format_terminal(&result));
644            }
645        }
646        "report" => {
647            let path = args.get(1).map_or(".", std::string::String::as_str);
648            let result = benchmark::run_project_benchmark(path);
649            println!("{}", benchmark::format_markdown(&result));
650        }
651        _ => {
652            if std::path::Path::new(action).exists() {
653                let result = benchmark::run_project_benchmark(action);
654                println!("{}", benchmark::format_terminal(&result));
655            } else {
656                eprintln!("lean-ctx benchmark: unknown subcommand or path '{action}'");
657                eprintln!(
658                    "Usage: lean-ctx benchmark [--format markdown|json|text] [--output <path>] [--share]\n{}",
659                    super::benchmark_cmd::SUBCOMMAND_USAGE
660                );
661                std::process::exit(2);
662            }
663        }
664    }
665}
666
667fn parse_flag_value(args: &[String], flag: &str) -> Option<String> {
668    args.iter()
669        .position(|a| a == flag)
670        .and_then(|i| args.get(i + 1))
671        .cloned()
672}
673
674fn load_mcp_live_stats() -> Option<serde_json::Value> {
675    let path = lean_ctx::core::paths::state_dir()
676        .ok()?
677        .join("mcp-live.json");
678    let content = std::fs::read_to_string(path).ok()?;
679    serde_json::from_str(&content).ok()
680}
681
682fn stats_json_value(
683    store: &lean_ctx::core::stats::StatsStore,
684    mcp_cache: Option<serde_json::Value>,
685) -> serde_json::Value {
686    let mut value = serde_json::to_value(store).unwrap_or_else(|_| serde_json::json!({}));
687    if let (Some(object), Some(mcp_cache)) = (value.as_object_mut(), mcp_cache) {
688        object.insert("mcp_cache".to_string(), mcp_cache);
689    }
690    value
691}
692
693fn mcp_cache_stats_lines(value: &serde_json::Value) -> Vec<String> {
694    let metric = |key| {
695        value
696            .get(key)
697            .and_then(serde_json::Value::as_u64)
698            .unwrap_or(0)
699    };
700    let mcp_reads = metric("total_reads");
701    let mcp_hits = metric("cache_hits");
702    let mcp_rate = if mcp_reads > 0 {
703        (mcp_hits as f64 / mcp_reads as f64 * 100.0).round() as u32
704    } else {
705        0
706    };
707    let updated = value
708        .get("updated_at")
709        .and_then(serde_json::Value::as_str)
710        .unwrap_or("unknown");
711    let mut lines = vec![
712        "MCP Session Cache (ctx_read via AI editor):".to_string(),
713        format!("  Reads:         {mcp_reads}"),
714        format!("  Hits:          {mcp_hits}"),
715        format!("  Hit Rate:      {mcp_rate}%"),
716        format!("  Tokens Saved:  {}", metric("tokens_saved")),
717        format!("  Last Updated:  {updated}"),
718    ];
719
720    let dedup_reads = metric("dedup_reads");
721    if dedup_reads > 0 {
722        let dedup_hits = metric("dedup_hits");
723        let dedup_rate = dedup_hits as f64 / dedup_reads as f64 * 100.0;
724        lines.extend([
725            String::new(),
726            "Content Dedup (repeated ctx_read output):".to_string(),
727            format!("  Reads Checked: {dedup_reads}"),
728            format!("  Hits:          {dedup_hits}"),
729            format!("  Hit Rate:      {dedup_rate:.1}%"),
730            format!("  Tokens Saved:  {}", metric("dedup_tokens_saved")),
731        ]);
732    }
733
734    lines
735}
736
737pub fn cmd_stats(args: &[String]) {
738    match args.first().map(std::string::String::as_str) {
739        Some("reset-cep") => {
740            lean_ctx::core::stats::reset_cep();
741            println!("CEP stats reset. Shell hook data preserved.");
742        }
743        Some("json") => {
744            let store = lean_ctx::core::stats::load();
745            let value = stats_json_value(&store, load_mcp_live_stats());
746            println!(
747                "{}",
748                serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
749            );
750        }
751        _ => {
752            let store = lean_ctx::core::stats::load();
753            let input_saved = store
754                .total_input_tokens
755                .saturating_sub(store.total_output_tokens);
756            let pct = if store.total_input_tokens > 0 {
757                input_saved as f64 / store.total_input_tokens as f64 * 100.0
758            } else {
759                0.0
760            };
761            println!("Commands:    {}", store.total_commands);
762            println!("Input:       {} tokens", store.total_input_tokens);
763            println!("Output:      {} tokens", store.total_output_tokens);
764            // #1284: scope the headline honestly — this ratio covers volume
765            // that flowed THROUGH lean-ctx. Native tool calls that bypassed
766            // lean-ctx are not in the denominator (they are counted separately
767            // as native_shell_passthrough in metering).
768            println!("Saved:       {input_saved} tokens ({pct:.1}% of metered lean-ctx volume)");
769            println!();
770            println!("CEP sessions:  {}", store.cep.sessions);
771            println!(
772                "CEP tokens:    {} → {}",
773                store.cep.total_tokens_original, store.cep.total_tokens_compressed
774            );
775            println!();
776            println!("Subcommands: stats reset-cep | stats json");
777        }
778    }
779}
780
781pub struct PruneResult {
782    pub scanned: u32,
783    pub removed: u32,
784    pub failed: u32,
785    pub bytes_freed: u64,
786}
787
788fn record_removed_file(result: &mut PruneResult, path: &std::path::Path, label: &str) {
789    let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
790
791    match std::fs::remove_file(path) {
792        Ok(()) => {
793            result.bytes_freed += bytes;
794            result.removed += 1;
795            println!("  {label}: {}", path.display());
796        }
797        Err(error) => {
798            result.failed += 1;
799            eprintln!("  Failed to remove {}: {error}", path.display());
800        }
801    }
802}
803
804fn record_removed_dir(
805    result: &mut PruneResult,
806    path: &std::path::Path,
807    bytes: u64,
808    message: impl FnOnce() -> String,
809) {
810    match std::fs::remove_dir_all(path) {
811        Ok(()) => {
812            result.bytes_freed += bytes;
813            result.removed += 1;
814            println!("  {}", message());
815        }
816        Err(error) => {
817            result.failed += 1;
818            eprintln!("  Failed to remove {}: {error}", path.display());
819        }
820    }
821}
822
823/// Files a local (per-checkout) index writes into its directory. Anything
824/// else there, such as `hosted-v2/`, is not the local index's to delete.
825const LOCAL_INDEX_FILES: &[&str] = &[
826    "bm25_index.bin.zst",
827    "bm25_index.bin",
828    "bm25_index.json",
829    "embeddings.json",
830    "embeddings.bin",
831    "bm25_provider_origins.json",
832    "project_root.txt",
833];
834
835pub fn prune_bm25_caches() -> PruneResult {
836    let mut result = PruneResult {
837        scanned: 0,
838        removed: 0,
839        failed: 0,
840        bytes_freed: 0,
841    };
842
843    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
844        return result;
845    };
846    let vectors_dir = data_dir.join("vectors");
847    let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
848        return result;
849    };
850
851    let max_bytes =
852        lean_ctx::core::config::Config::load().bm25_max_cache_mb_effective() * 1024 * 1024;
853
854    for entry in entries.flatten() {
855        let dir = entry.path();
856        if !dir.is_dir() {
857            continue;
858        }
859        result.scanned += 1;
860
861        for q_name in &[
862            "bm25_index.json.quarantined",
863            "bm25_index.bin.quarantined",
864            "bm25_index.bin.zst.quarantined",
865        ] {
866            let quarantined = dir.join(q_name);
867            if quarantined.exists() {
868                record_removed_file(&mut result, &quarantined, "Removed quarantined");
869            }
870        }
871
872        let index_path = if dir.join("bm25_index.bin.zst").exists() {
873            dir.join("bm25_index.bin.zst")
874        } else if dir.join("bm25_index.bin").exists() {
875            dir.join("bm25_index.bin")
876        } else {
877            dir.join("bm25_index.json")
878        };
879        if let Ok(meta) = std::fs::metadata(&index_path)
880            && meta.len() > max_bytes
881        {
882            record_removed_file(&mut result, &index_path, "Removed oversized");
883        }
884
885        let marker = dir.join("project_root.txt");
886        if let Ok(root_str) = std::fs::read_to_string(&marker) {
887            let root_path = std::path::Path::new(root_str.trim());
888            if !root_path.exists() && dir.join("hosted-v2").exists() {
889                // The namespace directory also holds the hosted index of
890                // every checkout of this repository: only the local index
891                // files of the gone checkout go.
892                for name in LOCAL_INDEX_FILES {
893                    let file = dir.join(name);
894                    if file.exists() {
895                        record_removed_file(&mut result, &file, "Removed orphaned");
896                    }
897                }
898            } else if !root_path.exists() {
899                let freed = dir_size(&dir);
900                record_removed_dir(&mut result, &dir, freed, || {
901                    format!(
902                        "Removed orphaned ({:.1} MB, project gone: {}): {}",
903                        freed as f64 / 1_048_576.0,
904                        root_str.trim(),
905                        dir.display()
906                    )
907                });
908            }
909        }
910    }
911
912    result
913}
914
915pub fn prune_graph_caches() -> PruneResult {
916    let mut result = PruneResult {
917        scanned: 0,
918        removed: 0,
919        failed: 0,
920        bytes_freed: 0,
921    };
922
923    let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() else {
924        return result;
925    };
926    let graphs_dir = data_dir.join("graphs");
927    let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
928        return result;
929    };
930
931    for entry in entries.flatten() {
932        let dir = entry.path();
933        if !dir.is_dir() {
934            continue;
935        }
936        result.scanned += 1;
937
938        // #696 C4: the property graph (graph.db + graph.meta.json) is the sole
939        // store. The meta carries the absolute project root, so an orphaned
940        // `graphs/<hash>/` dir (project deleted) can still be pruned.
941        let meta_file = dir.join("graph.meta.json");
942        let db_file = dir.join("graph.db");
943        if !meta_file.exists() && !db_file.exists() {
944            continue;
945        }
946
947        let root_from_meta = try_read_project_root_from_graph(&meta_file);
948        if let Some(root) = root_from_meta
949            && !root.is_empty()
950            && !std::path::Path::new(&root).exists()
951        {
952            let freed = dir_size(&dir);
953            record_removed_dir(&mut result, &dir, freed, || {
954                format!(
955                    "Removed orphaned graph ({:.1} MB, project gone: {}): {}",
956                    freed as f64 / 1_048_576.0,
957                    root,
958                    dir.display()
959                )
960            });
961            continue;
962        }
963
964        // Oversized guard: a pathologically large (e.g. corrupt) graph store is
965        // dropped so the next query rebuilds it cleanly — a rebuild cost, not
966        // data loss.
967        if let Ok(meta) = std::fs::metadata(&db_file)
968            && meta.len() > 100 * 1024 * 1024
969        {
970            let freed = dir_size(&dir);
971            record_removed_dir(&mut result, &dir, freed, || {
972                format!(
973                    "Removed oversized graph ({:.1} MB): {}",
974                    freed as f64 / 1_048_576.0,
975                    dir.display()
976                )
977            });
978        }
979    }
980
981    result
982}
983
984/// Read the absolute project root recorded in a `graph.meta.json` file, if
985/// present (#696 C4 — replaces reading it from the retired JSON index).
986fn try_read_project_root_from_graph(path: &std::path::Path) -> Option<String> {
987    let content = std::fs::read_to_string(path).ok()?;
988    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
989    val.get("project_root")?.as_str().map(String::from)
990}
991
992/// Create the simplified config. An existing one is never replaced: the
993/// template would reset every setting the person tightened.
994fn write_simplified_config() -> Result<String, String> {
995    use std::io::Write as _;
996    let path = config::Config::path().ok_or_else(|| "Cannot determine config path".to_string())?;
997    if let Some(dir) = path.parent() {
998        std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
999    }
1000    let mut file = std::fs::OpenOptions::new()
1001        .write(true)
1002        .create_new(true)
1003        .open(&path)
1004        .map_err(|e| {
1005            if e.kind() == std::io::ErrorKind::AlreadyExists {
1006                format!(
1007                    "{} exists and stays as it is; `lean-ctx config init --full` merges into it, `lean-ctx config set` changes one key",
1008                    path.display()
1009                )
1010            } else {
1011                format!("{e}")
1012            }
1013        })?;
1014    file.write_all(config::SIMPLIFIED_TEMPLATE.as_bytes())
1015        .map_err(|e| format!("{e}"))?;
1016    Ok(path.to_string_lossy().to_string())
1017}
1018
1019fn cmd_show_effective() {
1020    let cfg = config::Config::load();
1021    let compression = config::CompressionLevel::effective(&cfg);
1022    let policy = cfg.memory_policy_effective().unwrap_or_default();
1023
1024    println!("{}", box_top("Simplified (high-level)"));
1025    box_row(&format!(
1026        " compression_level   = {:10}  {}",
1027        format!("{compression:?}"),
1028        source_hint(
1029            "LEAN_CTX_COMPRESSION",
1030            cfg.compression_level != config::CompressionLevel::Off
1031        )
1032    ));
1033    box_row(&format!(
1034        " max_disk_mb         = {:10}  {}",
1035        cfg.max_disk_mb_effective(),
1036        source_hint("LEAN_CTX_MAX_DISK_MB", cfg.max_disk_mb > 0)
1037    ));
1038    box_row(&format!(
1039        " max_ram_percent     = {:10}  {}",
1040        cfg.max_ram_percent,
1041        source_hint("LEAN_CTX_MAX_RAM_PERCENT", cfg.max_ram_percent != 5)
1042    ));
1043    box_row(&format!(
1044        " mcp_max_rss_mb      = {:10}  {}",
1045        cfg.mcp_max_rss_mb_effective(),
1046        source_hint("LEAN_CTX_MCP_MAX_RSS_MB", cfg.mcp_max_rss_mb != 512)
1047    ));
1048    box_row(&format!(
1049        " daemon_max_rss_mb   = {:10}  {}",
1050        cfg.daemon_max_rss_mb_effective(),
1051        source_hint("LEAN_CTX_DAEMON_MAX_RSS_MB", cfg.daemon_max_rss_mb != 2048)
1052    ));
1053    box_row(&format!(
1054        " mcp_idle_exit_minutes = {:8}  {}",
1055        cfg.mcp_idle_exit_minutes_effective(),
1056        source_hint(
1057            "LEAN_CTX_MCP_IDLE_EXIT_MINUTES",
1058            cfg.mcp_idle_exit_minutes > 0
1059        )
1060    ));
1061    box_row(&format!(
1062        " session_retention_days = {:8}  {}",
1063        cfg.session_retention_days_effective(),
1064        source_hint(
1065            "LEAN_CTX_SESSION_RETENTION_DAYS",
1066            cfg.session_retention_days != 7
1067        )
1068    ));
1069    box_row(&format!(
1070        " max_staleness_days  = {:10}  {}",
1071        cfg.max_staleness_days_effective(),
1072        source_hint("LEAN_CTX_MAX_STALENESS_DAYS", cfg.max_staleness_days > 0)
1073    ));
1074    box_row(&format!(
1075        " memory_profile      = {:10}  {}",
1076        format!("{:?}", cfg.memory_profile),
1077        source_hint("LEAN_CTX_MEMORY_PROFILE", false)
1078    ));
1079    println!("{}", box_bottom());
1080
1081    println!();
1082    println!("{}", box_top("Derived effective limits"));
1083    box_row(&format!(
1084        " archive_max_disk_mb    = {:>6} MB",
1085        cfg.archive_max_disk_mb_effective()
1086    ));
1087    box_row(&format!(
1088        " bm25_max_cache_mb      = {:>6} MB",
1089        cfg.bm25_max_cache_mb_effective()
1090    ));
1091    box_row(&format!(
1092        " archive_max_age_hours  = {:>6} h",
1093        cfg.archive_max_age_hours_effective()
1094    ));
1095    box_row(&format!(
1096        " graph_index_max_files  = {:>6}",
1097        cfg.graph_index_max_files
1098    ));
1099    box_row("");
1100    box_row(" memory.knowledge facts         = no limit");
1101    box_row(&format!(
1102        " memory.knowledge.max_patterns  = {:>6}",
1103        policy.knowledge.max_patterns
1104    ));
1105    println!("{}", box_bottom());
1106
1107    if cfg.max_disk_mb_effective() > 0 {
1108        println!();
1109        println!(
1110            "  ℹ  max_disk_mb={} → limits scaled proportionally (factor: {:.1}x)",
1111            cfg.max_disk_mb_effective(),
1112            (cfg.max_disk_mb_effective() as f64 / 500.0).clamp(0.5, 10.0)
1113        );
1114    }
1115}
1116
1117/// Interior width of the `config show` frames, in terminal columns.
1118const SHOW_BOX_W: usize = 60;
1119
1120/// `╭─── Label ───…───╮`, always `SHOW_BOX_W` columns wide inside the corners.
1121fn box_top(label: &str) -> String {
1122    let head = format!("─── {label} ");
1123    let fill = SHOW_BOX_W.saturating_sub(lean_ctx::core::theme::visual_len(&head));
1124    format!("╭{head}{}╮", "─".repeat(fill))
1125}
1126
1127fn box_bottom() -> String {
1128    format!("╰{}╯", "─".repeat(SHOW_BOX_W))
1129}
1130
1131/// Print one framed row, padded (or truncated) to the frame's interior width so
1132/// the right border lines up regardless of the value's length.
1133fn box_row(content: &str) {
1134    println!(
1135        "│{}│",
1136        lean_ctx::core::theme::pad_right(content, SHOW_BOX_W)
1137    );
1138}
1139
1140fn source_hint(env_var: &str, config_set: bool) -> &'static str {
1141    if std::env::var(env_var).is_ok() {
1142        "← env"
1143    } else if config_set {
1144        "← config"
1145    } else {
1146        "← default"
1147    }
1148}
1149
1150fn dir_size(path: &std::path::Path) -> u64 {
1151    let mut total = 0u64;
1152    if let Ok(entries) = std::fs::read_dir(path) {
1153        for entry in entries.flatten() {
1154            let p = entry.path();
1155            if p.is_file() {
1156                total += std::fs::metadata(&p).map_or(0, |m| m.len());
1157            } else if p.is_dir() {
1158                total += dir_size(&p);
1159            }
1160        }
1161    }
1162    total
1163}
1164
1165#[cfg(test)]
1166mod tests;