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        println!(
10            "\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>`."
11        );
12        return;
13    }
14
15    match args[0].as_str() {
16        "init" | "create" => {
17            let full = args.iter().any(|a| a == "--full");
18            if full {
19                init_full_config();
20            } else {
21                match write_simplified_config() {
22                    Ok(path) => println!("Created simplified config at {path}"),
23                    Err(e) => eprintln!("Error: {e}"),
24                }
25            }
26        }
27        "set" => {
28            if args.len() < 3 {
29                eprintln!("Usage: lean-ctx config set <key> <value>");
30                std::process::exit(1);
31            }
32            let key = &args[1];
33            let val = &args[2];
34
35            // Special validation hooks for keys that need custom logic beyond
36            // what the schema type system can express. These either hard-fail
37            // early, or normalize the value/key that is actually persisted —
38            // the resolved (write_key, write_val) then flows through the single
39            // governed write path below so the #852 review covers every route.
40            let (write_key, write_val): (String, String) = match key.as_str() {
41                "theme" if theme::from_preset(val).is_none() && val != "custom" => {
42                    eprintln!(
43                        "Unknown theme '{val}'. Available: {}",
44                        theme::PRESET_NAMES.join(", ")
45                    );
46                    std::process::exit(1);
47                }
48                "tee_on_error" | "tee_mode" => {
49                    let normalized = match val.as_str() {
50                        "true" => "failures",
51                        "false" => "never",
52                        other => other,
53                    };
54                    ("tee_mode".to_string(), normalized.to_string())
55                }
56                "project_root" => {
57                    let path = std::path::Path::new(val.as_str());
58                    if !path.exists() || !path.is_dir() {
59                        eprintln!("Error: '{val}' is not an existing directory.");
60                        std::process::exit(1);
61                    }
62                    (key.clone(), val.clone())
63                }
64                "embedding.model"
65                    if crate::core::embeddings::model_registry::EmbeddingModel::from_str_name(
66                        val,
67                    )
68                    .is_none() =>
69                {
70                    eprintln!(
71                        "Unknown embedding model '{val}'. Available: minilm (default), \
72                         nomic — or hf:org/repo[@revision] for any HuggingFace repo with an \
73                         ONNX export, e.g. hf:jinaai/jina-embeddings-v2-base-code for code \
74                         (see docs/guides/custom-embeddings.md)."
75                    );
76                    std::process::exit(1);
77                }
78                "proxy.anthropic_upstream"
79                | "proxy.openai_upstream"
80                | "proxy.chatgpt_upstream"
81                | "proxy.gemini_upstream" => {
82                    let effective = normalize_optional_upstream(val).unwrap_or_default();
83                    (key.clone(), effective)
84                }
85                _ => (key.clone(), val.clone()),
86            };
87
88            write_config_key(&write_key, &write_val, key, val, args);
89        }
90        "schema" => {
91            let schema = config::schema::ConfigSchema::generate();
92            println!(
93                "{}",
94                serde_json::to_string_pretty(&schema).unwrap_or_else(|_| "{}".to_string())
95            );
96        }
97        "validate" => {
98            cmd_validate();
99        }
100        "show" | "effective" => {
101            cmd_show_effective();
102        }
103        "path" | "which" => {
104            cmd_config_path();
105        }
106        "apply" | "reload" => {
107            cmd_apply();
108        }
109        _ => {
110            eprintln!("Usage: lean-ctx config [init|set|show|schema|validate|apply|path]");
111            std::process::exit(1);
112        }
113    }
114}
115
116/// Single governed write path for `config set` (#852).
117///
118/// `key`/`value` are the resolved pair actually persisted; `display_key`/
119/// `display_val` are what the user typed (kept for messaging, e.g. when a value
120/// was normalized). Behavior:
121/// - **no-op** (current == new): report "unchanged", write nothing.
122/// - **consequential key** ([`config::risk`]): print a before→after review + a
123///   risk note, then require confirmation or `--yes`; abort if declined.
124/// - **routine key**: write directly, as before.
125fn write_config_key(key: &str, value: &str, display_key: &str, display_val: &str, args: &[String]) {
126    const BOLD: &str = "\x1b[1m";
127    const DIM: &str = "\x1b[2m";
128    const YELLOW: &str = "\x1b[33m";
129    const RST: &str = "\x1b[0m";
130
131    let current = config::setter::current_value(key);
132
133    if current.as_deref() == Some(value) {
134        println!("{display_key} is already set to {display_val} — unchanged.");
135        return;
136    }
137
138    if let Some(risk) = config::risk::classify(key) {
139        let before = current.as_deref().unwrap_or("(default)");
140        let after = if value.is_empty() { "(default)" } else { value };
141        println!("{BOLD}Review change to {display_key}{RST}");
142        println!("  {before}  →  {after}");
143        println!("  {YELLOW}{}{RST}", risk.note);
144        if !super::prompt::confirm(
145            &format!("Apply {display_key} = {display_val}?"),
146            super::prompt::wants_yes(args),
147        ) {
148            println!("{DIM}Aborted — {display_key} left unchanged.{RST}");
149            return;
150        }
151    }
152
153    match config::setter::set_by_key(key, value) {
154        Ok(_) => println!("Updated {display_key} = {display_val}"),
155        Err(e) => {
156            eprintln!("{e}");
157            std::process::exit(1);
158        }
159    }
160}
161
162/// Resolves the [`config::Config`] that `config init --full` should persist.
163///
164/// `existing_raw` is the verbatim content of the current GLOBAL `config.toml`
165/// (never the project-local `.lean-ctx.toml` — those overrides must not leak
166/// into the global file). When it holds a non-empty, parseable document we
167/// return its deserialized form so every user value is retained; an empty/absent
168/// file yields defaults, and an unparseable one is surfaced as an error so the
169/// caller can refuse to clobber it.
170///
171/// This is the regression guard for #443: `config init --full` previously wrote
172/// `Config::default()`, and `Config::save()` overwrites any key present in both
173/// the incoming document and the file (see `config_io::merge_table`), which
174/// silently reset customized values like `max_ram_percent` or `compression_level`.
175fn config_for_full_init(existing_raw: Option<&str>) -> Result<config::Config, String> {
176    match existing_raw.map(str::trim).filter(|raw| !raw.is_empty()) {
177        Some(raw) => toml::from_str::<config::Config>(raw).map_err(|e| e.to_string()),
178        None => Ok(config::Config::default()),
179    }
180}
181
182/// Implements `config init --full`: (re)writes the global config as a fully
183/// annotated reference document, seeded with the user's existing values (#443).
184///
185/// Unlike `save()` (which keeps the file minimal), this emits every key with its
186/// documentation. The body is a verbatim serialization of the resolved config,
187/// so no customized value is ever lost; an unparseable existing file is refused
188/// upstream by [`config_for_full_init`] rather than clobbered.
189fn init_full_config() {
190    let Some(path) = config::Config::path() else {
191        eprintln!("Error: cannot determine the config path");
192        return;
193    };
194
195    let existing_raw = std::fs::read_to_string(&path).ok();
196
197    let cfg = match config_for_full_init(existing_raw.as_deref()) {
198        Ok(cfg) => cfg,
199        Err(e) => {
200            eprintln!(
201                "Error: refusing to overwrite an unparseable config.toml ({e}).\n  \
202                 Fix it manually or run `lean-ctx doctor --fix`, then retry."
203            );
204            return;
205        }
206    };
207
208    let schema = config::schema::ConfigSchema::generate();
209    let rendered = config::render_annotated_config(&cfg, &schema);
210
211    match crate::config_io::write_atomic_with_backup(&path, &rendered) {
212        Ok(()) => println!("Created full annotated config at {}", path.display()),
213        Err(e) => eprintln!("Error: {e}"),
214    }
215}
216
217fn cmd_apply() {
218    use crate::daemon;
219    use crate::ipc;
220
221    println!("Applying config changes…");
222
223    // 1. Validate config first
224    println!("\n[1/4] Validating config…");
225    let schema = config::schema::ConfigSchema::generate();
226    let known = schema.known_keys();
227    let cfg = config::Config::load();
228
229    if let Some(path) = config::Config::path()
230        && path.exists()
231        && let Ok(raw) = std::fs::read_to_string(&path)
232        && let Ok(table) = raw.parse::<toml::Table>()
233    {
234        let mut user_keys = Vec::new();
235        fn collect_flat(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
236            for (k, v) in table {
237                let full = if prefix.is_empty() {
238                    k.clone()
239                } else {
240                    format!("{prefix}.{k}")
241                };
242                if let toml::Value::Table(sub) = v {
243                    collect_flat(sub, &full, out);
244                } else {
245                    out.push(full);
246                }
247            }
248        }
249        collect_flat(&table, "", &mut user_keys);
250        let warnings: Vec<_> = user_keys
251            .iter()
252            .filter(|uk| {
253                !known.contains(uk) && !known.iter().any(|k| uk.starts_with(&format!("{k}.")))
254            })
255            .collect();
256        if warnings.is_empty() {
257            println!("  ✓ All config keys valid.");
258        } else {
259            for w in &warnings {
260                eprintln!("  [WARN] Unknown key: {w}");
261            }
262            eprintln!(
263                "  {} unknown key(s) found. Continuing anyway…",
264                warnings.len()
265            );
266        }
267    }
268
269    // 2. Restart processes
270    println!("\n[2/4] Restarting processes…");
271    crate::proxy_autostart::stop();
272
273    if let Err(e) = daemon::stop_daemon() {
274        eprintln!("  Warning: daemon stop: {e}");
275    }
276
277    let orphans = ipc::process::kill_all_by_name("lean-ctx");
278    if orphans > 0 {
279        println!("  Terminated {orphans} orphan process(es).");
280    }
281
282    std::thread::sleep(std::time::Duration::from_millis(500));
283
284    // Preserve IDE-owned MCP stdio servers. Killing one here severs the active
285    // Codex connection and can leave the host stuck on "connecting" until it
286    // is restarted. `find_killable_pids` excludes those processes while still
287    // cleaning up stale daemon/proxy workers.
288    let remaining = ipc::process::find_killable_pids("lean-ctx");
289    if !remaining.is_empty() {
290        for &pid in &remaining {
291            let _ = ipc::process::force_kill(pid);
292        }
293        std::thread::sleep(std::time::Duration::from_millis(300));
294    }
295
296    daemon::cleanup_daemon_files();
297    crate::proxy_autostart::start();
298
299    match daemon::start_daemon(&[]) {
300        Ok(()) => println!("  ✓ Daemon restarted."),
301        Err(e) => {
302            eprintln!("  ✗ Daemon start failed: {e}");
303            std::process::exit(1);
304        }
305    }
306
307    // 3. Safety checks
308    println!("\n[3/4] Running safety checks…");
309    println!("  RAM guard: max {}% system", cfg.max_ram_percent);
310
311    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
312        let sessions_dir = data_dir.join("sessions");
313        let session_count = std::fs::read_dir(&sessions_dir)
314            .map_or(0, |rd| rd.filter_map(std::result::Result::ok).count());
315        println!("  Sessions dir: {session_count} files");
316    }
317
318    // 4. Summary
319    println!("\n[4/4] Config applied successfully.");
320    println!("  Theme:       {}", cfg.theme);
321    println!("  Ultra compact: {}", cfg.ultra_compact);
322    println!("  Checkpoint:  every {} calls", cfg.checkpoint_interval);
323    if let Some(ref root) = cfg.project_root {
324        println!("  Project root: {root}");
325    }
326}
327
328/// Print the absolute path of the resolved global `config.toml` (one line,
329/// scriptable).
330///
331/// This is the canonical way to verify that the CLI and the MCP server resolve
332/// the *same* config file (GH #594): run `lean-ctx config path` in a terminal
333/// and from the editor's MCP context, then compare. Output is the bare path so
334/// it can be diffed/captured in scripts and tests; it exits non-zero only when
335/// no config directory can be resolved at all.
336fn cmd_config_path() {
337    let Some(p) = config::Config::path() else {
338        eprintln!("Error: cannot resolve a config directory");
339        std::process::exit(1);
340    };
341    println!("{}", p.display());
342}
343
344fn cmd_validate() {
345    // GH #450: always surface *where* the effective settings come from first, so
346    // a "no config" result is never a dead end and a silently shadowed value
347    // (env / project-local / parse error) is immediately visible.
348    print_config_provenance();
349
350    let schema = config::schema::ConfigSchema::generate();
351    let known = schema.known_keys();
352
353    let path = match config::Config::path() {
354        Some(p) if p.exists() => p,
355        Some(p) => {
356            println!("[OK] No config.toml at {} — using defaults.", p.display());
357            return;
358        }
359        None => {
360            println!("[OK] No config dir resolved — using defaults.");
361            return;
362        }
363    };
364
365    let raw = match std::fs::read_to_string(&path) {
366        Ok(s) => s,
367        Err(e) => {
368            eprintln!("[ERROR] Cannot read {}: {e}", path.display());
369            std::process::exit(1);
370        }
371    };
372
373    let table: toml::Table = match raw.parse() {
374        Ok(t) => t,
375        Err(e) => {
376            eprintln!("[ERROR] Invalid TOML: {e}");
377            std::process::exit(1);
378        }
379    };
380
381    let mut warnings = 0u32;
382    let mut validated = 0u32;
383
384    fn collect_keys(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
385        for (k, v) in table {
386            let full = if prefix.is_empty() {
387                k.clone()
388            } else {
389                format!("{prefix}.{k}")
390            };
391            match v {
392                toml::Value::Table(sub) => collect_keys(sub, &full, out),
393                toml::Value::Array(arr) => {
394                    out.push(full.clone());
395                    for item in arr {
396                        if let toml::Value::Table(sub) = item {
397                            for sk in sub.keys() {
398                                out.push(format!("{full}[].{sk}"));
399                            }
400                        }
401                    }
402                }
403                _ => out.push(full),
404            }
405        }
406    }
407
408    let mut user_keys = Vec::new();
409    collect_keys(&table, "", &mut user_keys);
410
411    for uk in &user_keys {
412        let base = uk.split("[].").next().unwrap_or(uk);
413        let field = uk.rsplit("[].").next().unwrap_or("");
414        let check_key = if uk.contains("[].") {
415            format!("{base}.{field}")
416        } else {
417            uk.clone()
418        };
419
420        if known.contains(&check_key)
421            || known
422                .iter()
423                .any(|k| check_key.starts_with(&format!("{k}.")))
424        {
425            validated += 1;
426        } else {
427            warnings += 1;
428            let suggestion = find_closest(&check_key, &known);
429            if let Some(sug) = suggestion {
430                eprintln!("[WARN] Unknown key '{uk}' -- did you mean '{sug}'?");
431            } else {
432                eprintln!("[WARN] Unknown key '{uk}' -- this field does not exist");
433            }
434        }
435    }
436
437    let cfg = config::Config::load();
438    let budget = cfg.max_disk_mb_effective();
439    if budget > 0 {
440        let explicit_archive = cfg.archive.max_disk_mb;
441        let explicit_bm25 = cfg.bm25_max_cache_mb;
442        let sum = explicit_archive + explicit_bm25;
443        if sum > budget {
444            warnings += 1;
445            println!(
446                "  ⚠ max_disk_mb={budget} but archive.max_disk_mb({explicit_archive}) + bm25_max_cache_mb({explicit_bm25}) = {sum} exceeds budget"
447            );
448        }
449    }
450
451    let total = validated + warnings;
452    if warnings == 0 {
453        println!(
454            "[OK] All {total} keys validated successfully ({}).",
455            path.display()
456        );
457    } else {
458        println!(
459            "[RESULT] {validated} of {total} keys validated, {warnings} unknown ({}).",
460            path.display()
461        );
462        std::process::exit(1);
463    }
464}
465
466/// Print where the editable settings actually come from (GH #450): the resolved
467/// `config.toml` path, the layout pin, any parse error, and the env /
468/// project-local overrides that can silently shadow a saved value. This makes the
469/// "my quick settings keep resetting" reports self-diagnosing — the reporter sees
470/// the exact mechanism instead of an opaque "no config" message.
471fn print_config_provenance() {
472    let prov = config::Config::provenance();
473
474    println!("Config source:");
475    match &prov.config_path {
476        Some(p) if prov.config_exists => println!("  config.toml:    {} (exists)", p.display()),
477        Some(p) => println!(
478            "  config.toml:    {} (missing — using defaults)",
479            p.display()
480        ),
481        None => println!("  config.toml:    <no config dir resolved — using defaults>"),
482    }
483    println!(
484        "  layout pin:     {}",
485        if prov.xdg_pinned { "xdg" } else { "unpinned" }
486    );
487
488    if let Some(err) = &prov.parse_error {
489        println!("  [!] parse error: config.toml is unparseable — running on DEFAULTS:");
490        println!("                  {err}");
491        println!("                  Run `lean-ctx doctor --fix` to repair.");
492    }
493
494    if prov.local_exists && !prov.local_keys.is_empty() {
495        let path = prov
496            .local_path
497            .as_ref()
498            .map(|p| p.display().to_string())
499            .unwrap_or_default();
500        println!(
501            "  [!] project-local: {path} overrides {}",
502            prov.local_keys.join(", ")
503        );
504        println!("                  (these win over the global config for this project)");
505    }
506
507    if !prov.env_overrides.is_empty() {
508        let list = prov
509            .env_overrides
510            .iter()
511            .map(|e| format!("{} ({})", e.var, e.setting))
512            .collect::<Vec<_>>()
513            .join(", ");
514        println!("  [!] env override: {list}");
515        println!(
516            "                  (these win over config.toml; unset them for saved values to apply)"
517        );
518    }
519
520    if prov.has_shadow() {
521        println!(
522            "  -> A saved setting can appear to \"reset\" because a source above shadows it (GH #450)."
523        );
524    }
525    println!();
526}
527
528/// Closest config key: dotted-path match within distance 3, then a
529/// leaf-segment match within distance 2 (`proxy.prt` → `proxy.port`).
530/// Distances come from the shared [`crate::core::levenshtein`] helper (#712);
531/// the fixed budgets here predate the shared length-scaled one and are kept —
532/// dotted keys are long, so a length-scaled budget would over-suggest.
533fn find_closest(needle: &str, haystack: &[String]) -> Option<String> {
534    use crate::core::levenshtein::levenshtein;
535    let mut best: Option<(usize, &str)> = None;
536    for candidate in haystack {
537        let d = levenshtein(needle, candidate);
538        if d <= 3 && best.as_ref().is_none_or(|(best_d, _)| d < *best_d) {
539            best = Some((d, candidate));
540        }
541    }
542    if best.is_some() {
543        return best.map(|(_, s)| s.to_string());
544    }
545    let leaf = needle.rsplit('.').next().unwrap_or(needle);
546    let mut leaf_best: Option<(usize, &str)> = None;
547    for candidate in haystack {
548        let cand_leaf = candidate.rsplit('.').next().unwrap_or(candidate);
549        let d = levenshtein(leaf, cand_leaf);
550        if d <= 2 && leaf_best.as_ref().is_none_or(|(best_d, _)| d < *best_d) {
551            leaf_best = Some((d, candidate));
552        }
553    }
554    leaf_best.map(|(_, s)| s.to_string())
555}
556
557fn normalize_optional_upstream(value: &str) -> Option<String> {
558    use crate::core::config::normalize_url_opt;
559    let trimmed = value.trim();
560    if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("default") {
561        None
562    } else {
563        normalize_url_opt(trimmed)
564    }
565}
566
567pub fn cmd_benchmark(args: &[String]) {
568    use crate::core::benchmark;
569    use crate::core::benchmark_compare;
570
571    if args.is_empty() || args.first().is_some_and(|arg| arg.starts_with('-')) {
572        super::benchmark_tasks_cmd::cmd_benchmark_tasks(args);
573        return;
574    }
575
576    let action = args.first().map_or("run", std::string::String::as_str);
577
578    match action {
579        "--help" | "-h" => {
580            println!(
581                "Usage: lean-ctx benchmark [--config stock|standard|aggressive] [--repeats N] [--json|--markdown] [--output file]"
582            );
583            println!(
584                "       lean-ctx benchmark tasks [--config stock|standard|aggressive] [--repeats N] [--json|--markdown] [--output file]"
585            );
586            println!("       lean-ctx benchmark run [path] [--json]");
587            println!("       lean-ctx benchmark report [path]");
588            println!("       lean-ctx benchmark replay <sessions.json> [--output report.md]");
589            println!("       lean-ctx benchmark eval [path] [--json]");
590            println!("       lean-ctx benchmark eval-ab [path] [--suite file.ndjson] [--json]");
591            println!("       lean-ctx benchmark compare [--repo path] [--output file.md]");
592            println!("       lean-ctx benchmark scorecard [--json] [--output file]");
593            println!("       lean-ctx benchmark dual-arm [--json] [--output file]");
594            println!(
595                "       lean-ctx benchmark tasks [--config stock|standard|aggressive] [--repeats N] [--json|--markdown] [--output file]"
596            );
597            println!(
598                "       lean-ctx benchmark study [--suite humaneval] [--arms control,compress,route,combined] [--model MODEL] [--repeats N] [--timeout SECS] [--json] [--output file]"
599            );
600        }
601        "tasks" => {
602            super::benchmark_tasks_cmd::cmd_benchmark_tasks(&args[1..]);
603        }
604        "study" => {
605            super::benchmark_study_cmd::cmd_benchmark_study(&args[1..]);
606        }
607        "dual-arm" => {
608            let is_json = args.iter().any(|a| a == "--json");
609            let output = parse_flag_value(args, "--output");
610            match crate::core::scorecard::dual_arm::run_dual_arm() {
611                Ok(sc) => {
612                    let rendered = if is_json { sc.to_json() } else { sc.to_human() };
613                    if let Some(path) = output {
614                        if let Err(e) = std::fs::write(&path, &rendered) {
615                            eprintln!("Failed to write dual-arm scorecard to {path}: {e}");
616                            std::process::exit(1);
617                        }
618                        eprintln!("Wrote dual-arm scorecard to {path}");
619                    } else {
620                        print!("{rendered}");
621                    }
622                }
623                Err(e) => {
624                    eprintln!("Dual-arm bench failed: {e}");
625                    std::process::exit(1);
626                }
627            }
628        }
629        "scorecard" => {
630            let is_json = args.iter().any(|a| a == "--json");
631            let output = parse_flag_value(args, "--output");
632            match crate::core::scorecard::run_scorecard() {
633                Ok(sc) => {
634                    let rendered = if is_json { sc.to_json() } else { sc.to_human() };
635                    if let Some(path) = output {
636                        if let Err(e) = std::fs::write(&path, &rendered) {
637                            eprintln!("Failed to write scorecard to {path}: {e}");
638                            std::process::exit(1);
639                        }
640                        eprintln!("Wrote scorecard to {path}");
641                    } else {
642                        print!("{rendered}");
643                    }
644                }
645                Err(e) => {
646                    eprintln!("Scorecard failed: {e}");
647                    std::process::exit(1);
648                }
649            }
650        }
651        "eval" => {
652            let path = args.get(1).map_or(".", std::string::String::as_str);
653            let is_json = args.iter().any(|a| a == "--json");
654            let root = std::path::Path::new(path);
655
656            let index = crate::core::bm25_index::BM25Index::build_from_directory(root);
657            let cfg = crate::core::hybrid_search::HybridConfig::from_config();
658            let queries = crate::core::eval_harness::generate_self_eval(&index, 50);
659
660            if queries.is_empty() {
661                eprintln!("No symbols found — cannot generate eval queries.");
662                std::process::exit(1);
663            }
664
665            let scorecard = crate::core::eval_harness::run_eval(root, &queries, &index, &cfg);
666            if is_json {
667                if let Ok(json) = serde_json::to_string_pretty(&scorecard) {
668                    println!("{json}");
669                }
670            } else {
671                print!("{scorecard}");
672            }
673        }
674        "eval-ab" => {
675            let path = args
676                .get(1)
677                .filter(|a| !a.starts_with("--"))
678                .map_or(".", std::string::String::as_str);
679            let is_json = args.iter().any(|a| a == "--json");
680            let root = std::path::Path::new(path);
681            if !root.exists() {
682                eprintln!("Path does not exist: {path}");
683                std::process::exit(1);
684            }
685
686            let index = crate::core::bm25_index::BM25Index::build_from_directory(root);
687            let cfg = crate::core::hybrid_search::HybridConfig::from_config();
688
689            let queries = match parse_flag_value(args, "--suite") {
690                Some(suite) => {
691                    match crate::core::eval_harness::load_suite(std::path::Path::new(&suite)) {
692                        Ok(q) => q,
693                        Err(e) => {
694                            eprintln!("Failed to load suite {suite}: {e}");
695                            std::process::exit(1);
696                        }
697                    }
698                }
699                None => crate::core::eval_harness::generate_self_eval(&index, 50),
700            };
701
702            if queries.is_empty() {
703                eprintln!("No eval queries (empty suite / no symbols indexed).");
704                std::process::exit(1);
705            }
706
707            let report = crate::core::eval_harness::run_ab(root, &queries, &index, &cfg);
708            if is_json {
709                println!("{}", report.to_json());
710            } else {
711                print!("{report}");
712            }
713        }
714        "run" => {
715            let path = args.get(1).map_or(".", std::string::String::as_str);
716            let is_json = args.iter().any(|a| a == "--json");
717
718            let result = benchmark::run_project_benchmark(path);
719            if is_json {
720                println!("{}", benchmark::format_json(&result));
721            } else {
722                println!("{}", benchmark::format_terminal(&result));
723            }
724        }
725        "report" => {
726            let path = args.get(1).map_or(".", std::string::String::as_str);
727            let result = benchmark::run_project_benchmark(path);
728            println!("{}", benchmark::format_markdown(&result));
729        }
730        "replay" => {
731            let Some(input) = args.get(1).filter(|arg| !arg.starts_with("--")) else {
732                eprintln!("Usage: lean-ctx benchmark replay <sessions.json> [--output report.md]");
733                std::process::exit(1);
734            };
735            let result = crate::core::quality_benchmark::load_replay(std::path::Path::new(input))
736                .and_then(|suite| crate::core::quality_benchmark::replay(&suite));
737            match result {
738                Ok(report) => {
739                    let markdown = crate::core::quality_benchmark::format_markdown(&report);
740                    if let Some(output) = parse_flag_value(args, "--output") {
741                        if let Err(error) = std::fs::write(&output, markdown) {
742                            eprintln!("Failed to write benchmark report to {output}: {error}");
743                            std::process::exit(1);
744                        }
745                        eprintln!("Wrote compression quality report to {output}");
746                    } else {
747                        print!("{markdown}");
748                    }
749                }
750                Err(error) => {
751                    eprintln!("Benchmark replay failed: {error:#}");
752                    std::process::exit(1);
753                }
754            }
755        }
756        "compare" => {
757            let repo = parse_flag_value(args, "--repo").unwrap_or_else(|| ".".to_string());
758            let output = parse_flag_value(args, "--output");
759
760            let root = std::path::Path::new(&repo);
761            if !root.exists() {
762                eprintln!("Repository path does not exist: {repo}");
763                std::process::exit(1);
764            }
765
766            let report = benchmark_compare::run_compare(root, output.as_deref());
767
768            println!("{}", benchmark_compare::report::generate_terminal(&report));
769
770            if output.is_none() {
771                eprintln!("Tip: use --output BENCHMARKS.md to save the full markdown report");
772            }
773        }
774        _ => {
775            if std::path::Path::new(action).exists() {
776                let result = benchmark::run_project_benchmark(action);
777                println!("{}", benchmark::format_terminal(&result));
778            } else {
779                eprintln!("Usage: lean-ctx benchmark run [path] [--json]");
780                eprintln!("       lean-ctx benchmark report [path]");
781                eprintln!("       lean-ctx benchmark replay <sessions.json> [--output report.md]");
782                eprintln!("       lean-ctx benchmark eval [path] [--json]");
783                eprintln!(
784                    "       lean-ctx benchmark eval-ab [path] [--suite file.ndjson] [--json]"
785                );
786                eprintln!("       lean-ctx benchmark compare [--repo path] [--output file.md]");
787                eprintln!("       lean-ctx benchmark scorecard [--json] [--output file]");
788                std::process::exit(1);
789            }
790        }
791    }
792}
793
794fn parse_flag_value(args: &[String], flag: &str) -> Option<String> {
795    args.iter()
796        .position(|a| a == flag)
797        .and_then(|i| args.get(i + 1))
798        .cloned()
799}
800
801fn load_mcp_live_stats() -> Option<serde_json::Value> {
802    let path = crate::core::paths::state_dir().ok()?.join("mcp-live.json");
803    let content = std::fs::read_to_string(path).ok()?;
804    serde_json::from_str(&content).ok()
805}
806
807fn stats_json_value(
808    store: &crate::core::stats::StatsStore,
809    mcp_cache: Option<serde_json::Value>,
810) -> serde_json::Value {
811    let mut value = serde_json::to_value(store).unwrap_or_else(|_| serde_json::json!({}));
812    if let (Some(object), Some(mcp_cache)) = (value.as_object_mut(), mcp_cache) {
813        object.insert("mcp_cache".to_string(), mcp_cache);
814    }
815    value
816}
817
818fn mcp_cache_stats_lines(value: &serde_json::Value) -> Vec<String> {
819    let metric = |key| {
820        value
821            .get(key)
822            .and_then(serde_json::Value::as_u64)
823            .unwrap_or(0)
824    };
825    let mcp_reads = metric("total_reads");
826    let mcp_hits = metric("cache_hits");
827    let mcp_rate = if mcp_reads > 0 {
828        (mcp_hits as f64 / mcp_reads as f64 * 100.0).round() as u32
829    } else {
830        0
831    };
832    let updated = value
833        .get("updated_at")
834        .and_then(serde_json::Value::as_str)
835        .unwrap_or("unknown");
836    let mut lines = vec![
837        "MCP Session Cache (ctx_read via AI editor):".to_string(),
838        format!("  Reads:         {mcp_reads}"),
839        format!("  Hits:          {mcp_hits}"),
840        format!("  Hit Rate:      {mcp_rate}%"),
841        format!("  Tokens Saved:  {}", metric("tokens_saved")),
842        format!("  Last Updated:  {updated}"),
843    ];
844
845    let dedup_reads = metric("dedup_reads");
846    if dedup_reads > 0 {
847        let dedup_hits = metric("dedup_hits");
848        let dedup_rate = dedup_hits as f64 / dedup_reads as f64 * 100.0;
849        lines.extend([
850            String::new(),
851            "Content Dedup (repeated ctx_read output):".to_string(),
852            format!("  Reads Checked: {dedup_reads}"),
853            format!("  Hits:          {dedup_hits}"),
854            format!("  Hit Rate:      {dedup_rate:.1}%"),
855            format!("  Tokens Saved:  {}", metric("dedup_tokens_saved")),
856        ]);
857    }
858
859    lines
860}
861
862pub fn cmd_stats(args: &[String]) {
863    match args.first().map(std::string::String::as_str) {
864        Some("reset-cep") => {
865            crate::core::stats::reset_cep();
866            println!("CEP stats reset. Shell hook data preserved.");
867        }
868        Some("json") => {
869            let store = crate::core::stats::load();
870            let value = stats_json_value(&store, load_mcp_live_stats());
871            println!(
872                "{}",
873                serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
874            );
875        }
876        _ => {
877            let store = crate::core::stats::load();
878            let input_saved = store
879                .total_input_tokens
880                .saturating_sub(store.total_output_tokens);
881            let pct = if store.total_input_tokens > 0 {
882                input_saved as f64 / store.total_input_tokens as f64 * 100.0
883            } else {
884                0.0
885            };
886            println!("Commands:    {}", store.total_commands);
887            println!("Input:       {} tokens", store.total_input_tokens);
888            println!("Output:      {} tokens", store.total_output_tokens);
889            // #1284: scope the headline honestly — this ratio covers volume
890            // that flowed THROUGH lean-ctx. Native tool calls that bypassed
891            // lean-ctx are not in the denominator (they are counted separately
892            // as native_shell_passthrough in metering).
893            println!("Saved:       {input_saved} tokens ({pct:.1}% of metered lean-ctx volume)");
894            println!();
895            println!("CEP sessions:  {}", store.cep.sessions);
896            println!(
897                "CEP tokens:    {} → {}",
898                store.cep.total_tokens_original, store.cep.total_tokens_compressed
899            );
900            println!();
901            println!("Subcommands: stats reset-cep | stats json");
902        }
903    }
904}
905
906pub fn cmd_cache(args: &[String]) {
907    use crate::core::cli_cache;
908    match args.first().map(std::string::String::as_str) {
909        Some("clear") => {
910            let count = cli_cache::clear();
911            println!("Cleared {count} cached entries.");
912        }
913        Some("reset") => {
914            let project_flag = args.get(1).map(std::string::String::as_str) == Some("--project");
915            if project_flag {
916                let root =
917                    crate::core::session::SessionState::load_latest().and_then(|s| s.project_root);
918                if let Some(root) = root {
919                    let count = cli_cache::clear_project(&root);
920                    println!("Reset {count} cache entries for project: {root}");
921                } else {
922                    eprintln!("No active project root found. Start a session first.");
923                    std::process::exit(1);
924                }
925            } else {
926                let count = cli_cache::clear();
927                println!("Reset all {count} cache entries.");
928            }
929        }
930        Some("stats") => {
931            let (hits, reads, entries) = cli_cache::stats();
932            let rate = if reads > 0 {
933                (hits as f64 / reads as f64 * 100.0).round() as u32
934            } else {
935                0
936            };
937            println!("CLI Cache Stats (lean-ctx read / lean-ctx grep):");
938            println!("  Entries:   {entries}");
939            println!("  Reads:     {reads}");
940            println!("  Hits:      {hits}");
941            println!("  Hit Rate:  {rate}%");
942
943            if let Some(value) = load_mcp_live_stats() {
944                println!();
945                for line in mcp_cache_stats_lines(&value) {
946                    println!("{line}");
947                }
948            } else {
949                println!();
950                println!("MCP Session Cache: no data yet (start a session with your AI editor)");
951            }
952        }
953        Some("invalidate") => {
954            if args.len() < 2 {
955                eprintln!("Usage: lean-ctx cache invalidate <path>");
956                std::process::exit(1);
957            }
958            cli_cache::invalidate(&args[1]);
959            println!("Invalidated cache for {}", args[1]);
960        }
961        Some("prune") => {
962            let bm25 = prune_bm25_caches();
963            let graph = prune_graph_caches();
964            // Enforce the archive TTL + on-disk size budget alongside the index
965            // caches so a manual prune reclaims the (often largest) store too (#417).
966            let archive_before = crate::core::archive::disk_usage_bytes()
967                + crate::core::archive_fts::db_size_bytes();
968            let archive_removed = crate::core::archive::cleanup();
969            let _ = crate::core::archive_fts::enforce_cap();
970            let archive_after = crate::core::archive::disk_usage_bytes()
971                + crate::core::archive_fts::db_size_bytes();
972            let archive_freed = archive_before.saturating_sub(archive_after);
973
974            // Reclaim knowledge stores whose project_root was deleted (removed
975            // worktrees, thrown-away projects): they can never be written again,
976            // so their per-store eviction cap can never self-heal — pure bloat (#615).
977            let orphans = crate::core::knowledge::maintenance::prune_orphaned_stores();
978
979            let removed = bm25.removed + graph.removed + archive_removed + orphans.removed as u32;
980            let failed = bm25.failed + graph.failed;
981            let freed =
982                bm25.bytes_freed + graph.bytes_freed + archive_freed + orphans.reclaimed_bytes;
983            println!(
984                "Pruned {} entries, freed {:.1} MB (BM25: {}, graphs: {}, archive: {}, orphaned stores: {}, failed: {})",
985                removed,
986                freed as f64 / 1_048_576.0,
987                bm25.removed,
988                graph.removed,
989                archive_removed,
990                orphans.removed,
991                failed,
992            );
993        }
994        _ => {
995            let (hits, reads, entries) = cli_cache::stats();
996            let rate = if reads > 0 {
997                (hits as f64 / reads as f64 * 100.0).round() as u32
998            } else {
999                0
1000            };
1001            println!("CLI File Cache: {entries} entries, {hits}/{reads} hits ({rate}%)");
1002            println!();
1003            println!("Subcommands:");
1004            println!("  cache stats       Show detailed stats");
1005            println!("  cache clear       Clear all cached entries");
1006            println!("  cache reset       Reset all cache (or --project for current project only)");
1007            println!("  cache invalidate  Remove specific file from cache");
1008            println!(
1009                "  cache prune       Reclaim BM25 + graph indexes, archive, and orphaned knowledge stores"
1010            );
1011        }
1012    }
1013}
1014
1015pub struct PruneResult {
1016    pub scanned: u32,
1017    pub removed: u32,
1018    pub failed: u32,
1019    pub bytes_freed: u64,
1020}
1021
1022fn record_removed_file(result: &mut PruneResult, path: &std::path::Path, label: &str) {
1023    let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
1024
1025    match std::fs::remove_file(path) {
1026        Ok(()) => {
1027            result.bytes_freed += bytes;
1028            result.removed += 1;
1029            println!("  {label}: {}", path.display());
1030        }
1031        Err(error) => {
1032            result.failed += 1;
1033            eprintln!("  Failed to remove {}: {error}", path.display());
1034        }
1035    }
1036}
1037
1038fn record_removed_dir(
1039    result: &mut PruneResult,
1040    path: &std::path::Path,
1041    bytes: u64,
1042    message: impl FnOnce() -> String,
1043) {
1044    match std::fs::remove_dir_all(path) {
1045        Ok(()) => {
1046            result.bytes_freed += bytes;
1047            result.removed += 1;
1048            println!("  {}", message());
1049        }
1050        Err(error) => {
1051            result.failed += 1;
1052            eprintln!("  Failed to remove {}: {error}", path.display());
1053        }
1054    }
1055}
1056
1057pub fn prune_bm25_caches() -> PruneResult {
1058    let mut result = PruneResult {
1059        scanned: 0,
1060        removed: 0,
1061        failed: 0,
1062        bytes_freed: 0,
1063    };
1064
1065    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1066        return result;
1067    };
1068    let vectors_dir = data_dir.join("vectors");
1069    let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
1070        return result;
1071    };
1072
1073    let max_bytes = crate::core::config::Config::load().bm25_max_cache_mb_effective() * 1024 * 1024;
1074
1075    for entry in entries.flatten() {
1076        let dir = entry.path();
1077        if !dir.is_dir() {
1078            continue;
1079        }
1080        result.scanned += 1;
1081
1082        for q_name in &[
1083            "bm25_index.json.quarantined",
1084            "bm25_index.bin.quarantined",
1085            "bm25_index.bin.zst.quarantined",
1086        ] {
1087            let quarantined = dir.join(q_name);
1088            if quarantined.exists() {
1089                record_removed_file(&mut result, &quarantined, "Removed quarantined");
1090            }
1091        }
1092
1093        let index_path = if dir.join("bm25_index.bin.zst").exists() {
1094            dir.join("bm25_index.bin.zst")
1095        } else if dir.join("bm25_index.bin").exists() {
1096            dir.join("bm25_index.bin")
1097        } else {
1098            dir.join("bm25_index.json")
1099        };
1100        if let Ok(meta) = std::fs::metadata(&index_path)
1101            && meta.len() > max_bytes
1102        {
1103            record_removed_file(&mut result, &index_path, "Removed oversized");
1104        }
1105
1106        let marker = dir.join("project_root.txt");
1107        if let Ok(root_str) = std::fs::read_to_string(&marker) {
1108            let root_path = std::path::Path::new(root_str.trim());
1109            if !root_path.exists() {
1110                let freed = dir_size(&dir);
1111                record_removed_dir(&mut result, &dir, freed, || {
1112                    format!(
1113                        "Removed orphaned ({:.1} MB, project gone: {}): {}",
1114                        freed as f64 / 1_048_576.0,
1115                        root_str.trim(),
1116                        dir.display()
1117                    )
1118                });
1119            }
1120        }
1121    }
1122
1123    result
1124}
1125
1126pub fn prune_graph_caches() -> PruneResult {
1127    let mut result = PruneResult {
1128        scanned: 0,
1129        removed: 0,
1130        failed: 0,
1131        bytes_freed: 0,
1132    };
1133
1134    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1135        return result;
1136    };
1137    let graphs_dir = data_dir.join("graphs");
1138    let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
1139        return result;
1140    };
1141
1142    for entry in entries.flatten() {
1143        let dir = entry.path();
1144        if !dir.is_dir() {
1145            continue;
1146        }
1147        result.scanned += 1;
1148
1149        // #696 C4: the property graph (graph.db + graph.meta.json) is the sole
1150        // store. The meta carries the absolute project root, so an orphaned
1151        // `graphs/<hash>/` dir (project deleted) can still be pruned.
1152        let meta_file = dir.join("graph.meta.json");
1153        let db_file = dir.join("graph.db");
1154        if !meta_file.exists() && !db_file.exists() {
1155            continue;
1156        }
1157
1158        let root_from_meta = try_read_project_root_from_graph(&meta_file);
1159        if let Some(root) = root_from_meta
1160            && !root.is_empty()
1161            && !std::path::Path::new(&root).exists()
1162        {
1163            let freed = dir_size(&dir);
1164            record_removed_dir(&mut result, &dir, freed, || {
1165                format!(
1166                    "Removed orphaned graph ({:.1} MB, project gone: {}): {}",
1167                    freed as f64 / 1_048_576.0,
1168                    root,
1169                    dir.display()
1170                )
1171            });
1172            continue;
1173        }
1174
1175        // Oversized guard: a pathologically large (e.g. corrupt) graph store is
1176        // dropped so the next query rebuilds it cleanly — a rebuild cost, not
1177        // data loss.
1178        if let Ok(meta) = std::fs::metadata(&db_file)
1179            && meta.len() > 100 * 1024 * 1024
1180        {
1181            let freed = dir_size(&dir);
1182            record_removed_dir(&mut result, &dir, freed, || {
1183                format!(
1184                    "Removed oversized graph ({:.1} MB): {}",
1185                    freed as f64 / 1_048_576.0,
1186                    dir.display()
1187                )
1188            });
1189        }
1190    }
1191
1192    result
1193}
1194
1195/// Read the absolute project root recorded in a `graph.meta.json` file, if
1196/// present (#696 C4 — replaces reading it from the retired JSON index).
1197fn try_read_project_root_from_graph(path: &std::path::Path) -> Option<String> {
1198    let content = std::fs::read_to_string(path).ok()?;
1199    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1200    val.get("project_root")?.as_str().map(String::from)
1201}
1202
1203pub const SIMPLIFIED_TEMPLATE: &str = r#"# lean-ctx — Simplified Configuration
1204# Full reference: https://leanctx.com/docs/configuration
1205# For all settings: lean-ctx config init --full
1206#
1207# Optional named overlay. LEAN_CTX_CONFIG_PROFILE overrides this selection:
1208# config_profile = "cloud"
1209# [profiles.local]
1210# compression_level = "lite"
1211# [profiles.cloud]
1212# compression_level = "standard"
1213
1214# ── High-Level Knobs ─────────────────────────────────────────────────
1215# These auto-adjust advanced settings. Override individual values below
1216# only if you need fine-grained control.
1217
1218# Output style for the model's prose (not tool-output compression):
1219#   off    — no style guidance
1220#   lite   — plain-English concise (default; readable, still token-saving)
1221#   standard / max — denser symbolic "power modes" (opt-in)
1222compression_level = "lite"
1223
1224# RAM/feature trade-off: low | balanced | performance
1225memory_profile = "balanced"
1226
1227# Maximum % of system RAM lean-ctx may use (1-50)
1228max_ram_percent = 5
1229
1230# Total disk budget in MB (0 = use individual limits).
1231# Distributes proportionally: archive ~25%, BM25 cache ~10%.
1232# max_disk_mb = 2000
1233
1234# Auto-purge data older than N days (0 = disabled).
1235# Flows into archive.max_age_hours.
1236# max_staleness_days = 30
1237
1238# Session retention for `lean-ctx sessions cleanup` and `ctx_session cleanup`.
1239# This is independent from archive retention and preserves the newest session
1240# for every project root.
1241# session_retention_days = 7
1242
1243# Explicit project paths to scan/index (default: auto-detect).
1244# [ide_paths]
1245# cursor = ["/home/user/projects/app1"]
1246
1247# ── Proxy ────────────────────────────────────────────────────────────
1248# proxy_enabled = false
1249# proxy_port = 3128
1250"#;
1251
1252fn write_simplified_config() -> Result<String, String> {
1253    let path = config::Config::path().ok_or_else(|| "Cannot determine config path".to_string())?;
1254    if let Some(dir) = path.parent() {
1255        std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
1256    }
1257    std::fs::write(&path, SIMPLIFIED_TEMPLATE).map_err(|e| format!("{e}"))?;
1258    Ok(path.to_string_lossy().to_string())
1259}
1260
1261fn cmd_show_effective() {
1262    let cfg = config::Config::load();
1263    let compression = config::CompressionLevel::effective(&cfg);
1264    let policy = cfg.memory_policy_effective().unwrap_or_default();
1265
1266    println!("{}", box_top("Simplified (high-level)"));
1267    box_row(&format!(
1268        " compression_level   = {:10}  {}",
1269        format!("{compression:?}"),
1270        source_hint(
1271            "LEAN_CTX_COMPRESSION",
1272            cfg.compression_level != config::CompressionLevel::Off
1273        )
1274    ));
1275    box_row(&format!(
1276        " max_disk_mb         = {:10}  {}",
1277        cfg.max_disk_mb_effective(),
1278        source_hint("LEAN_CTX_MAX_DISK_MB", cfg.max_disk_mb > 0)
1279    ));
1280    box_row(&format!(
1281        " max_ram_percent     = {:10}  {}",
1282        cfg.max_ram_percent,
1283        source_hint("LEAN_CTX_MAX_RAM_PERCENT", cfg.max_ram_percent != 5)
1284    ));
1285    box_row(&format!(
1286        " session_retention_days = {:8}  {}",
1287        cfg.session_retention_days_effective(),
1288        source_hint(
1289            "LEAN_CTX_SESSION_RETENTION_DAYS",
1290            cfg.session_retention_days != 7
1291        )
1292    ));
1293    box_row(&format!(
1294        " max_staleness_days  = {:10}  {}",
1295        cfg.max_staleness_days_effective(),
1296        source_hint("LEAN_CTX_MAX_STALENESS_DAYS", cfg.max_staleness_days > 0)
1297    ));
1298    box_row(&format!(
1299        " memory_profile      = {:10}  {}",
1300        format!("{:?}", cfg.memory_profile),
1301        source_hint("LEAN_CTX_MEMORY_PROFILE", false)
1302    ));
1303    println!("{}", box_bottom());
1304
1305    println!();
1306    println!("{}", box_top("Derived effective limits"));
1307    box_row(&format!(
1308        " archive_max_disk_mb    = {:>6} MB",
1309        cfg.archive_max_disk_mb_effective()
1310    ));
1311    box_row(&format!(
1312        " bm25_max_cache_mb      = {:>6} MB",
1313        cfg.bm25_max_cache_mb_effective()
1314    ));
1315    box_row(&format!(
1316        " archive_max_age_hours  = {:>6} h",
1317        cfg.archive_max_age_hours_effective()
1318    ));
1319    box_row(&format!(
1320        " graph_index_max_files  = {:>6}",
1321        cfg.graph_index_max_files
1322    ));
1323    box_row("");
1324    box_row(&format!(
1325        " memory.knowledge.max_facts     = {:>6}",
1326        policy.knowledge.max_facts
1327    ));
1328    box_row(&format!(
1329        " memory.knowledge.max_patterns  = {:>6}",
1330        policy.knowledge.max_patterns
1331    ));
1332    box_row(&format!(
1333        " memory.episodic.max_episodes   = {:>6}",
1334        policy.episodic.max_episodes
1335    ));
1336    box_row(&format!(
1337        " memory.procedural.max_procedures = {:>4}",
1338        policy.procedural.max_procedures
1339    ));
1340    println!("{}", box_bottom());
1341
1342    if cfg.max_disk_mb_effective() > 0 {
1343        println!();
1344        println!(
1345            "  ℹ  max_disk_mb={} → limits scaled proportionally (factor: {:.1}x)",
1346            cfg.max_disk_mb_effective(),
1347            (cfg.max_disk_mb_effective() as f64 / 500.0).clamp(0.5, 10.0)
1348        );
1349    }
1350}
1351
1352/// Interior width of the `config show` frames, in terminal columns.
1353const SHOW_BOX_W: usize = 60;
1354
1355/// `╭─── Label ───…───╮`, always `SHOW_BOX_W` columns wide inside the corners.
1356fn box_top(label: &str) -> String {
1357    let head = format!("─── {label} ");
1358    let fill = SHOW_BOX_W.saturating_sub(crate::core::theme::visual_len(&head));
1359    format!("╭{head}{}╮", "─".repeat(fill))
1360}
1361
1362fn box_bottom() -> String {
1363    format!("╰{}╯", "─".repeat(SHOW_BOX_W))
1364}
1365
1366/// Print one framed row, padded (or truncated) to the frame's interior width so
1367/// the right border lines up regardless of the value's length.
1368fn box_row(content: &str) {
1369    println!("│{}│", crate::core::theme::pad_right(content, SHOW_BOX_W));
1370}
1371
1372fn source_hint(env_var: &str, config_set: bool) -> &'static str {
1373    if std::env::var(env_var).is_ok() {
1374        "← env"
1375    } else if config_set {
1376        "← config"
1377    } else {
1378        "← default"
1379    }
1380}
1381
1382fn dir_size(path: &std::path::Path) -> u64 {
1383    let mut total = 0u64;
1384    if let Ok(entries) = std::fs::read_dir(path) {
1385        for entry in entries.flatten() {
1386            let p = entry.path();
1387            if p.is_file() {
1388                total += std::fs::metadata(&p).map_or(0, |m| m.len());
1389            } else if p.is_dir() {
1390                total += dir_size(&p);
1391            }
1392        }
1393    }
1394    total
1395}
1396
1397#[cfg(test)]
1398mod tests {
1399    use super::*;
1400
1401    #[test]
1402    fn mcp_cache_stats_distinguish_session_cache_and_content_dedup() {
1403        let current = serde_json::json!({
1404            "total_reads": 55,
1405            "cache_hits": 2,
1406            "tokens_saved": 178_015,
1407            "dedup_reads": 10,
1408            "dedup_hits": 8,
1409            "dedup_tokens_saved": 12_345,
1410            "updated_at": "2026-07-24T14:17:30+02:00"
1411        });
1412        let lines = mcp_cache_stats_lines(&current);
1413        assert!(lines.iter().any(|line| line == "  Hit Rate:      4%"));
1414        assert!(
1415            lines
1416                .iter()
1417                .any(|line| line == "Content Dedup (repeated ctx_read output):")
1418        );
1419        assert!(lines.iter().any(|line| line == "  Hit Rate:      80.0%"));
1420        assert!(lines.iter().any(|line| line == "  Tokens Saved:  12345"));
1421
1422        let legacy = serde_json::json!({"total_reads": 3, "cache_hits": 1});
1423        let legacy_lines = mcp_cache_stats_lines(&legacy);
1424        assert!(
1425            legacy_lines
1426                .iter()
1427                .all(|line| !line.contains("Content Dedup"))
1428        );
1429    }
1430
1431    #[test]
1432    fn stats_json_embeds_mcp_cache_snapshot() {
1433        let store = crate::core::stats::StatsStore::default();
1434        let cache = serde_json::json!({"cache_hits": 2, "dedup_hits": 8});
1435        let value = stats_json_value(&store, Some(cache));
1436
1437        assert_eq!(value["mcp_cache"]["cache_hits"], 2);
1438        assert_eq!(value["mcp_cache"]["dedup_hits"], 8);
1439        assert!(stats_json_value(&store, None).get("mcp_cache").is_none());
1440    }
1441
1442    #[test]
1443    fn show_box_borders_line_up() {
1444        use crate::core::theme::{pad_right, visual_len};
1445        let bottom = visual_len(&box_bottom());
1446        for label in ["Simplified (high-level)", "Derived effective limits", ""] {
1447            assert_eq!(visual_len(&box_top(label)), bottom, "top border: {label:?}");
1448        }
1449        // Rows track the same width, short and overlong alike.
1450        for row in ["", " x = 1", &" long ".repeat(40)] {
1451            assert_eq!(visual_len(&pad_right(row, SHOW_BOX_W)) + 2, bottom);
1452        }
1453    }
1454
1455    // Reproduces `Config::save()`'s on-disk merge without touching the real
1456    // config path: serialize `cfg`, then merge it onto `existing` exactly as
1457    // save() does, and return the value that `max_ram_percent` ends up with.
1458    fn merged_max_ram(cfg: &config::Config, existing: &str) -> u8 {
1459        let dir = tempfile::tempdir().unwrap();
1460        let path = dir.path().join("config.toml");
1461        std::fs::write(&path, existing).unwrap();
1462        let new_content = toml::to_string_pretty(cfg).unwrap();
1463        let baseline = toml::from_str::<config::Config>("").unwrap();
1464        let defaults = toml::to_string_pretty(&baseline).unwrap();
1465        crate::config_io::write_toml_preserving_minimal(&path, &new_content, &defaults).unwrap();
1466        let written = std::fs::read_to_string(&path).unwrap();
1467        toml::from_str::<config::Config>(&written)
1468            .unwrap()
1469            .max_ram_percent
1470    }
1471
1472    #[test]
1473    fn full_init_uses_existing_values_not_defaults() {
1474        let existing = "max_ram_percent = 30\ncompression_level = \"standard\"\n";
1475        let cfg = config_for_full_init(Some(existing)).expect("parse existing");
1476        assert_eq!(cfg.max_ram_percent, 30, "must keep the user's value, not 5");
1477        assert_eq!(cfg.compression_level, config::CompressionLevel::Standard);
1478    }
1479
1480    #[test]
1481    fn full_init_falls_back_to_defaults_on_fresh_install() {
1482        let cfg = config_for_full_init(None).expect("default");
1483        assert_eq!(
1484            cfg.max_ram_percent,
1485            config::Config::default().max_ram_percent
1486        );
1487        let cfg_empty = config_for_full_init(Some("   \n")).expect("blank -> default");
1488        assert_eq!(
1489            cfg_empty.max_ram_percent,
1490            config::Config::default().max_ram_percent
1491        );
1492    }
1493
1494    #[test]
1495    fn full_init_refuses_unparseable_config() {
1496        assert!(config_for_full_init(Some("max_ram_percent = = =")).is_err());
1497    }
1498
1499    // #443 end-to-end: `config init --full` must not reset a customized value.
1500    #[test]
1501    fn full_init_preserves_value_through_save_merge() {
1502        let existing = "max_ram_percent = 30\n";
1503        let cfg = config_for_full_init(Some(existing)).unwrap();
1504        assert_eq!(
1505            merged_max_ram(&cfg, existing),
1506            30,
1507            "user value must survive `config init --full`"
1508        );
1509    }
1510
1511    // Guards the root cause: seeding the write from `Config::default()` (the old
1512    // behavior) DOES reset the value — proving why `config_for_full_init` must
1513    // load the existing config instead.
1514    #[test]
1515    fn default_seed_resets_value_root_cause_marker() {
1516        let existing = "max_ram_percent = 30\n";
1517        assert_eq!(
1518            merged_max_ram(&config::Config::default(), existing),
1519            5,
1520            "default seed resets to 5 — the #443 regression we fixed"
1521        );
1522    }
1523}