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