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 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
116fn 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
162fn 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
182fn 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 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 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 let remaining = ipc::process::find_pids_by_name("lean-ctx");
285 if !remaining.is_empty() {
286 for &pid in &remaining {
287 let _ = ipc::process::force_kill(pid);
288 }
289 std::thread::sleep(std::time::Duration::from_millis(300));
290 }
291
292 daemon::cleanup_daemon_files();
293 crate::proxy_autostart::start();
294
295 match daemon::start_daemon(&[]) {
296 Ok(()) => println!(" ✓ Daemon restarted."),
297 Err(e) => {
298 eprintln!(" ✗ Daemon start failed: {e}");
299 std::process::exit(1);
300 }
301 }
302
303 println!("\n[3/4] Running safety checks…");
305 println!(" RAM guard: max {}% system", cfg.max_ram_percent);
306
307 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
308 let sessions_dir = data_dir.join("sessions");
309 let session_count = std::fs::read_dir(&sessions_dir)
310 .map_or(0, |rd| rd.filter_map(std::result::Result::ok).count());
311 println!(" Sessions dir: {session_count} files");
312 }
313
314 println!("\n[4/4] Config applied successfully.");
316 println!(" Theme: {}", cfg.theme);
317 println!(" Ultra compact: {}", cfg.ultra_compact);
318 println!(" Checkpoint: every {} calls", cfg.checkpoint_interval);
319 if let Some(ref root) = cfg.project_root {
320 println!(" Project root: {root}");
321 }
322}
323
324fn cmd_config_path() {
333 let Some(p) = config::Config::path() else {
334 eprintln!("Error: cannot resolve a config directory");
335 std::process::exit(1);
336 };
337 println!("{}", p.display());
338}
339
340fn cmd_validate() {
341 print_config_provenance();
345
346 let schema = config::schema::ConfigSchema::generate();
347 let known = schema.known_keys();
348
349 let path = match config::Config::path() {
350 Some(p) if p.exists() => p,
351 Some(p) => {
352 println!("[OK] No config.toml at {} — using defaults.", p.display());
353 return;
354 }
355 None => {
356 println!("[OK] No config dir resolved — using defaults.");
357 return;
358 }
359 };
360
361 let raw = match std::fs::read_to_string(&path) {
362 Ok(s) => s,
363 Err(e) => {
364 eprintln!("[ERROR] Cannot read {}: {e}", path.display());
365 std::process::exit(1);
366 }
367 };
368
369 let table: toml::Table = match raw.parse() {
370 Ok(t) => t,
371 Err(e) => {
372 eprintln!("[ERROR] Invalid TOML: {e}");
373 std::process::exit(1);
374 }
375 };
376
377 let mut warnings = 0u32;
378 let mut validated = 0u32;
379
380 fn collect_keys(table: &toml::Table, prefix: &str, out: &mut Vec<String>) {
381 for (k, v) in table {
382 let full = if prefix.is_empty() {
383 k.clone()
384 } else {
385 format!("{prefix}.{k}")
386 };
387 match v {
388 toml::Value::Table(sub) => collect_keys(sub, &full, out),
389 toml::Value::Array(arr) => {
390 out.push(full.clone());
391 for item in arr {
392 if let toml::Value::Table(sub) = item {
393 for sk in sub.keys() {
394 out.push(format!("{full}[].{sk}"));
395 }
396 }
397 }
398 }
399 _ => out.push(full),
400 }
401 }
402 }
403
404 let mut user_keys = Vec::new();
405 collect_keys(&table, "", &mut user_keys);
406
407 for uk in &user_keys {
408 let base = uk.split("[].").next().unwrap_or(uk);
409 let field = uk.rsplit("[].").next().unwrap_or("");
410 let check_key = if uk.contains("[].") {
411 format!("{base}.{field}")
412 } else {
413 uk.clone()
414 };
415
416 if known.contains(&check_key)
417 || known
418 .iter()
419 .any(|k| check_key.starts_with(&format!("{k}.")))
420 {
421 validated += 1;
422 } else {
423 warnings += 1;
424 let suggestion = find_closest(&check_key, &known);
425 if let Some(sug) = suggestion {
426 eprintln!("[WARN] Unknown key '{uk}' -- did you mean '{sug}'?");
427 } else {
428 eprintln!("[WARN] Unknown key '{uk}' -- this field does not exist");
429 }
430 }
431 }
432
433 let cfg = config::Config::load();
434 let budget = cfg.max_disk_mb_effective();
435 if budget > 0 {
436 let explicit_archive = cfg.archive.max_disk_mb;
437 let explicit_bm25 = cfg.bm25_max_cache_mb;
438 let sum = explicit_archive + explicit_bm25;
439 if sum > budget {
440 warnings += 1;
441 println!(
442 " ⚠ max_disk_mb={budget} but archive.max_disk_mb({explicit_archive}) + bm25_max_cache_mb({explicit_bm25}) = {sum} exceeds budget"
443 );
444 }
445 }
446
447 let total = validated + warnings;
448 if warnings == 0 {
449 println!(
450 "[OK] All {total} keys validated successfully ({}).",
451 path.display()
452 );
453 } else {
454 println!(
455 "[RESULT] {validated} of {total} keys validated, {warnings} unknown ({}).",
456 path.display()
457 );
458 std::process::exit(1);
459 }
460}
461
462fn print_config_provenance() {
468 let prov = config::Config::provenance();
469
470 println!("Config source:");
471 match &prov.config_path {
472 Some(p) if prov.config_exists => println!(" config.toml: {} (exists)", p.display()),
473 Some(p) => println!(
474 " config.toml: {} (missing — using defaults)",
475 p.display()
476 ),
477 None => println!(" config.toml: <no config dir resolved — using defaults>"),
478 }
479 println!(
480 " layout pin: {}",
481 if prov.xdg_pinned { "xdg" } else { "unpinned" }
482 );
483
484 if let Some(err) = &prov.parse_error {
485 println!(" [!] parse error: config.toml is unparseable — running on DEFAULTS:");
486 println!(" {err}");
487 println!(" Run `lean-ctx doctor --fix` to repair.");
488 }
489
490 if prov.local_exists && !prov.local_keys.is_empty() {
491 let path = prov
492 .local_path
493 .as_ref()
494 .map(|p| p.display().to_string())
495 .unwrap_or_default();
496 println!(
497 " [!] project-local: {path} overrides {}",
498 prov.local_keys.join(", ")
499 );
500 println!(" (these win over the global config for this project)");
501 }
502
503 if !prov.env_overrides.is_empty() {
504 let list = prov
505 .env_overrides
506 .iter()
507 .map(|e| format!("{} ({})", e.var, e.setting))
508 .collect::<Vec<_>>()
509 .join(", ");
510 println!(" [!] env override: {list}");
511 println!(
512 " (these win over config.toml; unset them for saved values to apply)"
513 );
514 }
515
516 if prov.has_shadow() {
517 println!(
518 " -> A saved setting can appear to \"reset\" because a source above shadows it (GH #450)."
519 );
520 }
521 println!();
522}
523
524fn find_closest(needle: &str, haystack: &[String]) -> Option<String> {
530 use crate::core::levenshtein::levenshtein;
531 let mut best: Option<(usize, &str)> = None;
532 for candidate in haystack {
533 let d = levenshtein(needle, candidate);
534 if d <= 3 && (best.is_none() || d < best.unwrap().0) {
535 best = Some((d, candidate));
536 }
537 }
538 if best.is_some() {
539 return best.map(|(_, s)| s.to_string());
540 }
541 let leaf = needle.rsplit('.').next().unwrap_or(needle);
542 let mut leaf_best: Option<(usize, &str)> = None;
543 for candidate in haystack {
544 let cand_leaf = candidate.rsplit('.').next().unwrap_or(candidate);
545 let d = levenshtein(leaf, cand_leaf);
546 if d <= 2 && (leaf_best.is_none() || d < leaf_best.unwrap().0) {
547 leaf_best = Some((d, candidate));
548 }
549 }
550 leaf_best.map(|(_, s)| s.to_string())
551}
552
553fn normalize_optional_upstream(value: &str) -> Option<String> {
554 use crate::core::config::normalize_url_opt;
555 let trimmed = value.trim();
556 if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("default") {
557 None
558 } else {
559 normalize_url_opt(trimmed)
560 }
561}
562
563pub fn cmd_benchmark(args: &[String]) {
564 use crate::core::benchmark;
565 use crate::core::benchmark_compare;
566
567 let action = args.first().map_or("run", std::string::String::as_str);
568
569 match action {
570 "--help" | "-h" => {
571 println!("Usage: lean-ctx benchmark run [path] [--json]");
572 println!(" lean-ctx benchmark report [path]");
573 println!(" lean-ctx benchmark replay <sessions.json> [--output report.md]");
574 println!(" lean-ctx benchmark eval [path] [--json]");
575 println!(" lean-ctx benchmark eval-ab [path] [--suite file.ndjson] [--json]");
576 println!(" lean-ctx benchmark compare [--repo path] [--output file.md]");
577 println!(" lean-ctx benchmark scorecard [--json] [--output file]");
578 println!(" lean-ctx benchmark dual-arm [--json] [--output file]");
579 }
580 "dual-arm" => {
581 let is_json = args.iter().any(|a| a == "--json");
582 let output = parse_flag_value(args, "--output");
583 match crate::core::scorecard::dual_arm::run_dual_arm() {
584 Ok(sc) => {
585 let rendered = if is_json { sc.to_json() } else { sc.to_human() };
586 if let Some(path) = output {
587 if let Err(e) = std::fs::write(&path, &rendered) {
588 eprintln!("Failed to write dual-arm scorecard to {path}: {e}");
589 std::process::exit(1);
590 }
591 eprintln!("Wrote dual-arm scorecard to {path}");
592 } else {
593 print!("{rendered}");
594 }
595 }
596 Err(e) => {
597 eprintln!("Dual-arm bench failed: {e}");
598 std::process::exit(1);
599 }
600 }
601 }
602 "scorecard" => {
603 let is_json = args.iter().any(|a| a == "--json");
604 let output = parse_flag_value(args, "--output");
605 match crate::core::scorecard::run_scorecard() {
606 Ok(sc) => {
607 let rendered = if is_json { sc.to_json() } else { sc.to_human() };
608 if let Some(path) = output {
609 if let Err(e) = std::fs::write(&path, &rendered) {
610 eprintln!("Failed to write scorecard to {path}: {e}");
611 std::process::exit(1);
612 }
613 eprintln!("Wrote scorecard to {path}");
614 } else {
615 print!("{rendered}");
616 }
617 }
618 Err(e) => {
619 eprintln!("Scorecard failed: {e}");
620 std::process::exit(1);
621 }
622 }
623 }
624 "eval" => {
625 let path = args.get(1).map_or(".", std::string::String::as_str);
626 let is_json = args.iter().any(|a| a == "--json");
627 let root = std::path::Path::new(path);
628
629 let index = crate::core::bm25_index::BM25Index::build_from_directory(root);
630 let cfg = crate::core::hybrid_search::HybridConfig::from_config();
631 let queries = crate::core::eval_harness::generate_self_eval(&index, 50);
632
633 if queries.is_empty() {
634 eprintln!("No symbols found — cannot generate eval queries.");
635 std::process::exit(1);
636 }
637
638 let scorecard = crate::core::eval_harness::run_eval(root, &queries, &index, &cfg);
639 if is_json {
640 if let Ok(json) = serde_json::to_string_pretty(&scorecard) {
641 println!("{json}");
642 }
643 } else {
644 print!("{scorecard}");
645 }
646 }
647 "eval-ab" => {
648 let path = args
649 .get(1)
650 .filter(|a| !a.starts_with("--"))
651 .map_or(".", std::string::String::as_str);
652 let is_json = args.iter().any(|a| a == "--json");
653 let root = std::path::Path::new(path);
654 if !root.exists() {
655 eprintln!("Path does not exist: {path}");
656 std::process::exit(1);
657 }
658
659 let index = crate::core::bm25_index::BM25Index::build_from_directory(root);
660 let cfg = crate::core::hybrid_search::HybridConfig::from_config();
661
662 let queries = match parse_flag_value(args, "--suite") {
663 Some(suite) => {
664 match crate::core::eval_harness::load_suite(std::path::Path::new(&suite)) {
665 Ok(q) => q,
666 Err(e) => {
667 eprintln!("Failed to load suite {suite}: {e}");
668 std::process::exit(1);
669 }
670 }
671 }
672 None => crate::core::eval_harness::generate_self_eval(&index, 50),
673 };
674
675 if queries.is_empty() {
676 eprintln!("No eval queries (empty suite / no symbols indexed).");
677 std::process::exit(1);
678 }
679
680 let report = crate::core::eval_harness::run_ab(root, &queries, &index, &cfg);
681 if is_json {
682 println!("{}", report.to_json());
683 } else {
684 print!("{report}");
685 }
686 }
687 "run" => {
688 let path = args.get(1).map_or(".", std::string::String::as_str);
689 let is_json = args.iter().any(|a| a == "--json");
690
691 let result = benchmark::run_project_benchmark(path);
692 if is_json {
693 println!("{}", benchmark::format_json(&result));
694 } else {
695 println!("{}", benchmark::format_terminal(&result));
696 }
697 }
698 "report" => {
699 let path = args.get(1).map_or(".", std::string::String::as_str);
700 let result = benchmark::run_project_benchmark(path);
701 println!("{}", benchmark::format_markdown(&result));
702 }
703 "replay" => {
704 let Some(input) = args.get(1).filter(|arg| !arg.starts_with("--")) else {
705 eprintln!("Usage: lean-ctx benchmark replay <sessions.json> [--output report.md]");
706 std::process::exit(1);
707 };
708 let result = crate::core::quality_benchmark::load_replay(std::path::Path::new(input))
709 .and_then(|suite| crate::core::quality_benchmark::replay(&suite));
710 match result {
711 Ok(report) => {
712 let markdown = crate::core::quality_benchmark::format_markdown(&report);
713 if let Some(output) = parse_flag_value(args, "--output") {
714 if let Err(error) = std::fs::write(&output, markdown) {
715 eprintln!("Failed to write benchmark report to {output}: {error}");
716 std::process::exit(1);
717 }
718 eprintln!("Wrote compression quality report to {output}");
719 } else {
720 print!("{markdown}");
721 }
722 }
723 Err(error) => {
724 eprintln!("Benchmark replay failed: {error:#}");
725 std::process::exit(1);
726 }
727 }
728 }
729 "compare" => {
730 let repo = parse_flag_value(args, "--repo").unwrap_or_else(|| ".".to_string());
731 let output = parse_flag_value(args, "--output");
732
733 let root = std::path::Path::new(&repo);
734 if !root.exists() {
735 eprintln!("Repository path does not exist: {repo}");
736 std::process::exit(1);
737 }
738
739 let report = benchmark_compare::run_compare(root, output.as_deref());
740
741 println!("{}", benchmark_compare::report::generate_terminal(&report));
742
743 if output.is_none() {
744 eprintln!("Tip: use --output BENCHMARKS.md to save the full markdown report");
745 }
746 }
747 _ => {
748 if std::path::Path::new(action).exists() {
749 let result = benchmark::run_project_benchmark(action);
750 println!("{}", benchmark::format_terminal(&result));
751 } else {
752 eprintln!("Usage: lean-ctx benchmark run [path] [--json]");
753 eprintln!(" lean-ctx benchmark report [path]");
754 eprintln!(" lean-ctx benchmark replay <sessions.json> [--output report.md]");
755 eprintln!(" lean-ctx benchmark eval [path] [--json]");
756 eprintln!(
757 " lean-ctx benchmark eval-ab [path] [--suite file.ndjson] [--json]"
758 );
759 eprintln!(" lean-ctx benchmark compare [--repo path] [--output file.md]");
760 eprintln!(" lean-ctx benchmark scorecard [--json] [--output file]");
761 std::process::exit(1);
762 }
763 }
764 }
765}
766
767fn parse_flag_value(args: &[String], flag: &str) -> Option<String> {
768 args.iter()
769 .position(|a| a == flag)
770 .and_then(|i| args.get(i + 1))
771 .cloned()
772}
773
774fn load_mcp_live_stats() -> Option<serde_json::Value> {
775 let path = crate::core::paths::state_dir().ok()?.join("mcp-live.json");
776 let content = std::fs::read_to_string(path).ok()?;
777 serde_json::from_str(&content).ok()
778}
779
780fn stats_json_value(
781 store: &crate::core::stats::StatsStore,
782 mcp_cache: Option<serde_json::Value>,
783) -> serde_json::Value {
784 let mut value = serde_json::to_value(store).unwrap_or_else(|_| serde_json::json!({}));
785 if let (Some(object), Some(mcp_cache)) = (value.as_object_mut(), mcp_cache) {
786 object.insert("mcp_cache".to_string(), mcp_cache);
787 }
788 value
789}
790
791fn mcp_cache_stats_lines(value: &serde_json::Value) -> Vec<String> {
792 let metric = |key| {
793 value
794 .get(key)
795 .and_then(serde_json::Value::as_u64)
796 .unwrap_or(0)
797 };
798 let mcp_reads = metric("total_reads");
799 let mcp_hits = metric("cache_hits");
800 let mcp_rate = if mcp_reads > 0 {
801 (mcp_hits as f64 / mcp_reads as f64 * 100.0).round() as u32
802 } else {
803 0
804 };
805 let updated = value
806 .get("updated_at")
807 .and_then(serde_json::Value::as_str)
808 .unwrap_or("unknown");
809 let mut lines = vec![
810 "MCP Session Cache (ctx_read via AI editor):".to_string(),
811 format!(" Reads: {mcp_reads}"),
812 format!(" Hits: {mcp_hits}"),
813 format!(" Hit Rate: {mcp_rate}%"),
814 format!(" Tokens Saved: {}", metric("tokens_saved")),
815 format!(" Last Updated: {updated}"),
816 ];
817
818 let dedup_reads = metric("dedup_reads");
819 if dedup_reads > 0 {
820 let dedup_hits = metric("dedup_hits");
821 let dedup_rate = dedup_hits as f64 / dedup_reads as f64 * 100.0;
822 lines.extend([
823 String::new(),
824 "Content Dedup (repeated ctx_read output):".to_string(),
825 format!(" Reads Checked: {dedup_reads}"),
826 format!(" Hits: {dedup_hits}"),
827 format!(" Hit Rate: {dedup_rate:.1}%"),
828 format!(" Tokens Saved: {}", metric("dedup_tokens_saved")),
829 ]);
830 }
831
832 lines
833}
834
835pub fn cmd_stats(args: &[String]) {
836 match args.first().map(std::string::String::as_str) {
837 Some("reset-cep") => {
838 crate::core::stats::reset_cep();
839 println!("CEP stats reset. Shell hook data preserved.");
840 }
841 Some("json") => {
842 let store = crate::core::stats::load();
843 let value = stats_json_value(&store, load_mcp_live_stats());
844 println!(
845 "{}",
846 serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string())
847 );
848 }
849 _ => {
850 let store = crate::core::stats::load();
851 let input_saved = store
852 .total_input_tokens
853 .saturating_sub(store.total_output_tokens);
854 let pct = if store.total_input_tokens > 0 {
855 input_saved as f64 / store.total_input_tokens as f64 * 100.0
856 } else {
857 0.0
858 };
859 println!("Commands: {}", store.total_commands);
860 println!("Input: {} tokens", store.total_input_tokens);
861 println!("Output: {} tokens", store.total_output_tokens);
862 println!("Saved: {input_saved} tokens ({pct:.1}%)");
863 println!();
864 println!("CEP sessions: {}", store.cep.sessions);
865 println!(
866 "CEP tokens: {} → {}",
867 store.cep.total_tokens_original, store.cep.total_tokens_compressed
868 );
869 println!();
870 println!("Subcommands: stats reset-cep | stats json");
871 }
872 }
873}
874
875pub fn cmd_cache(args: &[String]) {
876 use crate::core::cli_cache;
877 match args.first().map(std::string::String::as_str) {
878 Some("clear") => {
879 let count = cli_cache::clear();
880 println!("Cleared {count} cached entries.");
881 }
882 Some("reset") => {
883 let project_flag = args.get(1).map(std::string::String::as_str) == Some("--project");
884 if project_flag {
885 let root =
886 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root);
887 if let Some(root) = root {
888 let count = cli_cache::clear_project(&root);
889 println!("Reset {count} cache entries for project: {root}");
890 } else {
891 eprintln!("No active project root found. Start a session first.");
892 std::process::exit(1);
893 }
894 } else {
895 let count = cli_cache::clear();
896 println!("Reset all {count} cache entries.");
897 }
898 }
899 Some("stats") => {
900 let (hits, reads, entries) = cli_cache::stats();
901 let rate = if reads > 0 {
902 (hits as f64 / reads as f64 * 100.0).round() as u32
903 } else {
904 0
905 };
906 println!("CLI Cache Stats (lean-ctx read / lean-ctx grep):");
907 println!(" Entries: {entries}");
908 println!(" Reads: {reads}");
909 println!(" Hits: {hits}");
910 println!(" Hit Rate: {rate}%");
911
912 if let Some(value) = load_mcp_live_stats() {
913 println!();
914 for line in mcp_cache_stats_lines(&value) {
915 println!("{line}");
916 }
917 } else {
918 println!();
919 println!("MCP Session Cache: no data yet (start a session with your AI editor)");
920 }
921 }
922 Some("invalidate") => {
923 if args.len() < 2 {
924 eprintln!("Usage: lean-ctx cache invalidate <path>");
925 std::process::exit(1);
926 }
927 cli_cache::invalidate(&args[1]);
928 println!("Invalidated cache for {}", args[1]);
929 }
930 Some("prune") => {
931 let bm25 = prune_bm25_caches();
932 let graph = prune_graph_caches();
933 let archive_before = crate::core::archive::disk_usage_bytes()
936 + crate::core::archive_fts::db_size_bytes();
937 let archive_removed = crate::core::archive::cleanup();
938 let _ = crate::core::archive_fts::enforce_cap();
939 let archive_after = crate::core::archive::disk_usage_bytes()
940 + crate::core::archive_fts::db_size_bytes();
941 let archive_freed = archive_before.saturating_sub(archive_after);
942
943 let orphans = crate::core::knowledge::maintenance::prune_orphaned_stores();
947
948 let removed = bm25.removed + graph.removed + archive_removed + orphans.removed as u32;
949 let failed = bm25.failed + graph.failed;
950 let freed =
951 bm25.bytes_freed + graph.bytes_freed + archive_freed + orphans.reclaimed_bytes;
952 println!(
953 "Pruned {} entries, freed {:.1} MB (BM25: {}, graphs: {}, archive: {}, orphaned stores: {}, failed: {})",
954 removed,
955 freed as f64 / 1_048_576.0,
956 bm25.removed,
957 graph.removed,
958 archive_removed,
959 orphans.removed,
960 failed,
961 );
962 }
963 _ => {
964 let (hits, reads, entries) = cli_cache::stats();
965 let rate = if reads > 0 {
966 (hits as f64 / reads as f64 * 100.0).round() as u32
967 } else {
968 0
969 };
970 println!("CLI File Cache: {entries} entries, {hits}/{reads} hits ({rate}%)");
971 println!();
972 println!("Subcommands:");
973 println!(" cache stats Show detailed stats");
974 println!(" cache clear Clear all cached entries");
975 println!(" cache reset Reset all cache (or --project for current project only)");
976 println!(" cache invalidate Remove specific file from cache");
977 println!(
978 " cache prune Reclaim BM25 + graph indexes, archive, and orphaned knowledge stores"
979 );
980 }
981 }
982}
983
984pub struct PruneResult {
985 pub scanned: u32,
986 pub removed: u32,
987 pub failed: u32,
988 pub bytes_freed: u64,
989}
990
991fn record_removed_file(result: &mut PruneResult, path: &std::path::Path, label: &str) {
992 let bytes = std::fs::metadata(path).map_or(0, |meta| meta.len());
993
994 match std::fs::remove_file(path) {
995 Ok(()) => {
996 result.bytes_freed += bytes;
997 result.removed += 1;
998 println!(" {label}: {}", path.display());
999 }
1000 Err(error) => {
1001 result.failed += 1;
1002 eprintln!(" Failed to remove {}: {error}", path.display());
1003 }
1004 }
1005}
1006
1007fn record_removed_dir(
1008 result: &mut PruneResult,
1009 path: &std::path::Path,
1010 bytes: u64,
1011 message: impl FnOnce() -> String,
1012) {
1013 match std::fs::remove_dir_all(path) {
1014 Ok(()) => {
1015 result.bytes_freed += bytes;
1016 result.removed += 1;
1017 println!(" {}", message());
1018 }
1019 Err(error) => {
1020 result.failed += 1;
1021 eprintln!(" Failed to remove {}: {error}", path.display());
1022 }
1023 }
1024}
1025
1026pub fn prune_bm25_caches() -> PruneResult {
1027 let mut result = PruneResult {
1028 scanned: 0,
1029 removed: 0,
1030 failed: 0,
1031 bytes_freed: 0,
1032 };
1033
1034 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1035 return result;
1036 };
1037 let vectors_dir = data_dir.join("vectors");
1038 let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
1039 return result;
1040 };
1041
1042 let max_bytes = crate::core::config::Config::load().bm25_max_cache_mb_effective() * 1024 * 1024;
1043
1044 for entry in entries.flatten() {
1045 let dir = entry.path();
1046 if !dir.is_dir() {
1047 continue;
1048 }
1049 result.scanned += 1;
1050
1051 for q_name in &[
1052 "bm25_index.json.quarantined",
1053 "bm25_index.bin.quarantined",
1054 "bm25_index.bin.zst.quarantined",
1055 ] {
1056 let quarantined = dir.join(q_name);
1057 if quarantined.exists() {
1058 record_removed_file(&mut result, &quarantined, "Removed quarantined");
1059 }
1060 }
1061
1062 let index_path = if dir.join("bm25_index.bin.zst").exists() {
1063 dir.join("bm25_index.bin.zst")
1064 } else if dir.join("bm25_index.bin").exists() {
1065 dir.join("bm25_index.bin")
1066 } else {
1067 dir.join("bm25_index.json")
1068 };
1069 if let Ok(meta) = std::fs::metadata(&index_path)
1070 && meta.len() > max_bytes
1071 {
1072 record_removed_file(&mut result, &index_path, "Removed oversized");
1073 }
1074
1075 let marker = dir.join("project_root.txt");
1076 if let Ok(root_str) = std::fs::read_to_string(&marker) {
1077 let root_path = std::path::Path::new(root_str.trim());
1078 if !root_path.exists() {
1079 let freed = dir_size(&dir);
1080 record_removed_dir(&mut result, &dir, freed, || {
1081 format!(
1082 "Removed orphaned ({:.1} MB, project gone: {}): {}",
1083 freed as f64 / 1_048_576.0,
1084 root_str.trim(),
1085 dir.display()
1086 )
1087 });
1088 }
1089 }
1090 }
1091
1092 result
1093}
1094
1095pub fn prune_graph_caches() -> PruneResult {
1096 let mut result = PruneResult {
1097 scanned: 0,
1098 removed: 0,
1099 failed: 0,
1100 bytes_freed: 0,
1101 };
1102
1103 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1104 return result;
1105 };
1106 let graphs_dir = data_dir.join("graphs");
1107 let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
1108 return result;
1109 };
1110
1111 for entry in entries.flatten() {
1112 let dir = entry.path();
1113 if !dir.is_dir() {
1114 continue;
1115 }
1116 result.scanned += 1;
1117
1118 let meta_file = dir.join("graph.meta.json");
1122 let db_file = dir.join("graph.db");
1123 if !meta_file.exists() && !db_file.exists() {
1124 continue;
1125 }
1126
1127 let root_from_meta = try_read_project_root_from_graph(&meta_file);
1128 if let Some(root) = root_from_meta
1129 && !root.is_empty()
1130 && !std::path::Path::new(&root).exists()
1131 {
1132 let freed = dir_size(&dir);
1133 record_removed_dir(&mut result, &dir, freed, || {
1134 format!(
1135 "Removed orphaned graph ({:.1} MB, project gone: {}): {}",
1136 freed as f64 / 1_048_576.0,
1137 root,
1138 dir.display()
1139 )
1140 });
1141 continue;
1142 }
1143
1144 if let Ok(meta) = std::fs::metadata(&db_file)
1148 && meta.len() > 100 * 1024 * 1024
1149 {
1150 let freed = dir_size(&dir);
1151 record_removed_dir(&mut result, &dir, freed, || {
1152 format!(
1153 "Removed oversized graph ({:.1} MB): {}",
1154 freed as f64 / 1_048_576.0,
1155 dir.display()
1156 )
1157 });
1158 }
1159 }
1160
1161 result
1162}
1163
1164fn try_read_project_root_from_graph(path: &std::path::Path) -> Option<String> {
1167 let content = std::fs::read_to_string(path).ok()?;
1168 let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1169 val.get("project_root")?.as_str().map(String::from)
1170}
1171
1172pub const SIMPLIFIED_TEMPLATE: &str = r#"# lean-ctx — Simplified Configuration
1173# Full reference: https://leanctx.com/docs/configuration
1174# For all settings: lean-ctx config init --full
1175#
1176# Optional named overlay. LEAN_CTX_CONFIG_PROFILE overrides this selection:
1177# config_profile = "cloud"
1178# [profiles.local]
1179# compression_level = "lite"
1180# [profiles.cloud]
1181# compression_level = "standard"
1182
1183# ── High-Level Knobs ─────────────────────────────────────────────────
1184# These auto-adjust advanced settings. Override individual values below
1185# only if you need fine-grained control.
1186
1187# Output style for the model's prose (not tool-output compression):
1188# off — no style guidance
1189# lite — plain-English concise (default; readable, still token-saving)
1190# standard / max — denser symbolic "power modes" (opt-in)
1191compression_level = "lite"
1192
1193# RAM/feature trade-off: low | balanced | performance
1194memory_profile = "balanced"
1195
1196# Maximum % of system RAM lean-ctx may use (1-50)
1197max_ram_percent = 5
1198
1199# Total disk budget in MB (0 = use individual limits).
1200# Distributes proportionally: archive ~25%, BM25 cache ~10%.
1201# max_disk_mb = 2000
1202
1203# Auto-purge data older than N days (0 = disabled).
1204# Flows into archive.max_age_hours.
1205# max_staleness_days = 30
1206
1207# Explicit project paths to scan/index (default: auto-detect).
1208# [ide_paths]
1209# cursor = ["/home/user/projects/app1"]
1210
1211# ── Proxy ────────────────────────────────────────────────────────────
1212# proxy_enabled = false
1213# proxy_port = 3128
1214"#;
1215
1216fn write_simplified_config() -> Result<String, String> {
1217 let path = config::Config::path().ok_or_else(|| "Cannot determine config path".to_string())?;
1218 if let Some(dir) = path.parent() {
1219 std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
1220 }
1221 std::fs::write(&path, SIMPLIFIED_TEMPLATE).map_err(|e| format!("{e}"))?;
1222 Ok(path.to_string_lossy().to_string())
1223}
1224
1225fn cmd_show_effective() {
1226 let cfg = config::Config::load();
1227 let compression = config::CompressionLevel::effective(&cfg);
1228 let policy = cfg.memory_policy_effective().unwrap_or_default();
1229
1230 println!("{}", box_top("Simplified (high-level)"));
1231 box_row(&format!(
1232 " compression_level = {:10} {}",
1233 format!("{compression:?}"),
1234 source_hint(
1235 "LEAN_CTX_COMPRESSION",
1236 cfg.compression_level != config::CompressionLevel::Off
1237 )
1238 ));
1239 box_row(&format!(
1240 " max_disk_mb = {:10} {}",
1241 cfg.max_disk_mb_effective(),
1242 source_hint("LEAN_CTX_MAX_DISK_MB", cfg.max_disk_mb > 0)
1243 ));
1244 box_row(&format!(
1245 " max_ram_percent = {:10} {}",
1246 cfg.max_ram_percent,
1247 source_hint("LEAN_CTX_MAX_RAM_PERCENT", cfg.max_ram_percent != 5)
1248 ));
1249 box_row(&format!(
1250 " max_staleness_days = {:10} {}",
1251 cfg.max_staleness_days_effective(),
1252 source_hint("LEAN_CTX_MAX_STALENESS_DAYS", cfg.max_staleness_days > 0)
1253 ));
1254 box_row(&format!(
1255 " memory_profile = {:10} {}",
1256 format!("{:?}", cfg.memory_profile),
1257 source_hint("LEAN_CTX_MEMORY_PROFILE", false)
1258 ));
1259 println!("{}", box_bottom());
1260
1261 println!();
1262 println!("{}", box_top("Derived effective limits"));
1263 box_row(&format!(
1264 " archive_max_disk_mb = {:>6} MB",
1265 cfg.archive_max_disk_mb_effective()
1266 ));
1267 box_row(&format!(
1268 " bm25_max_cache_mb = {:>6} MB",
1269 cfg.bm25_max_cache_mb_effective()
1270 ));
1271 box_row(&format!(
1272 " archive_max_age_hours = {:>6} h",
1273 cfg.archive_max_age_hours_effective()
1274 ));
1275 box_row(&format!(
1276 " graph_index_max_files = {:>6}",
1277 cfg.graph_index_max_files
1278 ));
1279 box_row("");
1280 box_row(&format!(
1281 " memory.knowledge.max_facts = {:>6}",
1282 policy.knowledge.max_facts
1283 ));
1284 box_row(&format!(
1285 " memory.knowledge.max_patterns = {:>6}",
1286 policy.knowledge.max_patterns
1287 ));
1288 box_row(&format!(
1289 " memory.episodic.max_episodes = {:>6}",
1290 policy.episodic.max_episodes
1291 ));
1292 box_row(&format!(
1293 " memory.procedural.max_procedures = {:>4}",
1294 policy.procedural.max_procedures
1295 ));
1296 println!("{}", box_bottom());
1297
1298 if cfg.max_disk_mb_effective() > 0 {
1299 println!();
1300 println!(
1301 " ℹ max_disk_mb={} → limits scaled proportionally (factor: {:.1}x)",
1302 cfg.max_disk_mb_effective(),
1303 (cfg.max_disk_mb_effective() as f64 / 500.0).clamp(0.5, 10.0)
1304 );
1305 }
1306}
1307
1308const SHOW_BOX_W: usize = 60;
1310
1311fn box_top(label: &str) -> String {
1313 let head = format!("─── {label} ");
1314 let fill = SHOW_BOX_W.saturating_sub(crate::core::theme::visual_len(&head));
1315 format!("╭{head}{}╮", "─".repeat(fill))
1316}
1317
1318fn box_bottom() -> String {
1319 format!("╰{}╯", "─".repeat(SHOW_BOX_W))
1320}
1321
1322fn box_row(content: &str) {
1325 println!("│{}│", crate::core::theme::pad_right(content, SHOW_BOX_W));
1326}
1327
1328fn source_hint(env_var: &str, config_set: bool) -> &'static str {
1329 if std::env::var(env_var).is_ok() {
1330 "← env"
1331 } else if config_set {
1332 "← config"
1333 } else {
1334 "← default"
1335 }
1336}
1337
1338fn dir_size(path: &std::path::Path) -> u64 {
1339 let mut total = 0u64;
1340 if let Ok(entries) = std::fs::read_dir(path) {
1341 for entry in entries.flatten() {
1342 let p = entry.path();
1343 if p.is_file() {
1344 total += std::fs::metadata(&p).map_or(0, |m| m.len());
1345 } else if p.is_dir() {
1346 total += dir_size(&p);
1347 }
1348 }
1349 }
1350 total
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355 use super::*;
1356
1357 #[test]
1358 fn mcp_cache_stats_distinguish_session_cache_and_content_dedup() {
1359 let current = serde_json::json!({
1360 "total_reads": 55,
1361 "cache_hits": 2,
1362 "tokens_saved": 178_015,
1363 "dedup_reads": 10,
1364 "dedup_hits": 8,
1365 "dedup_tokens_saved": 12_345,
1366 "updated_at": "2026-07-24T14:17:30+02:00"
1367 });
1368 let lines = mcp_cache_stats_lines(¤t);
1369 assert!(lines.iter().any(|line| line == " Hit Rate: 4%"));
1370 assert!(
1371 lines
1372 .iter()
1373 .any(|line| line == "Content Dedup (repeated ctx_read output):")
1374 );
1375 assert!(lines.iter().any(|line| line == " Hit Rate: 80.0%"));
1376 assert!(lines.iter().any(|line| line == " Tokens Saved: 12345"));
1377
1378 let legacy = serde_json::json!({"total_reads": 3, "cache_hits": 1});
1379 let legacy_lines = mcp_cache_stats_lines(&legacy);
1380 assert!(
1381 legacy_lines
1382 .iter()
1383 .all(|line| !line.contains("Content Dedup"))
1384 );
1385 }
1386
1387 #[test]
1388 fn stats_json_embeds_mcp_cache_snapshot() {
1389 let store = crate::core::stats::StatsStore::default();
1390 let cache = serde_json::json!({"cache_hits": 2, "dedup_hits": 8});
1391 let value = stats_json_value(&store, Some(cache));
1392
1393 assert_eq!(value["mcp_cache"]["cache_hits"], 2);
1394 assert_eq!(value["mcp_cache"]["dedup_hits"], 8);
1395 assert!(stats_json_value(&store, None).get("mcp_cache").is_none());
1396 }
1397
1398 #[test]
1399 fn show_box_borders_line_up() {
1400 use crate::core::theme::{pad_right, visual_len};
1401 let bottom = visual_len(&box_bottom());
1402 for label in ["Simplified (high-level)", "Derived effective limits", ""] {
1403 assert_eq!(visual_len(&box_top(label)), bottom, "top border: {label:?}");
1404 }
1405 for row in ["", " x = 1", &" long ".repeat(40)] {
1407 assert_eq!(visual_len(&pad_right(row, SHOW_BOX_W)) + 2, bottom);
1408 }
1409 }
1410
1411 fn merged_max_ram(cfg: &config::Config, existing: &str) -> u8 {
1415 let dir = tempfile::tempdir().unwrap();
1416 let path = dir.path().join("config.toml");
1417 std::fs::write(&path, existing).unwrap();
1418 let new_content = toml::to_string_pretty(cfg).unwrap();
1419 let baseline = toml::from_str::<config::Config>("").unwrap();
1420 let defaults = toml::to_string_pretty(&baseline).unwrap();
1421 crate::config_io::write_toml_preserving_minimal(&path, &new_content, &defaults).unwrap();
1422 let written = std::fs::read_to_string(&path).unwrap();
1423 toml::from_str::<config::Config>(&written)
1424 .unwrap()
1425 .max_ram_percent
1426 }
1427
1428 #[test]
1429 fn full_init_uses_existing_values_not_defaults() {
1430 let existing = "max_ram_percent = 30\ncompression_level = \"standard\"\n";
1431 let cfg = config_for_full_init(Some(existing)).expect("parse existing");
1432 assert_eq!(cfg.max_ram_percent, 30, "must keep the user's value, not 5");
1433 assert_eq!(cfg.compression_level, config::CompressionLevel::Standard);
1434 }
1435
1436 #[test]
1437 fn full_init_falls_back_to_defaults_on_fresh_install() {
1438 let cfg = config_for_full_init(None).expect("default");
1439 assert_eq!(
1440 cfg.max_ram_percent,
1441 config::Config::default().max_ram_percent
1442 );
1443 let cfg_empty = config_for_full_init(Some(" \n")).expect("blank -> default");
1444 assert_eq!(
1445 cfg_empty.max_ram_percent,
1446 config::Config::default().max_ram_percent
1447 );
1448 }
1449
1450 #[test]
1451 fn full_init_refuses_unparseable_config() {
1452 assert!(config_for_full_init(Some("max_ram_percent = = =")).is_err());
1453 }
1454
1455 #[test]
1457 fn full_init_preserves_value_through_save_merge() {
1458 let existing = "max_ram_percent = 30\n";
1459 let cfg = config_for_full_init(Some(existing)).unwrap();
1460 assert_eq!(
1461 merged_max_ram(&cfg, existing),
1462 30,
1463 "user value must survive `config init --full`"
1464 );
1465 }
1466
1467 #[test]
1471 fn default_seed_resets_value_root_cause_marker() {
1472 let existing = "max_ram_percent = 30\n";
1473 assert_eq!(
1474 merged_max_ram(&config::Config::default(), existing),
1475 5,
1476 "default seed resets to 5 — the #443 regression we fixed"
1477 );
1478 }
1479}