1use crate::{doctor, status, token_report, uninstall};
3use lean_ctx::{core, heatmap, report, shell};
4use lean_ctx_hooks::hook_handlers;
5
6pub mod analytics;
7mod app_hint;
8mod cmd_help;
9mod cockpit_hint;
10mod decisions_suggest;
11mod evidence;
12pub(crate) mod evidence_cost;
13mod evidence_landing;
14pub(crate) mod evidence_realworld;
15pub(crate) mod evidence_report;
16pub(crate) mod evidence_workflow;
17mod help;
18mod lifecycle;
19#[cfg(unix)]
20mod mcp_instances;
21mod network;
22mod server;
23mod setup_cmd;
24pub(crate) mod suggest;
25pub mod verify;
26
27#[allow(clippy::wildcard_imports)]
28use analytics::*;
29#[allow(clippy::wildcard_imports)]
30use help::*;
31#[allow(clippy::wildcard_imports)]
32use lifecycle::*;
33#[allow(clippy::wildcard_imports)]
34use network::*;
35#[allow(clippy::wildcard_imports)]
36use server::*;
37use setup_cmd::{handle_bootstrap, handle_install, handle_onboard, handle_setup};
38
39pub fn run() {
40 #[cfg(unix)]
44 if let Some(code) = shell::containment::dispatch_hidden_mode() {
45 std::process::exit(code);
46 }
47 #[cfg(windows)]
50 shell::process_tree::contain_requested_session();
51
52 lean_ctx::shell_hook::register_installed_hook_refresh(super::refresh_installed_shell_hooks);
55 lean_ctx_shell_policy::install();
58 lean_ctx_proxy::register_shapers();
59 lean_ctx_cloud::register_hooks();
60 lean_ctx_server::server::registry::register_tool_catalog();
63 lean_ctx_server::tools::ctx_read::register_conformance_renderer();
65 #[cfg(unix)]
68 lean_ctx_server::server::register_protected_shell_runner();
69
70 let mut args: Vec<String> = std::env::args().collect();
71
72 if args.get(1).is_some_and(|a| a == "(deleted)") {
76 args.remove(1);
77 }
78
79 match crate::cli::codex_protected_cmd::protected_gitlab_dispatch(&args) {
80 Ok(Some(code)) => std::process::exit(code),
81 Ok(None) => {}
82 Err(error) => {
83 eprintln!("Error: {error}");
84 std::process::exit(1);
85 }
86 }
87
88 if !is_server_mode(&args) {
89 restore_sigpipe_default();
90 }
91
92 let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
93 if !enters_mcp {
94 if is_server_mode(&args) {
95 lean_ctx::core::logging::init_logging();
96 } else {
97 lean_ctx::core::logging::init_cli_logging();
98 }
99 }
100 let help_only = args.len() > 1 && cmd_help::is_help_request(&args[1], &args[2..]);
103 if !enters_mcp
106 && !help_only
107 && !is_server_mode(&args)
108 && !matches!(args.get(1).map(String::as_str), Some("setup" | "telemetry"))
109 {
110 lean_ctx::core::telemetry_consent::maybe_show_notice();
111 lean_ctx::core::telemetry_notices::maybe_show();
112 lean_ctx::core::pathjail_scope::maybe_show_default_notice();
113 }
114 if !enters_mcp && !help_only && !is_server_mode(&args) {
116 lean_ctx::core::telemetry_features::record_cli(&args);
117 }
118
119 if args.len() > 1 {
120 let rest = args[2..].to_vec();
121
122 if let Some(usage) = cmd_help::guarded_help(&args[1], &rest) {
123 print!("{usage}");
124 return;
125 }
126 if let Some(notice) = cmd_help::removed_notice(&args[1]) {
127 eprintln!("{notice}");
128 std::process::exit(2);
129 }
130 if super::local_read::context_part::try_run(&args[1], &rest) {
134 return;
135 }
136 if super::local_read::task_receipt::try_run(&args[1], &rest) {
137 return;
138 }
139 if super::local_read::chat_part::try_run(&args[1], &rest) {
141 return;
142 }
143 if super::local_read::lease_part::try_run(&args[1], &rest) {
144 return;
145 }
146 if super::local_read::decisions_part::try_run(&args[1], &rest) {
147 return;
148 }
149 if super::local_read::members_part::try_run(&args[1], &rest) {
150 return;
151 }
152 if super::local_read::billing_topup::try_run(&args[1], &rest) {
155 return;
156 }
157 if super::local_read::billing_part::try_run(&args[1], &rest) {
159 return;
160 }
161 if super::local_read::cloud_models::try_run(&args[1], &rest) {
164 return;
165 }
166 if super::local_read::team_stop_part::try_run(&args[1], &rest) {
167 return;
168 }
169 if super::local_read::plan_part::try_run(&args[1], &rest) {
171 return;
172 }
173
174 if args[1] == "decisions"
177 && matches!(
178 rest.first().map(String::as_str),
179 Some("suggest" | "confirm")
180 )
181 {
182 let code = if rest[0] == "confirm" {
183 decisions_suggest::run_confirm(&rest[1..])
184 } else {
185 decisions_suggest::run(&rest[1..])
186 };
187 if code != 0 {
188 std::process::exit(code);
189 }
190 return;
191 }
192
193 match args[1].as_str() {
194 "-c" | "exec" => handle_exec(&args, &rest),
195 "-t" | "--track" => handle_track(&args),
196 "shell" | "--shell" => {
197 shell::interactive();
198 return;
199 }
200 "gain" => {
201 if super::local_read::usage::try_run("gain", &rest) {
203 return;
204 }
205 if let cockpit_hint::Handled::Text(hint) =
208 cockpit_hint::redirect(cockpit_hint::gain_route(&rest), &rest)
209 {
210 cmd_gain(&rest);
211 cockpit_hint::print_hint(hint.as_deref());
212 }
213 return;
214 }
215 "spend" => {
216 if super::local_read::usage::try_run("spend", &rest) {
217 return;
218 }
219 cmd_spend(&rest);
220 cockpit_hint::print_footer("spend", &rest);
221 return;
222 }
223 "savings" => {
224 cmd_savings(&rest);
225 if rest.first().is_none_or(|arg| arg.starts_with("--")) {
227 cockpit_hint::print_footer("savings", &rest);
228 }
229 return;
230 }
231 "learning" => {
232 cmd_learning(&rest);
233 return;
234 }
235 "autopilot" => {
236 let code = crate::cli::autopilot_cmd::cmd_autopilot(&rest);
237 if code != 0 {
238 std::process::exit(code);
239 }
240 return;
241 }
242 "conformance" | "selftest" => {
243 cmd_conformance(&rest);
244 return;
245 }
246 "health" => {
247 let code = crate::cli::health_cmd::cmd_health(&rest);
248 if code != 0 {
249 std::process::exit(code);
250 }
251 return;
252 }
253 "finops" => {
254 cmd_finops(&rest);
255 return;
256 }
257 "roi" => {
258 super::cmd_roi(&rest);
260 cockpit_hint::print_footer("report", &rest);
261 return;
262 }
263 "output-savings" | "output_savings" => {
264 super::cmd_output_savings(&rest);
267 cockpit_hint::print_footer("savings", &rest);
268 return;
269 }
270 "value-report" | "value_report" => {
271 super::cmd_value_report(&rest);
272 return;
273 }
274 "evidence-export" => {
275 super::cmd_evidence_export(&rest);
276 return;
277 }
278 "evidence" => {
279 let code = evidence::run(&rest);
280 if code != 0 {
281 std::process::exit(code);
282 }
283 return;
284 }
285 "shadow" => {
286 super::cmd_shadow(&rest);
287 return;
288 }
289 "triage" => {
290 super::cmd_triage(&rest);
291 return;
292 }
293 "scenario" => {
294 if let Err(error) = crate::cli::scenario_cmd::cmd_scenario_from_cli(&rest) {
295 eprintln!("scenario: {error}");
296 std::process::exit(2);
297 }
298 return;
299 }
300 "token-report" | "report-tokens" => {
301 let code = token_report::run_cli(&rest);
302 if code != 0 {
303 std::process::exit(code);
304 }
305 cockpit_hint::print_footer("savings", &rest);
306 return;
307 }
308 "pack" => {
309 crate::cli::cmd_pack(&rest);
310 return;
311 }
312 "migrate" => {
313 let Some(source) = rest.first() else {
314 eprintln!(
315 "Usage: lean-ctx migrate <headroom|config|task-receipt|legacy-context> [source]"
316 );
317 std::process::exit(2);
318 };
319 if source == "legacy-context" {
320 if let Err(error) = crate::cli::migrate_legacy::run(&rest[1..]) {
321 eprintln!("Migration failed: {error}");
322 std::process::exit(1);
323 }
324 return;
325 }
326 let migrate_args = crate::cli::migrate_cmd::MigrateArgs {
327 source: source.clone(),
328 input: rest
329 .iter()
330 .skip(1)
331 .find(|arg| !arg.starts_with("--"))
332 .map(Into::into),
333 dry_run: rest.iter().any(|arg| arg == "--dry-run"),
334 rollback: rest.iter().any(|arg| arg == "--rollback"),
335 force: rest.iter().any(|arg| arg == "--force"),
336 };
337 if let Err(error) = crate::cli::migrate_cmd::cmd_migrate(&migrate_args) {
338 eprintln!("Migration failed: {error}");
339 std::process::exit(1);
340 }
341 return;
342 }
343 "policy" => {
344 crate::cli::cmd_policy(&rest);
345 return;
346 }
347 "addon" | "addons" => {
348 crate::cli::cmd_addon(&rest);
349 return;
350 }
351 "plugin" | "plugins" => {
356 eprintln!(
357 "Plugin commands have been removed. Extensions are WASM addons now — \
358 see `lean-ctx addon help`."
359 );
360 std::process::exit(1);
361 }
362 "embeddings" => {
363 crate::cli::embeddings_cmd::cmd_embeddings(&rest);
364 return;
365 }
366 "model" => {
367 crate::cli::model_cmd::cmd_model(&rest);
368 return;
369 }
370 "enable-gpu" | "gpu" => {
371 core::updater::enable_gpu(&rest, &crate::setup::UpdateRefresh);
372 return;
373 }
374 "decisions" => {
375 crate::cli::decisions_cmd::cmd_decisions(&rest);
376 return;
377 }
378 "rules" => {
379 crate::cli::rules_cmd::cmd_rules(&rest);
380 return;
381 }
382 "proof" => {
383 crate::cli::cmd_proof(&rest);
384 return;
385 }
386 "value" => {
387 crate::cli::cmd_value(&rest);
388 cockpit_hint::print_footer("activity", &rest);
389 return;
390 }
391 "prompt-segment" => {
392 crate::cli::cmd_prompt_segment(&rest);
393 return;
394 }
395 "git-trailer" => {
397 crate::cli::cmd_git_trailer(&rest);
398 return;
399 }
400 "claude-mod" | "claude_mod" => {
401 crate::cli::claude_mod_cmd::cmd_claude_mod(&rest);
402 return;
403 }
404 "statusline" => {
405 crate::cli::cmd_statusline(&rest);
406 return;
407 }
408 "inspect" => {
409 crate::cli::cmd_inspect(&rest);
410 return;
411 }
412 "gateway" => {
413 crate::cli::gateway_cmd::cmd_gateway(&rest);
414 return;
415 }
416 "snapshot" => {
417 crate::cli::cmd_snapshot(&rest);
418 return;
419 }
420 "verify" => {
421 if verify::looks_like_bundle_command(&rest) {
422 let code = verify::run(&rest);
423 if code != 0 {
424 std::process::exit(code);
425 }
426 } else {
427 crate::cli::cmd_verify(&rest);
428 }
429 return;
430 }
431 "verify-cache" | "cache-selftest" => {
432 let code = crate::cli::verify_cache_cmd::cmd_verify_cache(&rest);
433 if code != 0 {
434 std::process::exit(code);
435 }
436 return;
437 }
438 "compliance" => {
439 crate::cli::compliance_evidence_cmd::cmd_compliance(&rest);
440 return;
441 }
442 "audit" => {
443 match rest.first().map(String::as_str) {
444 Some("verify") if super::local_read::wants_json(&rest) => {
445 super::local_read::kinds::run("audit.verify", &rest);
446 }
447 Some("evidence") => crate::cli::audit_report::cmd_evidence(&rest[1..]),
448 Some("determinism") => crate::cli::audit_report::cmd_determinism(&rest[1..]),
449 _ => println!("{}", crate::cli::audit_report::generate_report()),
450 }
451 return;
452 }
453 "agent" => {
454 if rest.first().map(String::as_str) == Some("diaries") {
455 super::local_read::engine_files::run_diaries(&rest[1..]);
456 return;
457 }
458 crate::cli::cmd_agent(&rest);
459 return;
460 }
461 "archive" => {
462 super::local_read::engine_files::run_archive(&rest);
463 return;
464 }
465 "client" => {
466 crate::cli::cmd_client(&rest);
467 return;
468 }
469 "agents" => {
470 crate::cli::local_read::agents::cmd(&rest);
471 return;
472 }
473 "instructions" => {
474 crate::cli::cmd_instructions(&rest);
475 return;
476 }
477 "index" => {
478 crate::cli::cmd_index(&rest);
479 return;
480 }
481 "semantic-search" | "search-code" => {
482 crate::cli::cmd_semantic_search(&rest);
483 core::stats::flush();
484 return;
485 }
486 "explore" => {
487 crate::cli::explore_cmd::cmd_explore(&rest);
488 core::stats::flush();
489 return;
490 }
491 "repomap" | "repo-map" => {
492 crate::cli::cmd_repomap(&rest);
493 core::stats::flush();
494 return;
495 }
496 "cep" => {
497 println!("{}", core::stats::format_cep_report());
498 cockpit_hint::print_footer("savings", &rest);
499 return;
500 }
501 "cockpit" | "dashboard" => {
502 cmd_dashboard(&rest);
503 return;
504 }
505 "provider" => {
506 cmd_provider(&rest);
507 return;
508 }
509 "serve" => {
510 cmd_serve(&rest);
511 return;
512 }
513 "watch" => {
514 cmd_watch(&rest);
515 return;
516 }
517 "proxy" => {
518 cmd_proxy(&rest);
519 return;
520 }
521 "daemon" => {
522 cmd_daemon(&rest);
523 return;
524 }
525 "init" => {
526 super::cmd_init(&rest);
527 return;
528 }
529 "setup" => {
530 handle_setup(&rest);
531 return;
532 }
533 "onboard" => {
534 handle_onboard(&rest);
535 return;
536 }
537 "install" => {
538 handle_install(&rest);
539 return;
540 }
541 "bootstrap" => {
542 handle_bootstrap(&rest);
543 return;
544 }
545 "wrap" => {
546 let code = crate::cli::wrap_cmd::cmd_wrap(&rest);
547 if code != 0 {
548 std::process::exit(code);
549 }
550 return;
551 }
552 "unwrap" => {
553 let code = crate::cli::wrap_cmd::cmd_unwrap(&rest);
554 if code != 0 {
555 std::process::exit(code);
556 }
557 return;
558 }
559 "status" => {
560 let code = status::run_cli(&rest);
561 if code != 0 {
562 std::process::exit(code);
563 }
564 return;
565 }
566 "read" => {
567 let success = super::cmd_read(&rest);
568 if !success {
569 std::process::exit(1);
570 }
571 return;
572 }
573 "call" => {
574 super::cmd_call(&rest);
575 return;
576 }
577 "diff" => {
578 super::cmd_diff(&rest);
579 return;
580 }
581 "grep" => {
582 super::cmd_grep(&rest);
583 return;
584 }
585 "glob" => {
586 super::cmd_glob(&rest);
587 return;
588 }
589 "find" => {
590 super::cmd_find(&rest);
591 return;
592 }
593 "ls" => {
594 super::cmd_ls(&rest);
595 return;
596 }
597 "deps" => {
598 super::cmd_deps(&rest);
599 return;
600 }
601 "discover" => {
602 super::cmd_discover(&rest);
603 return;
604 }
605 "engine" => {
606 super::cmd_engine(&rest);
607 return;
608 }
609 "ghost" => {
610 super::cmd_ghost(&rest);
611 return;
612 }
613 "filter" => {
614 super::cmd_filter(&rest);
615 return;
616 }
617 "heatmap" => {
618 heatmap::cmd_heatmap(&rest);
619 cockpit_hint::print_footer("context?detail=heatmap", &rest);
620 return;
621 }
622 "graph" => {
623 cmd_graph(&rest);
624 return;
625 }
626 "smells" => {
627 cmd_smells(&rest);
628 return;
629 }
630 "session" => {
631 super::cmd_session_action(&rest);
632 return;
633 }
634 "ledger" => {
635 super::cmd_ledger(&rest);
636 return;
637 }
638 "ocla" => {
639 super::cmd_ocla(&rest);
640 return;
641 }
642 "control" | "context-control" => {
643 super::cmd_control(&rest);
644 return;
645 }
646 "plan" | "context-plan" => {
647 super::cmd_plan(&rest);
648 return;
649 }
650 "compile" | "context-compile" => {
651 super::cmd_compile(&rest);
652 return;
653 }
654 "import" => {
655 crate::cli::import_cmd::cmd_import(&rest);
656 return;
657 }
658 "checkpoints" => {
659 crate::cli::checkpoint_cmd::cmd_checkpoints(&rest);
660 return;
661 }
662 "knowledge" => {
663 super::cmd_knowledge(&rest);
664 return;
665 }
666 "activity" => {
667 super::local_read::activity::run(&rest);
668 return;
669 }
670 "bus" => {
671 super::local_read::bus::run_bus(&rest);
672 return;
673 }
674 "presence" => {
675 super::local_read::bus_presence::run(&rest);
676 return;
677 }
678 "capabilities" => {
679 super::local_read::capabilities::run(&rest);
680 return;
681 }
682 "tasks" => {
683 super::cmd_tasks(&rest);
684 return;
685 }
686 "docs" => {
687 crate::cli::docs_cmd::run(&rest);
688 return;
689 }
690 "kit" | "kits" => {
691 super::cmd_kit(&rest);
692 return;
693 }
694 "skillify" => {
695 super::cmd_skillify(&rest);
696 return;
697 }
698 "summary" => {
699 super::cmd_summary(&rest);
700 return;
701 }
702 "overview" => {
703 super::cmd_overview(&rest);
704 return;
705 }
706 "compress" => {
707 super::cmd_compress(&rest);
708 return;
709 }
710 "wrapped" => {
711 let hint = match cockpit_hint::redirect(Some(VIEW_REPORT), &rest) {
713 cockpit_hint::Handled::Opened => return,
714 cockpit_hint::Handled::Text(hint) => hint,
715 };
716 eprintln!(
717 "'lean-ctx wrapped' has been removed. The recap is in the Cockpit: \
718 lean-ctx cockpit \u{2192} #report\n\
719 Exports stay in the terminal: lean-ctx gain --wrapped | --svg | --share"
720 );
721 cockpit_hint::print_hint(hint.as_deref());
722 std::process::exit(1);
723 }
724 "sessions" | "session-store" => {
725 super::cmd_sessions(&rest);
726 return;
727 }
728 "benchmark" => {
729 if rest.is_empty()
730 || rest.first().is_some_and(|arg| {
731 matches!(
732 arg.as_str(),
733 "--real"
734 | "--format"
735 | "--json"
736 | "--output"
737 | "-o"
738 | "--share"
739 | "--help"
740 | "-h"
741 )
742 })
743 {
744 super::cmd_benchmark_real(&rest);
745 } else {
746 super::cmd_benchmark(&rest);
747 }
748 return;
749 }
750 "compact" => {
751 cmd_compact(&rest);
752 return;
753 }
754 "profile" => {
755 super::cmd_profile(&rest);
756 return;
757 }
758 "tools" => {
759 if rest.first().map(String::as_str) == Some("health") {
762 super::cmd_tools_health(&rest[1..]);
763 return;
764 }
765 let mut forwarded = vec!["tools".to_string()];
769 forwarded.extend(rest.iter().cloned());
770 super::cmd_profile(&forwarded);
771 return;
772 }
773 "config" => {
774 super::cmd_config(&rest);
775 return;
776 }
777 "allow" => {
778 super::cmd_allow(&rest);
779 return;
780 }
781 "allow-path" => {
782 super::cmd_allow_path(&rest);
783 return;
784 }
785 "project" => {
786 super::project_cmd::cmd_project(&rest);
787 return;
788 }
789 "workspace" => {
790 super::workspace_cmd::cmd_workspace(&rest);
791 return;
792 }
793 "security" => {
794 super::cmd_security(&rest);
795 return;
796 }
797 "yolo" => {
798 super::cmd_yolo(&rest);
799 return;
800 }
801 "secure" | "lockdown" => {
802 super::cmd_secure(&rest);
803 return;
804 }
805 "trust" => {
806 super::cmd_trust(&rest);
807 return;
808 }
809 "untrust" => {
810 super::cmd_untrust(&rest);
811 return;
812 }
813 "stats" => {
814 super::cmd_stats(&rest);
815 return;
816 }
817 "introspect" => {
818 super::cmd_introspect(&rest);
819 return;
820 }
821 "cache" => {
822 super::cmd_cache(&rest);
823 return;
824 }
825 "theme" => {
826 super::cmd_theme(&rest);
827 return;
828 }
829 "tee" => {
830 super::cmd_tee(&rest);
831 return;
832 }
833 "terse" | "compression" => {
834 super::cmd_compression(&rest);
835 return;
836 }
837 "slow-log" => {
838 super::cmd_slow_log(&rest);
839 return;
840 }
841 "debug-log" => {
842 super::cmd_debug_log(&rest);
843 return;
844 }
845 "editor-signal" => {
848 let file = rest
849 .iter()
850 .position(|a| a == "--file")
851 .and_then(|i| rest.get(i + 1));
852 if let Some(path) = file {
853 if let Err(e) = core::editor_signal::record_focus(path) {
854 eprintln!("editor-signal: {e}");
855 std::process::exit(1);
856 }
857 } else {
858 eprintln!("usage: lean-ctx editor-signal --file <path>");
859 std::process::exit(2);
860 }
861 return;
862 }
863 "editor-session" => {
864 handle_editor_session(&rest);
865 return;
866 }
867 "editor-bridge" => {
870 if rest.first().map(String::as_str) != Some("dir") {
871 eprintln!("usage: lean-ctx editor-bridge dir");
872 std::process::exit(2);
873 }
874 match lean_ctx::lsp::editor_bridge::ensure_bridge_dir() {
875 Ok(dir) => println!("{}", dir.display()),
876 Err(e) => {
877 eprintln!("editor-bridge: {e}");
878 std::process::exit(1);
879 }
880 }
881 return;
882 }
883 "update" | "--self-update" => {
884 core::updater::run(&rest, &crate::setup::UpdateRefresh);
885 return;
886 }
887 "restart" => {
888 cmd_restart();
889 return;
890 }
891 "stop" => {
892 cmd_stop();
893 return;
894 }
895 "dev-install" => {
896 cmd_dev_install(&rest);
897 return;
898 }
899 "codesign-setup" => {
900 cmd_codesign_setup();
901 return;
902 }
903 "doctor" => {
904 let code = doctor::run_cli(&rest);
905 app_hint::after_doctor(&rest);
906 if code != 0 {
907 std::process::exit(code);
908 }
909 return;
910 }
911 "codex-protected" => {
912 let code = super::cmd_codex_protected(&rest);
913 if code != 0 {
914 std::process::exit(code);
915 }
916 return;
917 }
918 "harden" => {
919 super::harden::run(&rest);
920 return;
921 }
922 "export-rules" => {
923 super::export_rules::run(&rest);
924 return;
925 }
926 "completions" => {
927 super::completions::run_completions(&rest);
928 return;
929 }
930 "__complete" => {
931 #[allow(non_snake_case)]
932 super::completions::run___complete(&rest);
933 return;
934 }
935 "gotchas" | "bugs" => {
936 super::gotchas_cmd::cmd_gotchas(&rest);
937 return;
938 }
939 "learn" => {
940 super::cmd_learn(&rest);
941 return;
942 }
943 "hook" => {
944 hook_handlers::mark_hook_environment();
945 let action = rest.first().map_or("help", std::string::String::as_str);
946 let action = hook_handlers::profile::effective_action(action);
949 if hook_handlers::handle_protected_gate(action) {
952 return;
953 }
954 core::agent_runtime_env::capture();
958 match action {
963 "observe" => {
967 hook_handlers::arm_fail_open_watchdog(hook_handlers::OBSERVE_HOOK_BUDGET);
968 }
969 "rewrite" | "redirect" | "deny" | "vibe-pre-tool" | "rewrite-enforce"
971 | "codex-enforce" | "kiro-enforce" | "cline-enforce" | "rights" => {}
972 "govern" => {
975 hook_handlers::arm_fail_open_watchdog(std::time::Duration::from_secs(4));
976 }
977 _ => hook_handlers::arm_watchdog(std::time::Duration::from_secs(5)),
978 }
979 match action {
980 "rewrite" => hook_handlers::handle_rewrite(),
981 "redirect" => hook_handlers::handle_redirect(),
982 "deny" => hook_handlers::handle_deny(),
983 "write-guard" => hook_handlers::handle_write_guard(),
984 "read-dedup" => hook_handlers::handle_read_dedup(),
985 "govern" => hook_handlers::handle_govern(),
986 "rewrite-enforce" => hook_handlers::handle_rewrite_enforce(),
987 "observe" => {
988 let lifecycle = external_lifecycle_guard(
989 "hook_observe",
990 None,
991 core::execution_lifecycle::ToolSurface::Hook,
992 );
993 let _ = lifecycle
994 .context()
995 .advance(core::execution_lifecycle::LifecycleStage::DispatchPrimitive);
996 hook_handlers::handle_observe();
997 let _ = lifecycle.context().skip(
998 core::execution_lifecycle::LifecycleStage::ReversiblePostProcess,
999 "hook observation has no output transform",
1000 );
1001 let _ = lifecycle.context().skip(
1002 core::execution_lifecycle::LifecycleStage::RecordContextIr,
1003 "hook observation has no Context IR intent",
1004 );
1005 let _ = lifecycle.context().skip(
1006 core::execution_lifecycle::LifecycleStage::RecordLedger,
1007 "hook observation has no ledger intent",
1008 );
1009 let _ = lifecycle.complete(
1010 core::execution_lifecycle::CompletionObservation::tool_result(
1011 0, 0, "hook", true,
1012 ),
1013 );
1014 }
1015 "post-commit" => hook_handlers::handle_post_commit(),
1016 "copilot" => hook_handlers::handle_copilot(),
1017 "codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
1018 "codex-enforce" => hook_handlers::handle_codex_enforce(),
1019 "kiro-enforce" => hook_handlers::handle_kiro_enforce(),
1020 "cline-enforce" => hook_handlers::handle_cline_enforce(),
1021 "codex-session-start" => hook_handlers::handle_codex_session_start(),
1022 "rewrite-inline" => hook_handlers::handle_rewrite_inline(),
1023 "vibe-pre-tool" => hook_handlers::handle_vibe_pre_tool(),
1024 "rights" => hook_handlers::handle_rights(),
1025 _ => {
1026 eprintln!(
1027 "Usage: lean-ctx hook <rewrite|redirect|deny|write-guard|rights|read-dedup|govern|rewrite-enforce|observe|post-commit|copilot|codex-pretooluse|codex-enforce|kiro-enforce|cline-enforce|codex-session-start|rewrite-inline|vibe-pre-tool>"
1028 );
1029 eprintln!(
1030 " Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)"
1031 );
1032 std::process::exit(1);
1033 }
1034 }
1035 return;
1036 }
1037 "report-issue" | "report" => {
1038 if args[1] == "report"
1042 && matches!(rest.first().map(String::as_str), Some("sign" | "verify"))
1043 {
1044 crate::cli::local_read::report_sign::run(&rest);
1045 } else {
1046 report::run(&rest);
1047 }
1048 return;
1049 }
1050 "uninstall" => {
1051 if rest.iter().any(|a| a == "--help" || a == "-h") {
1054 uninstall::print_help();
1055 return;
1056 }
1057 match uninstall::parse_args(&rest) {
1058 Ok((dry_run, keep_config, keep_binary)) => {
1059 if !uninstall::run(dry_run, keep_config, keep_binary) {
1060 std::process::exit(1);
1061 }
1062 }
1063 Err(e) => {
1064 eprintln!("{e}");
1065 std::process::exit(2);
1066 }
1067 }
1068 return;
1069 }
1070 "raw" | "bypass" => handle_raw(&args, &rest),
1075 "safety-levels" | "safety" => {
1076 println!("{}", core::compression_safety::format_safety_table());
1077 return;
1078 }
1079 "cheat" | "cheatsheet" | "cheat-sheet" => {
1080 super::cmd_cheatsheet();
1081 return;
1082 }
1083 "telemetry" => {
1084 super::telemetry_cmd::cmd_telemetry(&rest);
1085 return;
1086 }
1087 "cloud" => {
1088 super::cloud_cmd::cmd_cloud(&rest);
1089 return;
1090 }
1091 "run" => {
1092 super::run_cmd::cmd_run(&rest);
1093 return;
1094 }
1095 "models" => {
1096 super::models_cmd::cmd_models(&rest);
1097 return;
1098 }
1099 "upgrade" => {
1100 super::gotchas_cmd::cmd_upgrade(&rest);
1101 return;
1102 }
1103 "--version" | "-V" => {
1104 if super::local_read::wants_json(&rest) {
1105 println!("{}", core::integrity::version_json());
1106 } else {
1107 println!("{}", core::integrity::origin_line());
1108 }
1109 return;
1110 }
1111 "help" => {
1112 let want_all = rest
1113 .iter()
1114 .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
1115 if want_all {
1116 print_help();
1117 } else {
1118 print_help_concise();
1119 }
1120 return;
1121 }
1122 "--help" | "-h" => {
1123 if rest
1124 .iter()
1125 .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
1126 {
1127 print_help();
1128 } else {
1129 print_help_concise();
1130 }
1131 return;
1132 }
1133 "mcp" => {}
1134 _ => {
1135 let unknown = &args[1];
1136 eprintln!("lean-ctx: unknown command '{unknown}'");
1137 if let Some(suggestion) = suggest::closest_command(unknown) {
1138 eprintln!(" did you mean '{suggestion}'?");
1139 }
1140 eprintln!(" run 'lean-ctx help' for the full command list");
1141 std::process::exit(1);
1142 }
1143 }
1144 }
1145
1146 if args.len() == 1 && lean_ctx::core::host_env::stdin_is_terminal() {
1159 eprint!("{}", quickstart_text());
1160 }
1161
1162 let served = run_mcp_server();
1163 #[cfg(unix)]
1169 shell::containment::shutdown_spawn_helper();
1170 if let Err(e) = served {
1171 tracing::error!("lean-ctx: {e}");
1172 std::process::exit(1);
1173 }
1174}
1175
1176fn handle_editor_session(args: &[String]) {
1177 let value_for = |flag: &str| {
1178 args.iter()
1179 .position(|argument| argument == flag)
1180 .and_then(|index| args.get(index + 1))
1181 };
1182 let fields = (
1183 value_for("--event"),
1184 value_for("--source"),
1185 value_for("--workspace"),
1186 value_for("--session-id"),
1187 );
1188 let (Some(event), Some(source), Some(workspace), Some(session_id)) = fields else {
1189 eprintln!(
1190 "usage: lean-ctx editor-session --event <open|heartbeat|close> \
1191 --source <editor> --workspace <path> --session-id <id>"
1192 );
1193 std::process::exit(2);
1194 };
1195
1196 if let Err(error) = lean_ctx::core::agents::AgentRegistry::record_logical_session_presence(
1197 event, source, workspace, session_id,
1198 ) {
1199 eprintln!("editor-session: {error}");
1200 std::process::exit(1);
1201 }
1202}
1203
1204fn is_server_mode(args: &[String]) -> bool {
1210 args.len() == 1
1211 || args.get(1).is_some_and(|a| {
1212 matches!(
1213 a.as_str(),
1214 "mcp"
1215 | "daemon"
1216 | "proxy"
1217 | "serve"
1218 | "watch"
1219 | "cockpit"
1220 | "dashboard"
1221 | "gateway"
1222 ) || (a == "gain" && args[2..].iter().any(|f| f == "--web" || f == "--live"))
1223 })
1224}
1225
1226fn extract_and_apply_env_prefix(cmd: &str) -> String {
1233 let mut rest = cmd.trim_start();
1234 let mut last_rest = rest;
1235
1236 loop {
1237 if let Some(eq_pos) = rest.find('=') {
1238 let key = &rest[..eq_pos];
1239 if !key.is_empty()
1240 && key
1241 .bytes()
1242 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1243 {
1244 let after_eq = &rest[eq_pos + 1..];
1245 if let Some(space_pos) = after_eq.find(' ') {
1246 let value = &after_eq[..space_pos];
1247 if lean_ctx_shell_policy::LEAN_CTX_RUN_CONTROL_ENV.contains(&key) {
1251 unsafe { std::env::set_var(key, value) };
1253 }
1254 rest = after_eq[space_pos..].trim_start();
1255 last_rest = rest;
1256 continue;
1257 }
1258 }
1259 }
1260 break;
1261 }
1262
1263 last_rest.to_string()
1264}
1265
1266fn handle_exec(args: &[String], rest: &[String]) -> ! {
1267 let raw = rest.first().is_some_and(|a| a == "--raw");
1268 let cmd_args = if raw { &args[3..] } else { &args[2..] };
1269 let command = if cmd_args.len() == 1 {
1270 cmd_args[0].clone()
1271 } else {
1272 shell::join_command(cmd_args)
1273 };
1274 let _stripped_command = extract_and_apply_env_prefix(&command);
1278 core::agent_runtime_env::capture();
1282 if lean_ctx::shell::reentry::should_pass_through() {
1283 passthrough(&command);
1284 }
1285 if raw {
1286 core::runtime_flags::enable_raw();
1287 } else {
1288 core::runtime_flags::enable_compress();
1289 }
1290 let code = execute_cli_shell("exec", &command, None, false)
1291 .map_or_else(|code| code, |(observation, _)| observation.exit_code);
1292 std::process::exit(code);
1293}
1294
1295fn handle_track(args: &[String]) -> ! {
1296 let cmd_args = &args[2..];
1297 let command = shell::join_command(cmd_args);
1298 let is_passthrough = lean_ctx::shell::reentry::should_pass_through();
1299 if cmd_args.len() <= 1 && is_passthrough {
1300 passthrough(cmd_args.first().map_or("", String::as_str));
1301 }
1302 let (command, argv) = if cmd_args.len() > 1 {
1303 (command.as_str(), Some(cmd_args))
1304 } else {
1305 (cmd_args.first().map_or("", String::as_str), None)
1306 };
1307 let code = execute_cli_shell("track", command, argv, is_passthrough)
1308 .map_or_else(|code| code, |(observation, _)| observation.exit_code);
1309 std::process::exit(code);
1310}
1311
1312fn execute_cli_shell(
1313 name: &str,
1314 command: &str,
1315 argv: Option<&[String]>,
1316 is_passthrough: bool,
1317) -> Result<
1318 (
1319 shell::ShellDispatchObservation,
1320 Option<core::execution_lifecycle::LifecycleGuard<'static>>,
1321 ),
1322 i32,
1323> {
1324 let prepared = match argv {
1325 Some(args) => shell::prepare_exec_argv(args),
1326 None => shell::prepare_exec(command),
1327 }?;
1328 let lifecycle = (!is_passthrough).then(|| {
1329 external_lifecycle_guard(
1330 name,
1331 Some(command),
1332 core::execution_lifecycle::ToolSurface::Cli,
1333 )
1334 });
1335 if let Some(guard) = &lifecycle {
1336 let _ = guard
1337 .context()
1338 .advance(core::execution_lifecycle::LifecycleStage::DispatchPrimitive);
1339 }
1340 let observation = shell::execute_prepared(prepared);
1341 if let Some(guard) = &lifecycle {
1342 use core::execution_lifecycle::LifecycleStage;
1343 for stage in [
1344 LifecycleStage::ReversiblePostProcess,
1345 LifecycleStage::RecordContextIr,
1346 LifecycleStage::RecordLedger,
1347 LifecycleStage::RecordEvidence,
1348 ] {
1349 let _ = guard
1350 .context()
1351 .skip(stage, "CLI shell adapter has no artifact observation");
1352 }
1353 let _ = guard.complete(cli_shell_completion(observation.exit_code));
1354 }
1355 Ok((observation, lifecycle))
1356}
1357
1358fn cli_shell_completion(code: i32) -> core::execution_lifecycle::CompletionObservation {
1359 let mut observation =
1360 core::execution_lifecycle::CompletionObservation::tool_result(0, 0, "cli-shell", code == 0);
1361 "local".clone_into(&mut observation.provider);
1362 observation.outcome_signals.clear();
1363 observation
1364}
1365
1366#[cfg(all(test, unix))]
1367#[path = "cli_shell_admission_tests.rs"]
1368mod cli_shell_admission_tests;
1369
1370pub(super) fn external_lifecycle_guard(
1371 tool_name: &str,
1372 query: Option<&str>,
1373 surface: core::execution_lifecycle::ToolSurface,
1374) -> core::execution_lifecycle::LifecycleGuard<'static> {
1375 let session_id = std::env::var("CODEX_THREAD_ID")
1376 .or_else(|_| std::env::var("CLAUDE_SESSION_ID"))
1377 .unwrap_or_else(|_| format!("cli-{}", std::process::id()));
1378 let project_root = std::env::current_dir()
1379 .ok()
1380 .map(|path| path.to_string_lossy().into_owned());
1381 let lifecycle = core::execution_lifecycle::ExecutionLifecycle::global();
1382 let context = lifecycle.begin(
1383 core::execution_lifecycle::ToolRequest {
1384 tool_name: tool_name.to_owned(),
1385 query: query.map(str::to_owned),
1386 session_id,
1387 agent_id: "cli".to_owned(),
1388 surface,
1389 idempotency_key: None,
1390 },
1391 core::execution_lifecycle::RuntimeContext {
1392 client_name: Some("lean-ctx-cli".to_owned()),
1393 project_root,
1394 },
1395 core::execution_lifecycle::ProductEntitlements::default(),
1396 );
1397 core::execution_lifecycle::LifecycleGuard::new(lifecycle, context)
1398}
1399
1400fn handle_raw(args: &[String], rest: &[String]) -> ! {
1401 if rest.is_empty() {
1402 eprintln!("Usage: lean-ctx raw \"command\"");
1403 eprintln!(
1404 "Runs the command with output passed through unchanged (no compression). \
1405 The shell allowlist still applies."
1406 );
1407 std::process::exit(1);
1408 }
1409 let command = if rest.len() == 1 {
1410 rest[0].clone()
1411 } else {
1412 shell::join_command(&args[2..])
1413 };
1414 core::runtime_flags::enable_raw();
1415 let code = shell::exec(&command);
1416 std::process::exit(code);
1417}
1418
1419#[cfg(unix)]
1429fn restore_sigpipe_default() {
1430 unsafe {
1433 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
1434 }
1435}
1436
1437#[cfg(not(unix))]
1438fn restore_sigpipe_default() {}
1439
1440fn passthrough(command: &str) -> ! {
1446 if let Some(code) = shell::exec::allowlist_gate(command) {
1447 std::process::exit(code);
1448 }
1449 let status = passthrough_command(command)
1450 .status()
1451 .map_or(127, shell::exit_status::exit_code);
1452 std::process::exit(status);
1453}
1454
1455fn passthrough_command(command: &str) -> std::process::Command {
1460 let (shell, flag) = shell::shell_and_flag();
1461 let mut cmd = std::process::Command::new(&shell);
1462 cmd.arg(&flag).arg(command);
1463 shell::reentry::mark_child(&mut cmd);
1464 shell::platform::apply_utf8_locale(&mut cmd);
1465 shell::platform::apply_profile_free_env(&mut cmd);
1466 cmd
1467}
1468
1469pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
1470 match tokio::runtime::Runtime::new() {
1473 Ok(rt) => rt.block_on(future),
1474 Err(e) => {
1475 eprintln!("lean-ctx: failed to create async runtime: {e}");
1476 std::process::exit(1);
1477 }
1478 }
1479}
1480
1481#[cfg(test)]
1482mod tests;
1483
1484#[cfg(test)]
1485mod env_prefix_tests;