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 eval [path] [--json]");
574 println!(" lean-ctx benchmark eval-ab [path] [--suite file.ndjson] [--json]");
575 println!(" lean-ctx benchmark compare [--repo path] [--output file.md]");
576 println!(" lean-ctx benchmark scorecard [--json] [--output file]");
577 println!(" lean-ctx benchmark dual-arm [--json] [--output file]");
578 }
579 "dual-arm" => {
580 let is_json = args.iter().any(|a| a == "--json");
581 let output = parse_flag_value(args, "--output");
582 match crate::core::scorecard::dual_arm::run_dual_arm() {
583 Ok(sc) => {
584 let rendered = if is_json { sc.to_json() } else { sc.to_human() };
585 if let Some(path) = output {
586 if let Err(e) = std::fs::write(&path, &rendered) {
587 eprintln!("Failed to write dual-arm scorecard to {path}: {e}");
588 std::process::exit(1);
589 }
590 eprintln!("Wrote dual-arm scorecard to {path}");
591 } else {
592 print!("{rendered}");
593 }
594 }
595 Err(e) => {
596 eprintln!("Dual-arm bench failed: {e}");
597 std::process::exit(1);
598 }
599 }
600 }
601 "scorecard" => {
602 let is_json = args.iter().any(|a| a == "--json");
603 let output = parse_flag_value(args, "--output");
604 match crate::core::scorecard::run_scorecard() {
605 Ok(sc) => {
606 let rendered = if is_json { sc.to_json() } else { sc.to_human() };
607 if let Some(path) = output {
608 if let Err(e) = std::fs::write(&path, &rendered) {
609 eprintln!("Failed to write scorecard to {path}: {e}");
610 std::process::exit(1);
611 }
612 eprintln!("Wrote scorecard to {path}");
613 } else {
614 print!("{rendered}");
615 }
616 }
617 Err(e) => {
618 eprintln!("Scorecard failed: {e}");
619 std::process::exit(1);
620 }
621 }
622 }
623 "eval" => {
624 let path = args.get(1).map_or(".", std::string::String::as_str);
625 let is_json = args.iter().any(|a| a == "--json");
626 let root = std::path::Path::new(path);
627
628 let index = crate::core::bm25_index::BM25Index::build_from_directory(root);
629 let cfg = crate::core::hybrid_search::HybridConfig::from_config();
630 let queries = crate::core::eval_harness::generate_self_eval(&index, 50);
631
632 if queries.is_empty() {
633 eprintln!("No symbols found — cannot generate eval queries.");
634 std::process::exit(1);
635 }
636
637 let scorecard = crate::core::eval_harness::run_eval(root, &queries, &index, &cfg);
638 if is_json {
639 if let Ok(json) = serde_json::to_string_pretty(&scorecard) {
640 println!("{json}");
641 }
642 } else {
643 print!("{scorecard}");
644 }
645 }
646 "eval-ab" => {
647 let path = args
648 .get(1)
649 .filter(|a| !a.starts_with("--"))
650 .map_or(".", std::string::String::as_str);
651 let is_json = args.iter().any(|a| a == "--json");
652 let root = std::path::Path::new(path);
653 if !root.exists() {
654 eprintln!("Path does not exist: {path}");
655 std::process::exit(1);
656 }
657
658 let index = crate::core::bm25_index::BM25Index::build_from_directory(root);
659 let cfg = crate::core::hybrid_search::HybridConfig::from_config();
660
661 let queries = match parse_flag_value(args, "--suite") {
662 Some(suite) => {
663 match crate::core::eval_harness::load_suite(std::path::Path::new(&suite)) {
664 Ok(q) => q,
665 Err(e) => {
666 eprintln!("Failed to load suite {suite}: {e}");
667 std::process::exit(1);
668 }
669 }
670 }
671 None => crate::core::eval_harness::generate_self_eval(&index, 50),
672 };
673
674 if queries.is_empty() {
675 eprintln!("No eval queries (empty suite / no symbols indexed).");
676 std::process::exit(1);
677 }
678
679 let report = crate::core::eval_harness::run_ab(root, &queries, &index, &cfg);
680 if is_json {
681 println!("{}", report.to_json());
682 } else {
683 print!("{report}");
684 }
685 }
686 "run" => {
687 let path = args.get(1).map_or(".", std::string::String::as_str);
688 let is_json = args.iter().any(|a| a == "--json");
689
690 let result = benchmark::run_project_benchmark(path);
691 if is_json {
692 println!("{}", benchmark::format_json(&result));
693 } else {
694 println!("{}", benchmark::format_terminal(&result));
695 }
696 }
697 "report" => {
698 let path = args.get(1).map_or(".", std::string::String::as_str);
699 let result = benchmark::run_project_benchmark(path);
700 println!("{}", benchmark::format_markdown(&result));
701 }
702 "compare" => {
703 let repo = parse_flag_value(args, "--repo").unwrap_or_else(|| ".".to_string());
704 let output = parse_flag_value(args, "--output");
705
706 let root = std::path::Path::new(&repo);
707 if !root.exists() {
708 eprintln!("Repository path does not exist: {repo}");
709 std::process::exit(1);
710 }
711
712 let report = benchmark_compare::run_compare(root, output.as_deref());
713
714 println!("{}", benchmark_compare::report::generate_terminal(&report));
715
716 if output.is_none() {
717 eprintln!("Tip: use --output BENCHMARKS.md to save the full markdown report");
718 }
719 }
720 _ => {
721 if std::path::Path::new(action).exists() {
722 let result = benchmark::run_project_benchmark(action);
723 println!("{}", benchmark::format_terminal(&result));
724 } else {
725 eprintln!("Usage: lean-ctx benchmark run [path] [--json]");
726 eprintln!(" lean-ctx benchmark report [path]");
727 eprintln!(" lean-ctx benchmark eval [path] [--json]");
728 eprintln!(
729 " lean-ctx benchmark eval-ab [path] [--suite file.ndjson] [--json]"
730 );
731 eprintln!(" lean-ctx benchmark compare [--repo path] [--output file.md]");
732 eprintln!(" lean-ctx benchmark scorecard [--json] [--output file]");
733 std::process::exit(1);
734 }
735 }
736 }
737}
738
739fn parse_flag_value(args: &[String], flag: &str) -> Option<String> {
740 args.iter()
741 .position(|a| a == flag)
742 .and_then(|i| args.get(i + 1))
743 .cloned()
744}
745
746pub fn cmd_stats(args: &[String]) {
747 match args.first().map(std::string::String::as_str) {
748 Some("reset-cep") => {
749 crate::core::stats::reset_cep();
750 println!("CEP stats reset. Shell hook data preserved.");
751 }
752 Some("json") => {
753 let store = crate::core::stats::load();
754 println!(
755 "{}",
756 serde_json::to_string_pretty(&store).unwrap_or_else(|_| "{}".to_string())
757 );
758 }
759 _ => {
760 let store = crate::core::stats::load();
761 let input_saved = store
762 .total_input_tokens
763 .saturating_sub(store.total_output_tokens);
764 let pct = if store.total_input_tokens > 0 {
765 input_saved as f64 / store.total_input_tokens as f64 * 100.0
766 } else {
767 0.0
768 };
769 println!("Commands: {}", store.total_commands);
770 println!("Input: {} tokens", store.total_input_tokens);
771 println!("Output: {} tokens", store.total_output_tokens);
772 println!("Saved: {input_saved} tokens ({pct:.1}%)");
773 println!();
774 println!("CEP sessions: {}", store.cep.sessions);
775 println!(
776 "CEP tokens: {} → {}",
777 store.cep.total_tokens_original, store.cep.total_tokens_compressed
778 );
779 println!();
780 println!("Subcommands: stats reset-cep | stats json");
781 }
782 }
783}
784
785pub fn cmd_cache(args: &[String]) {
786 use crate::core::cli_cache;
787 match args.first().map(std::string::String::as_str) {
788 Some("clear") => {
789 let count = cli_cache::clear();
790 println!("Cleared {count} cached entries.");
791 }
792 Some("reset") => {
793 let project_flag = args.get(1).map(std::string::String::as_str) == Some("--project");
794 if project_flag {
795 let root =
796 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root);
797 if let Some(root) = root {
798 let count = cli_cache::clear_project(&root);
799 println!("Reset {count} cache entries for project: {root}");
800 } else {
801 eprintln!("No active project root found. Start a session first.");
802 std::process::exit(1);
803 }
804 } else {
805 let count = cli_cache::clear();
806 println!("Reset all {count} cache entries.");
807 }
808 }
809 Some("stats") => {
810 let (hits, reads, entries) = cli_cache::stats();
811 let rate = if reads > 0 {
812 (hits as f64 / reads as f64 * 100.0).round() as u32
813 } else {
814 0
815 };
816 println!("CLI Cache Stats (lean-ctx read / lean-ctx grep):");
817 println!(" Entries: {entries}");
818 println!(" Reads: {reads}");
819 println!(" Hits: {hits}");
820 println!(" Hit Rate: {rate}%");
821
822 if let Ok(dir) = crate::core::paths::state_dir() {
823 let live_path = dir.join("mcp-live.json");
824 if let Ok(content) = std::fs::read_to_string(&live_path) {
825 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
826 let mcp_reads = val
827 .get("total_reads")
828 .and_then(serde_json::Value::as_u64)
829 .unwrap_or(0);
830 let mcp_hits = val
831 .get("cache_hits")
832 .and_then(serde_json::Value::as_u64)
833 .unwrap_or(0);
834 let mcp_saved = val
835 .get("tokens_saved")
836 .and_then(serde_json::Value::as_u64)
837 .unwrap_or(0);
838 let mcp_rate = if mcp_reads > 0 {
839 (mcp_hits as f64 / mcp_reads as f64 * 100.0).round() as u32
840 } else {
841 0
842 };
843 let updated = val
844 .get("updated_at")
845 .and_then(serde_json::Value::as_str)
846 .unwrap_or("unknown");
847 println!();
848 println!("MCP Session Cache (ctx_read via AI editor):");
849 println!(" Reads: {mcp_reads}");
850 println!(" Hits: {mcp_hits}");
851 println!(" Hit Rate: {mcp_rate}%");
852 println!(" Tokens Saved: {mcp_saved}");
853 println!(" Last Updated: {updated}");
854 }
855 } else {
856 println!();
857 println!(
858 "MCP Session Cache: no data yet (start a session with your AI editor)"
859 );
860 }
861 }
862 }
863 Some("invalidate") => {
864 if args.len() < 2 {
865 eprintln!("Usage: lean-ctx cache invalidate <path>");
866 std::process::exit(1);
867 }
868 cli_cache::invalidate(&args[1]);
869 println!("Invalidated cache for {}", args[1]);
870 }
871 Some("prune") => {
872 let bm25 = prune_bm25_caches();
873 let graph = prune_graph_caches();
874 let archive_before = crate::core::archive::disk_usage_bytes()
877 + crate::core::archive_fts::db_size_bytes();
878 let archive_removed = crate::core::archive::cleanup();
879 let _ = crate::core::archive_fts::enforce_cap();
880 let archive_after = crate::core::archive::disk_usage_bytes()
881 + crate::core::archive_fts::db_size_bytes();
882 let archive_freed = archive_before.saturating_sub(archive_after);
883
884 let orphans = crate::core::knowledge::maintenance::prune_orphaned_stores();
888
889 let removed = bm25.removed + graph.removed + archive_removed + orphans.removed as u32;
890 let freed =
891 bm25.bytes_freed + graph.bytes_freed + archive_freed + orphans.reclaimed_bytes;
892 println!(
893 "Pruned {} entries, freed {:.1} MB (BM25: {}, graphs: {}, archive: {}, orphaned stores: {})",
894 removed,
895 freed as f64 / 1_048_576.0,
896 bm25.removed,
897 graph.removed,
898 archive_removed,
899 orphans.removed,
900 );
901 }
902 _ => {
903 let (hits, reads, entries) = cli_cache::stats();
904 let rate = if reads > 0 {
905 (hits as f64 / reads as f64 * 100.0).round() as u32
906 } else {
907 0
908 };
909 println!("CLI File Cache: {entries} entries, {hits}/{reads} hits ({rate}%)");
910 println!();
911 println!("Subcommands:");
912 println!(" cache stats Show detailed stats");
913 println!(" cache clear Clear all cached entries");
914 println!(" cache reset Reset all cache (or --project for current project only)");
915 println!(" cache invalidate Remove specific file from cache");
916 println!(
917 " cache prune Reclaim BM25 + graph indexes, archive, and orphaned knowledge stores"
918 );
919 }
920 }
921}
922
923pub struct PruneResult {
924 pub scanned: u32,
925 pub removed: u32,
926 pub bytes_freed: u64,
927}
928
929pub fn prune_bm25_caches() -> PruneResult {
930 let mut result = PruneResult {
931 scanned: 0,
932 removed: 0,
933 bytes_freed: 0,
934 };
935
936 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
937 return result;
938 };
939 let vectors_dir = data_dir.join("vectors");
940 let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
941 return result;
942 };
943
944 let max_bytes = crate::core::config::Config::load().bm25_max_cache_mb_effective() * 1024 * 1024;
945
946 for entry in entries.flatten() {
947 let dir = entry.path();
948 if !dir.is_dir() {
949 continue;
950 }
951 result.scanned += 1;
952
953 for q_name in &[
954 "bm25_index.json.quarantined",
955 "bm25_index.bin.quarantined",
956 "bm25_index.bin.zst.quarantined",
957 ] {
958 let quarantined = dir.join(q_name);
959 if quarantined.exists() {
960 if let Ok(meta) = std::fs::metadata(&quarantined) {
961 result.bytes_freed += meta.len();
962 }
963 let _ = std::fs::remove_file(&quarantined);
964 result.removed += 1;
965 println!(" Removed quarantined: {}", quarantined.display());
966 }
967 }
968
969 let index_path = if dir.join("bm25_index.bin.zst").exists() {
970 dir.join("bm25_index.bin.zst")
971 } else if dir.join("bm25_index.bin").exists() {
972 dir.join("bm25_index.bin")
973 } else {
974 dir.join("bm25_index.json")
975 };
976 if let Ok(meta) = std::fs::metadata(&index_path)
977 && meta.len() > max_bytes
978 {
979 result.bytes_freed += meta.len();
980 let _ = std::fs::remove_file(&index_path);
981 result.removed += 1;
982 println!(
983 " Removed oversized ({:.1} MB): {}",
984 meta.len() as f64 / 1_048_576.0,
985 index_path.display()
986 );
987 }
988
989 let marker = dir.join("project_root.txt");
990 if let Ok(root_str) = std::fs::read_to_string(&marker) {
991 let root_path = std::path::Path::new(root_str.trim());
992 if !root_path.exists() {
993 let freed = dir_size(&dir);
994 result.bytes_freed += freed;
995 let _ = std::fs::remove_dir_all(&dir);
996 result.removed += 1;
997 println!(
998 " Removed orphaned ({:.1} MB, project gone: {}): {}",
999 freed as f64 / 1_048_576.0,
1000 root_str.trim(),
1001 dir.display()
1002 );
1003 }
1004 }
1005 }
1006
1007 result
1008}
1009
1010pub fn prune_graph_caches() -> PruneResult {
1011 let mut result = PruneResult {
1012 scanned: 0,
1013 removed: 0,
1014 bytes_freed: 0,
1015 };
1016
1017 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1018 return result;
1019 };
1020 let graphs_dir = data_dir.join("graphs");
1021 let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
1022 return result;
1023 };
1024
1025 for entry in entries.flatten() {
1026 let dir = entry.path();
1027 if !dir.is_dir() {
1028 continue;
1029 }
1030 result.scanned += 1;
1031
1032 let meta_file = dir.join("graph.meta.json");
1036 let db_file = dir.join("graph.db");
1037 if !meta_file.exists() && !db_file.exists() {
1038 continue;
1039 }
1040
1041 let root_from_meta = try_read_project_root_from_graph(&meta_file);
1042 if let Some(root) = root_from_meta
1043 && !root.is_empty()
1044 && !std::path::Path::new(&root).exists()
1045 {
1046 let freed = dir_size(&dir);
1047 result.bytes_freed += freed;
1048 let _ = std::fs::remove_dir_all(&dir);
1049 result.removed += 1;
1050 println!(
1051 " Removed orphaned graph ({:.1} MB, project gone: {}): {}",
1052 freed as f64 / 1_048_576.0,
1053 root,
1054 dir.display()
1055 );
1056 continue;
1057 }
1058
1059 if let Ok(meta) = std::fs::metadata(&db_file)
1063 && meta.len() > 100 * 1024 * 1024
1064 {
1065 let freed = dir_size(&dir);
1066 result.bytes_freed += freed;
1067 let _ = std::fs::remove_dir_all(&dir);
1068 result.removed += 1;
1069 println!(
1070 " Removed oversized graph ({:.1} MB): {}",
1071 freed as f64 / 1_048_576.0,
1072 dir.display()
1073 );
1074 }
1075 }
1076
1077 result
1078}
1079
1080fn try_read_project_root_from_graph(path: &std::path::Path) -> Option<String> {
1083 let content = std::fs::read_to_string(path).ok()?;
1084 let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1085 val.get("project_root")?.as_str().map(String::from)
1086}
1087
1088pub const SIMPLIFIED_TEMPLATE: &str = r#"# lean-ctx — Simplified Configuration
1089# Full reference: https://leanctx.com/docs/configuration
1090# For all settings: lean-ctx config init --full
1091
1092# ── High-Level Knobs ─────────────────────────────────────────────────
1093# These auto-adjust advanced settings. Override individual values below
1094# only if you need fine-grained control.
1095
1096# Output style for the model's prose (not tool-output compression):
1097# off — no style guidance
1098# lite — plain-English concise (default; readable, still token-saving)
1099# standard / max — denser symbolic "power modes" (opt-in)
1100compression_level = "lite"
1101
1102# RAM/feature trade-off: low | balanced | performance
1103memory_profile = "balanced"
1104
1105# Maximum % of system RAM lean-ctx may use (1-50)
1106max_ram_percent = 5
1107
1108# Total disk budget in MB (0 = use individual limits).
1109# Distributes proportionally: archive ~25%, BM25 cache ~10%.
1110# max_disk_mb = 2000
1111
1112# Auto-purge data older than N days (0 = disabled).
1113# Flows into archive.max_age_hours.
1114# max_staleness_days = 30
1115
1116# Explicit project paths to scan/index (default: auto-detect).
1117# [ide_paths]
1118# cursor = ["/home/user/projects/app1"]
1119
1120# ── Proxy ────────────────────────────────────────────────────────────
1121# proxy_enabled = false
1122# proxy_port = 3128
1123"#;
1124
1125fn write_simplified_config() -> Result<String, String> {
1126 let path = config::Config::path().ok_or_else(|| "Cannot determine config path".to_string())?;
1127 if let Some(dir) = path.parent() {
1128 std::fs::create_dir_all(dir).map_err(|e| format!("{e}"))?;
1129 }
1130 std::fs::write(&path, SIMPLIFIED_TEMPLATE).map_err(|e| format!("{e}"))?;
1131 Ok(path.to_string_lossy().to_string())
1132}
1133
1134fn cmd_show_effective() {
1135 let cfg = config::Config::load();
1136 let compression = config::CompressionLevel::effective(&cfg);
1137 let policy = cfg.memory_policy_effective().unwrap_or_default();
1138
1139 println!("╭─── Simplified (high-level) ───────────────────────────────╮");
1140 println!(
1141 "│ compression_level = {:10} {}",
1142 format!("{compression:?}"),
1143 source_hint(
1144 "LEAN_CTX_COMPRESSION",
1145 cfg.compression_level != config::CompressionLevel::Off
1146 )
1147 );
1148 println!(
1149 "│ max_disk_mb = {:10} {}",
1150 cfg.max_disk_mb_effective(),
1151 source_hint("LEAN_CTX_MAX_DISK_MB", cfg.max_disk_mb > 0)
1152 );
1153 println!(
1154 "│ max_ram_percent = {:10} {}",
1155 cfg.max_ram_percent,
1156 source_hint("LEAN_CTX_MAX_RAM_PERCENT", cfg.max_ram_percent != 5)
1157 );
1158 println!(
1159 "│ max_staleness_days = {:10} {}",
1160 cfg.max_staleness_days_effective(),
1161 source_hint("LEAN_CTX_MAX_STALENESS_DAYS", cfg.max_staleness_days > 0)
1162 );
1163 println!(
1164 "│ memory_profile = {:10} {}",
1165 format!("{:?}", cfg.memory_profile),
1166 source_hint("LEAN_CTX_MEMORY_PROFILE", false)
1167 );
1168 println!("╰────────────────────────────────────────────────────────────╯");
1169
1170 println!();
1171 println!("╭─── Derived effective limits ────────────────────────────────╮");
1172 println!(
1173 "│ archive_max_disk_mb = {:>6} MB",
1174 cfg.archive_max_disk_mb_effective()
1175 );
1176 println!(
1177 "│ bm25_max_cache_mb = {:>6} MB",
1178 cfg.bm25_max_cache_mb_effective()
1179 );
1180 println!(
1181 "│ archive_max_age_hours = {:>6} h",
1182 cfg.archive_max_age_hours_effective()
1183 );
1184 println!(
1185 "│ graph_index_max_files = {:>6}",
1186 cfg.graph_index_max_files
1187 );
1188 println!("│");
1189 println!(
1190 "│ memory.knowledge.max_facts = {:>6}",
1191 policy.knowledge.max_facts
1192 );
1193 println!(
1194 "│ memory.knowledge.max_patterns = {:>6}",
1195 policy.knowledge.max_patterns
1196 );
1197 println!(
1198 "│ memory.episodic.max_episodes = {:>6}",
1199 policy.episodic.max_episodes
1200 );
1201 println!(
1202 "│ memory.procedural.max_procedures = {:>4}",
1203 policy.procedural.max_procedures
1204 );
1205 println!("╰────────────────────────────────────────────────────────────╯");
1206
1207 if cfg.max_disk_mb_effective() > 0 {
1208 println!();
1209 println!(
1210 " ℹ max_disk_mb={} → limits scaled proportionally (factor: {:.1}x)",
1211 cfg.max_disk_mb_effective(),
1212 (cfg.max_disk_mb_effective() as f64 / 500.0).clamp(0.5, 10.0)
1213 );
1214 }
1215}
1216
1217fn source_hint(env_var: &str, config_set: bool) -> &'static str {
1218 if std::env::var(env_var).is_ok() {
1219 "← env"
1220 } else if config_set {
1221 "← config"
1222 } else {
1223 "← default"
1224 }
1225}
1226
1227fn dir_size(path: &std::path::Path) -> u64 {
1228 let mut total = 0u64;
1229 if let Ok(entries) = std::fs::read_dir(path) {
1230 for entry in entries.flatten() {
1231 let p = entry.path();
1232 if p.is_file() {
1233 total += std::fs::metadata(&p).map_or(0, |m| m.len());
1234 } else if p.is_dir() {
1235 total += dir_size(&p);
1236 }
1237 }
1238 }
1239 total
1240}
1241
1242#[cfg(test)]
1243mod tests {
1244 use super::*;
1245
1246 fn merged_max_ram(cfg: &config::Config, existing: &str) -> u8 {
1250 let dir = tempfile::tempdir().unwrap();
1251 let path = dir.path().join("config.toml");
1252 std::fs::write(&path, existing).unwrap();
1253 let new_content = toml::to_string_pretty(cfg).unwrap();
1254 let baseline = toml::from_str::<config::Config>("").unwrap();
1255 let defaults = toml::to_string_pretty(&baseline).unwrap();
1256 crate::config_io::write_toml_preserving_minimal(&path, &new_content, &defaults).unwrap();
1257 let written = std::fs::read_to_string(&path).unwrap();
1258 toml::from_str::<config::Config>(&written)
1259 .unwrap()
1260 .max_ram_percent
1261 }
1262
1263 #[test]
1264 fn full_init_uses_existing_values_not_defaults() {
1265 let existing = "max_ram_percent = 30\ncompression_level = \"standard\"\n";
1266 let cfg = config_for_full_init(Some(existing)).expect("parse existing");
1267 assert_eq!(cfg.max_ram_percent, 30, "must keep the user's value, not 5");
1268 assert_eq!(cfg.compression_level, config::CompressionLevel::Standard);
1269 }
1270
1271 #[test]
1272 fn full_init_falls_back_to_defaults_on_fresh_install() {
1273 let cfg = config_for_full_init(None).expect("default");
1274 assert_eq!(
1275 cfg.max_ram_percent,
1276 config::Config::default().max_ram_percent
1277 );
1278 let cfg_empty = config_for_full_init(Some(" \n")).expect("blank -> default");
1279 assert_eq!(
1280 cfg_empty.max_ram_percent,
1281 config::Config::default().max_ram_percent
1282 );
1283 }
1284
1285 #[test]
1286 fn full_init_refuses_unparseable_config() {
1287 assert!(config_for_full_init(Some("max_ram_percent = = =")).is_err());
1288 }
1289
1290 #[test]
1292 fn full_init_preserves_value_through_save_merge() {
1293 let existing = "max_ram_percent = 30\n";
1294 let cfg = config_for_full_init(Some(existing)).unwrap();
1295 assert_eq!(
1296 merged_max_ram(&cfg, existing),
1297 30,
1298 "user value must survive `config init --full`"
1299 );
1300 }
1301
1302 #[test]
1306 fn default_seed_resets_value_root_cause_marker() {
1307 let existing = "max_ram_percent = 30\n";
1308 assert_eq!(
1309 merged_max_ram(&config::Config::default(), existing),
1310 5,
1311 "default seed resets to 5 — the #443 regression we fixed"
1312 );
1313 }
1314}