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