1use crate::{
2 core, doctor, heatmap, hook_handlers, report, setup, shell, status, token_report, uninstall,
3};
4
5mod analytics;
6mod help;
7mod lifecycle;
8mod network;
9mod server;
10
11#[allow(clippy::wildcard_imports)]
12use analytics::*;
13#[allow(clippy::wildcard_imports)]
14use help::*;
15#[allow(clippy::wildcard_imports)]
16use lifecycle::*;
17#[allow(clippy::wildcard_imports)]
18use network::*;
19#[allow(clippy::wildcard_imports)]
20use server::*;
21
22pub fn run() {
23 let mut args: Vec<String> = std::env::args().collect();
24
25 if args.get(1).is_some_and(|a| a == "(deleted)") {
29 args.remove(1);
30 }
31
32 if !is_server_mode(&args) {
33 restore_sigpipe_default();
34 }
35
36 let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
37 if !enters_mcp {
38 crate::core::logging::init_logging();
39 }
40
41 if args.len() > 1 {
42 let rest = args[2..].to_vec();
43
44 match args[1].as_str() {
45 "-c" | "exec" => {
46 let raw = rest.first().is_some_and(|a| a == "--raw");
47 let cmd_args = if raw { &args[3..] } else { &args[2..] };
48 let command = if cmd_args.len() == 1 {
49 cmd_args[0].clone()
50 } else {
51 shell::join_command(cmd_args)
52 };
53 core::agent_runtime_env::capture();
57 if std::env::var("LEAN_CTX_ACTIVE").is_ok()
58 || std::env::var("LEAN_CTX_DISABLED").is_ok()
59 {
60 passthrough(&command);
61 }
62 if raw {
63 unsafe { std::env::set_var("LEAN_CTX_RAW", "1") };
66 } else {
67 unsafe { std::env::set_var("LEAN_CTX_COMPRESS", "1") };
70 }
71 let code = shell::exec(&command);
72 core::stats::flush();
73 core::heatmap::flush();
74 core::path_mode_memory::flush();
75 core::auto_mode_resolver::flush_sources();
76 std::process::exit(code);
77 }
78 "-t" | "--track" => {
79 let cmd_args = &args[2..];
80 let code = if cmd_args.len() > 1 {
81 shell::exec_argv(cmd_args)
82 } else {
83 let command = cmd_args[0].clone();
84 if std::env::var("LEAN_CTX_ACTIVE").is_ok()
85 || std::env::var("LEAN_CTX_DISABLED").is_ok()
86 {
87 passthrough(&command);
88 }
89 shell::exec(&command)
90 };
91 core::stats::flush();
92 core::heatmap::flush();
93 core::path_mode_memory::flush();
94 core::auto_mode_resolver::flush_sources();
95 std::process::exit(code);
96 }
97 "shell" | "--shell" => {
98 shell::interactive();
99 return;
100 }
101 "gain" => {
102 cmd_gain(&rest);
103 return;
104 }
105 "savings" => {
106 cmd_savings(&rest);
107 return;
108 }
109 "learning" => {
110 cmd_learning(&rest);
111 return;
112 }
113 "conformance" | "selftest" => {
114 cmd_conformance(&rest);
115 return;
116 }
117 "billing" => {
118 cmd_billing(&rest);
119 return;
120 }
121 "finops" => {
122 cmd_finops(&rest);
123 return;
124 }
125 "roi" => {
126 super::cmd_roi(&rest);
129 return;
130 }
131 "token-report" | "report-tokens" => {
132 let code = token_report::run_cli(&rest);
133 if code != 0 {
134 std::process::exit(code);
135 }
136 return;
137 }
138 "pack" => {
139 crate::cli::cmd_pack(&rest);
140 return;
141 }
142 "policy" => {
143 crate::cli::cmd_policy(&rest);
144 return;
145 }
146 "plugin" | "plugins" => {
147 crate::cli::plugin_cmd::cmd_plugin(&rest);
148 return;
149 }
150 "rules" => {
151 crate::cli::rules_cmd::cmd_rules(&rest);
152 return;
153 }
154 "proof" => {
155 crate::cli::cmd_proof(&rest);
156 return;
157 }
158 "verify" => {
159 crate::cli::cmd_verify(&rest);
160 return;
161 }
162 "eval" => {
163 crate::cli::eval_cmd::cmd_eval(&rest);
164 return;
165 }
166 "verify-cache" | "cache-selftest" => {
167 let code = crate::cli::verify_cache_cmd::cmd_verify_cache(&rest);
168 if code != 0 {
169 std::process::exit(code);
170 }
171 return;
172 }
173 "visualize" => {
174 super::cmd_visualize(&rest);
175 return;
176 }
177 "audit" => {
178 if rest.first().map(String::as_str) == Some("evidence") {
179 crate::cli::audit_report::cmd_evidence(&rest[1..]);
180 } else {
181 println!("{}", crate::cli::audit_report::generate_report());
182 }
183 return;
184 }
185 "agent" => {
186 crate::cli::cmd_agent(&rest);
187 return;
188 }
189 "instructions" => {
190 crate::cli::cmd_instructions(&rest);
191 return;
192 }
193 "index" => {
194 crate::cli::cmd_index(&rest);
195 return;
196 }
197 "semantic-search" | "search-code" => {
198 crate::cli::cmd_semantic_search(&rest);
199 core::stats::flush();
200 return;
201 }
202 "repomap" | "repo-map" => {
203 crate::cli::cmd_repomap(&rest);
204 core::stats::flush();
205 return;
206 }
207 "cep" => {
208 println!("{}", core::stats::format_cep_report());
209 return;
210 }
211 "dashboard" => {
212 cmd_dashboard(&rest);
213 return;
214 }
215 "team" => {
216 cmd_team(&rest);
217 return;
218 }
219 "provider" => {
220 cmd_provider(&rest);
221 return;
222 }
223 "serve" => {
224 cmd_serve(&rest);
225 return;
226 }
227 "watch" => {
228 cmd_watch(&rest);
229 return;
230 }
231 "proxy" => {
232 cmd_proxy(&rest);
233 return;
234 }
235 "daemon" => {
236 cmd_daemon(&rest);
237 return;
238 }
239 "init" => {
240 super::cmd_init(&rest);
241 return;
242 }
243 "setup" => {
244 let non_interactive = rest.iter().any(|a| a == "--non-interactive");
245 let yes = rest.iter().any(|a| a == "--yes" || a == "-y");
246 let fix = rest.iter().any(|a| a == "--fix");
247 let json = rest.iter().any(|a| a == "--json");
248 let no_auto_approve = rest.iter().any(|a| a == "--no-auto-approve");
249 let skip_rules = rest.iter().any(|a| a == "--skip-rules");
250
251 if non_interactive || fix || json || yes {
252 let opts = setup::SetupOptions {
253 non_interactive,
254 yes,
255 fix,
256 json,
257 no_auto_approve,
258 skip_rules,
259 ..Default::default()
260 };
261 match setup::run_setup_with_options(opts) {
262 Ok(report) => {
263 if json {
264 println!(
265 "{}",
266 serde_json::to_string_pretty(&report)
267 .unwrap_or_else(|_| "{}".to_string())
268 );
269 }
270 if !report.success {
271 std::process::exit(1);
272 }
273 }
274 Err(e) => {
275 eprintln!("{e}");
276 std::process::exit(1);
277 }
278 }
279 } else {
280 setup::run_setup();
281 }
282 return;
283 }
284 "onboard" => {
285 setup::run_onboard();
286 return;
287 }
288 "install" => {
289 let repair = rest.iter().any(|a| a == "--repair" || a == "--fix");
294 let json = rest.iter().any(|a| a == "--json");
295 if !repair {
296 setup::run_setup();
297 return;
298 }
299 let opts = setup::SetupOptions {
300 non_interactive: true,
301 yes: true,
302 fix: true,
303 json,
304 ..Default::default()
305 };
306 match setup::run_setup_with_options(opts) {
307 Ok(report) => {
308 if json {
309 println!(
310 "{}",
311 serde_json::to_string_pretty(&report)
312 .unwrap_or_else(|_| "{}".to_string())
313 );
314 }
315 if !report.success {
316 std::process::exit(1);
317 }
318 }
319 Err(e) => {
320 eprintln!("{e}");
321 std::process::exit(1);
322 }
323 }
324 return;
325 }
326 "bootstrap" => {
327 let json = rest.iter().any(|a| a == "--json");
328 let opts = setup::SetupOptions {
329 non_interactive: true,
330 yes: true,
331 fix: true,
332 json,
333 ..Default::default()
334 };
335 match setup::run_setup_with_options(opts) {
336 Ok(report) => {
337 if json {
338 println!(
339 "{}",
340 serde_json::to_string_pretty(&report)
341 .unwrap_or_else(|_| "{}".to_string())
342 );
343 }
344 if !report.success {
345 std::process::exit(1);
346 }
347 }
348 Err(e) => {
349 eprintln!("{e}");
350 std::process::exit(1);
351 }
352 }
353 return;
354 }
355 "status" => {
356 let code = status::run_cli(&rest);
357 if code != 0 {
358 std::process::exit(code);
359 }
360 return;
361 }
362 "read" => {
363 super::cmd_read(&rest);
364 core::stats::flush();
365 return;
366 }
367 "call" => {
368 super::cmd_call(&rest);
369 return;
370 }
371 "diff" => {
372 super::cmd_diff(&rest);
373 core::stats::flush();
374 return;
375 }
376 "grep" => {
377 super::cmd_grep(&rest);
378 core::stats::flush();
379 return;
380 }
381 "find" => {
382 super::cmd_find(&rest);
383 core::stats::flush();
384 return;
385 }
386 "ls" => {
387 super::cmd_ls(&rest);
388 core::stats::flush();
389 return;
390 }
391 "deps" => {
392 super::cmd_deps(&rest);
393 core::stats::flush();
394 return;
395 }
396 "discover" => {
397 super::cmd_discover(&rest);
398 return;
399 }
400 "ghost" => {
401 super::cmd_ghost(&rest);
402 return;
403 }
404 "filter" => {
405 super::cmd_filter(&rest);
406 return;
407 }
408 "heatmap" => {
409 heatmap::cmd_heatmap(&rest);
410 return;
411 }
412 "graph" => {
413 cmd_graph(&rest);
414 return;
415 }
416 "smells" => {
417 cmd_smells(&rest);
418 return;
419 }
420 "session" => {
421 super::cmd_session_action(&rest);
422 return;
423 }
424 "ledger" => {
425 super::cmd_ledger(&rest);
426 return;
427 }
428 "control" | "context-control" => {
429 super::cmd_control(&rest);
430 return;
431 }
432 "plan" | "context-plan" => {
433 super::cmd_plan(&rest);
434 return;
435 }
436 "compile" | "context-compile" => {
437 super::cmd_compile(&rest);
438 return;
439 }
440 "knowledge" => {
441 super::cmd_knowledge(&rest);
442 return;
443 }
444 "skillify" => {
445 super::cmd_skillify(&rest);
446 return;
447 }
448 "summary" => {
449 super::cmd_summary(&rest);
450 return;
451 }
452 "overview" => {
453 super::cmd_overview(&rest);
454 return;
455 }
456 "compress" => {
457 super::cmd_compress(&rest);
458 return;
459 }
460 "wrapped" => {
461 eprintln!("'lean-ctx wrapped' has been removed. Use: lean-ctx gain --wrapped");
462 std::process::exit(1);
463 }
464 "sessions" | "session-store" => {
465 super::cmd_sessions(&rest);
466 return;
467 }
468 "benchmark" => {
469 super::cmd_benchmark(&rest);
470 return;
471 }
472 "compact" => {
473 cmd_compact(&rest);
474 return;
475 }
476 "profile" => {
477 super::cmd_profile(&rest);
478 return;
479 }
480 "tools" => {
481 let mut forwarded = vec!["tools".to_string()];
485 forwarded.extend(rest.iter().cloned());
486 super::cmd_profile(&forwarded);
487 return;
488 }
489 "config" => {
490 super::cmd_config(&rest);
491 return;
492 }
493 "allow" => {
494 super::cmd_allow(&rest);
495 return;
496 }
497 "stats" => {
498 super::cmd_stats(&rest);
499 return;
500 }
501 "cache" => {
502 super::cmd_cache(&rest);
503 return;
504 }
505 "theme" => {
506 super::cmd_theme(&rest);
507 return;
508 }
509 "tee" => {
510 super::cmd_tee(&rest);
511 return;
512 }
513 "terse" | "compression" => {
514 super::cmd_compression(&rest);
515 return;
516 }
517 "slow-log" => {
518 super::cmd_slow_log(&rest);
519 return;
520 }
521 "editor-signal" => {
524 let file = rest
525 .iter()
526 .position(|a| a == "--file")
527 .and_then(|i| rest.get(i + 1));
528 if let Some(path) = file {
529 if let Err(e) = core::editor_signal::record_focus(path) {
530 eprintln!("editor-signal: {e}");
531 std::process::exit(1);
532 }
533 } else {
534 eprintln!("usage: lean-ctx editor-signal --file <path>");
535 std::process::exit(2);
536 }
537 return;
538 }
539 "update" | "--self-update" => {
540 core::updater::run(&rest);
541 return;
542 }
543 "restart" => {
544 cmd_restart();
545 return;
546 }
547 "stop" => {
548 cmd_stop();
549 return;
550 }
551 "dev-install" => {
552 cmd_dev_install();
553 return;
554 }
555 "codesign-setup" => {
556 cmd_codesign_setup();
557 return;
558 }
559 "doctor" => {
560 let code = doctor::run_cli(&rest);
561 if code != 0 {
562 std::process::exit(code);
563 }
564 return;
565 }
566 "harden" => {
567 super::harden::run(&rest);
568 return;
569 }
570 "export-rules" => {
571 super::export_rules::run(&rest);
572 return;
573 }
574 "gotchas" | "bugs" => {
575 super::cloud::cmd_gotchas(&rest);
576 return;
577 }
578 "learn" => {
579 super::cmd_learn(&rest);
580 return;
581 }
582 "buddy" | "pet" => {
583 super::cloud::cmd_buddy(&rest);
584 return;
585 }
586 "hook" => {
587 hook_handlers::mark_hook_environment();
588 core::agent_runtime_env::capture();
592 hook_handlers::arm_watchdog(std::time::Duration::from_secs(5));
593 let action = rest.first().map_or("help", std::string::String::as_str);
594 match action {
595 "rewrite" => hook_handlers::handle_rewrite(),
596 "redirect" => hook_handlers::handle_redirect(),
597 "observe" => hook_handlers::handle_observe(),
598 "copilot" => hook_handlers::handle_copilot(),
599 "codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
600 "codex-session-start" => hook_handlers::handle_codex_session_start(),
601 "rewrite-inline" => hook_handlers::handle_rewrite_inline(),
602 _ => {
603 eprintln!(
604 "Usage: lean-ctx hook <rewrite|redirect|observe|copilot|codex-pretooluse|codex-session-start|rewrite-inline>"
605 );
606 eprintln!(
607 " Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)"
608 );
609 std::process::exit(1);
610 }
611 }
612 return;
613 }
614 "report-issue" | "report" => {
615 report::run(&rest);
616 return;
617 }
618 "uninstall" => {
619 let dry_run = rest.iter().any(|a| a == "--dry-run");
620 let keep_config = rest.iter().any(|a| a == "--keep-config");
621 let keep_binary = rest.iter().any(|a| a == "--keep-binary");
622 uninstall::run(dry_run, keep_config, keep_binary);
623 return;
624 }
625 "bypass" => {
626 if rest.is_empty() {
627 eprintln!("Usage: lean-ctx bypass \"command\"");
628 eprintln!("Runs the command with zero compression (raw passthrough).");
629 std::process::exit(1);
630 }
631 let command = if rest.len() == 1 {
632 rest[0].clone()
633 } else {
634 shell::join_command(&args[2..])
635 };
636 unsafe { std::env::set_var("LEAN_CTX_RAW", "1") };
639 let code = shell::exec(&command);
640 std::process::exit(code);
641 }
642 "safety-levels" | "safety" => {
643 println!("{}", core::compression_safety::format_safety_table());
644 return;
645 }
646 "cheat" | "cheatsheet" | "cheat-sheet" => {
647 super::cmd_cheatsheet();
648 return;
649 }
650 "login" => {
651 super::cloud::cmd_login(&rest);
652 return;
653 }
654 "register" => {
655 super::cloud::cmd_register(&rest);
656 return;
657 }
658 "forgot-password" => {
659 super::cloud::cmd_forgot_password(&rest);
660 return;
661 }
662 "sync" => {
663 super::cloud::cmd_sync(&rest);
664 return;
665 }
666 "contribute" => {
667 super::cloud::cmd_contribute();
668 return;
669 }
670 "cloud" => {
671 super::cloud::cmd_cloud(&rest);
672 return;
673 }
674 "upgrade" => {
675 super::cloud::cmd_upgrade();
676 return;
677 }
678 "--version" | "-V" => {
679 println!("{}", core::integrity::origin_line());
680 return;
681 }
682 "help" => {
683 let want_all = rest
684 .iter()
685 .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
686 if want_all {
687 print_help();
688 } else {
689 print_help_concise();
690 }
691 return;
692 }
693 "--help" | "-h" => {
694 if rest
695 .iter()
696 .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
697 {
698 print_help();
699 } else {
700 print_help_concise();
701 }
702 return;
703 }
704 "mcp" => {}
705 _ => {
706 tracing::error!("lean-ctx: unknown command '{}'", args[1]);
707 print_help_concise();
708 std::process::exit(1);
709 }
710 }
711 }
712
713 if args.len() == 1 && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
719 print_quickstart();
720 return;
721 }
722
723 if let Err(e) = run_mcp_server() {
724 tracing::error!("lean-ctx: {e}");
725 std::process::exit(1);
726 }
727}
728
729fn is_server_mode(args: &[String]) -> bool {
733 args.len() == 1
734 || args.get(1).is_some_and(|a| {
735 matches!(
736 a.as_str(),
737 "mcp" | "daemon" | "proxy" | "serve" | "watch" | "dashboard"
738 )
739 })
740}
741
742#[cfg(unix)]
752fn restore_sigpipe_default() {
753 unsafe {
756 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
757 }
758}
759
760#[cfg(not(unix))]
761fn restore_sigpipe_default() {}
762
763fn passthrough(command: &str) -> ! {
764 let (shell, flag) = shell::shell_and_flag();
765 let mut cmd = std::process::Command::new(&shell);
766 cmd.arg(&flag).arg(command).env("LEAN_CTX_ACTIVE", "1");
767 shell::platform::apply_utf8_locale(&mut cmd);
768 let status = cmd.status().map_or(127, |s| s.code().unwrap_or(1));
769 std::process::exit(status);
770}
771
772pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
773 tokio::runtime::Runtime::new()
774 .expect("failed to create async runtime")
775 .block_on(future)
776}
777
778#[cfg(test)]
779mod tests {
780 use super::*;
781 use serial_test::serial;
782
783 fn args_of(parts: &[&str]) -> Vec<String> {
784 parts.iter().map(|s| (*s).to_string()).collect()
785 }
786
787 #[test]
788 fn server_modes_keep_ignored_sigpipe() {
789 for mode in ["mcp", "daemon", "proxy", "serve", "watch", "dashboard"] {
790 assert!(
791 is_server_mode(&args_of(&["lean-ctx", mode])),
792 "{mode} must count as server mode"
793 );
794 }
795 assert!(is_server_mode(&args_of(&["lean-ctx"])));
797 }
798
799 #[test]
800 fn cli_modes_restore_default_sigpipe() {
801 for mode in ["doctor", "-c", "status", "ls", "grep", "gain", "help"] {
802 assert!(
803 !is_server_mode(&args_of(&["lean-ctx", mode])),
804 "{mode} must count as CLI mode (SIGPIPE default)"
805 );
806 }
807 }
808
809 #[test]
810 fn quickstart_is_short_and_points_to_setup() {
811 let q = quickstart_text();
812 assert!(
813 q.contains("lean-ctx onboard"),
814 "quickstart must point to onboard"
815 );
816 assert!(q.contains("lean-ctx help"), "quickstart must point to help");
817 assert!(
819 q.lines().count() <= 16,
820 "quickstart should be short; got {} lines",
821 q.lines().count()
822 );
823 assert!(
824 !q.contains("COMMANDS:"),
825 "quickstart must not inline the full command reference"
826 );
827 }
828
829 #[test]
830 fn concise_help_is_short_and_points_to_full() {
831 let h = concise_help_text();
832 assert!(h.contains("lean-ctx onboard"), "must lead with onboard");
833 assert!(
834 h.contains("lean-ctx help all"),
835 "must point to full reference"
836 );
837 assert!(
838 h.contains("lean-ctx tools"),
839 "must surface the tools profile command"
840 );
841 assert!(
843 h.lines().count() <= 40,
844 "concise help should stay short; got {} lines",
845 h.lines().count()
846 );
847 assert!(
848 !h.contains("SHELL HOOK PATTERNS"),
849 "concise help must not inline the full pattern catalog"
850 );
851 }
852
853 #[test]
854 fn capability_banner_tool_count_matches_registry() {
855 let n = crate::server::registry::tool_count();
856 let banner = capability_banner();
857 assert!(
858 banner.contains(&format!("{n} MCP tools")),
859 "banner must show the live registry count ({n}); got: {banner}"
860 );
861 }
862
863 #[test]
864 #[serial]
865 fn worker_threads_default_clamps_low() {
866 crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
867 assert_eq!(resolve_worker_threads(1), 1);
868 }
869
870 #[test]
871 #[serial]
872 fn worker_threads_default_clamps_high() {
873 crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
874 assert_eq!(resolve_worker_threads(32), 4);
875 }
876
877 #[test]
878 #[serial]
879 fn worker_threads_default_passthrough() {
880 crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
881 assert_eq!(resolve_worker_threads(3), 3);
882 }
883
884 #[test]
885 #[serial]
886 fn worker_threads_env_override() {
887 crate::test_env::set_var("LEAN_CTX_WORKER_THREADS", "12");
888 assert_eq!(resolve_worker_threads(2), 12);
889 crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
890 }
891
892 #[test]
893 #[serial]
894 fn worker_threads_env_invalid_falls_back() {
895 crate::test_env::set_var("LEAN_CTX_WORKER_THREADS", "not_a_number");
896 assert_eq!(resolve_worker_threads(3), 3);
897 crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
898 }
899}