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