Skip to main content

lean_ctx/cli/dispatch/
mod.rs

1use crate::{
2    core, doctor, heatmap, hook_handlers, report, setup, shell, status, token_report, uninstall,
3};
4
5pub mod analytics;
6pub(crate) mod benchmark_run;
7pub(crate) mod calibrate;
8mod cmd_help;
9mod evidence;
10pub(crate) mod evidence_cost;
11pub(crate) mod evidence_realworld;
12pub(crate) mod evidence_report;
13pub(crate) mod evidence_workflow;
14mod help;
15mod lifecycle;
16mod network;
17pub(crate) mod pair;
18mod server;
19pub(crate) mod suggest;
20pub mod verify;
21
22#[allow(clippy::wildcard_imports)]
23use analytics::*;
24#[allow(clippy::wildcard_imports)]
25use help::*;
26#[allow(clippy::wildcard_imports)]
27use lifecycle::*;
28#[allow(clippy::wildcard_imports)]
29use network::*;
30#[allow(clippy::wildcard_imports)]
31use server::*;
32
33pub fn run() {
34    let mut args: Vec<String> = std::env::args().collect();
35
36    // On Linux, if the binary was replaced while running, systemd may write
37    // the path with " (deleted)" suffix into ExecStart, causing "(deleted)"
38    // to appear as an argument. Strip it defensively.
39    if args.get(1).is_some_and(|a| a == "(deleted)") {
40        args.remove(1);
41    }
42
43    match crate::cli::codex_protected_cmd::protected_gitlab_dispatch(&args) {
44        Ok(Some(code)) => std::process::exit(code),
45        Ok(None) => {}
46        Err(error) => {
47            eprintln!("Error: {error}");
48            std::process::exit(1);
49        }
50    }
51
52    if !is_server_mode(&args) {
53        restore_sigpipe_default();
54    }
55
56    let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
57    if !enters_mcp {
58        crate::core::logging::init_logging();
59    }
60    // Default-on telemetry is disclosed once on the first interactive command;
61    // setup and `telemetry` print the same disclosure themselves.
62    if !enters_mcp
63        && !is_server_mode(&args)
64        && !matches!(args.get(1).map(String::as_str), Some("setup" | "telemetry"))
65    {
66        crate::core::telemetry_consent::maybe_show_notice();
67    }
68
69    if args.len() > 1 {
70        let rest = args[2..].to_vec();
71
72        if let Some(usage) = cmd_help::guarded_help(&args[1], &rest) {
73            print!("{usage}");
74            return;
75        }
76
77        match args[1].as_str() {
78            "-c" | "exec" => handle_exec(&args, &rest),
79            "-t" | "--track" => handle_track(&args),
80            "badge" => {
81                crate::cli::badge_cmd::cmd_badge(&rest);
82                return;
83            }
84            "shell" | "--shell" => {
85                shell::interactive();
86                return;
87            }
88            "gain" => {
89                cmd_gain(&rest);
90                return;
91            }
92            "spend" => {
93                cmd_spend(&rest);
94                return;
95            }
96            "savings" => {
97                cmd_savings(&rest);
98                return;
99            }
100            "learning" => {
101                cmd_learning(&rest);
102                return;
103            }
104            "autopilot" => {
105                let code = crate::cli::autopilot_cmd::cmd_autopilot(&rest);
106                if code != 0 {
107                    std::process::exit(code);
108                }
109                return;
110            }
111            "conformance" | "selftest" => {
112                cmd_conformance(&rest);
113                return;
114            }
115            "health" => {
116                let code = crate::cli::health_cmd::cmd_health(&rest);
117                if code != 0 {
118                    std::process::exit(code);
119                }
120                return;
121            }
122            "quality-lab" | "quality_lab" => {
123                let code = crate::cli::quality_lab_cmd::cmd_quality_lab(&rest);
124                if code != 0 {
125                    std::process::exit(code);
126                }
127                return;
128            }
129            "billing" => {
130                cmd_billing(&rest);
131                return;
132            }
133            "finops" => {
134                cmd_finops(&rest);
135                return;
136            }
137            "roi" => {
138                // Local ROI is individual + free. The team roll-up lives on its own
139                // surface (`savings team` / the web account), not under `roi`.
140                super::cmd_roi(&rest);
141                return;
142            }
143            "output-savings" | "output_savings" => {
144                // #895 Track B: measured (A/B holdout) or estimated output-token
145                // reduction. Local + free, like `roi`.
146                super::cmd_output_savings(&rest);
147                return;
148            }
149            "value-report" | "value_report" => {
150                super::cmd_value_report(&rest);
151                return;
152            }
153            "evidence-export" => {
154                super::cmd_evidence_export(&rest);
155                return;
156            }
157            "evidence" => {
158                let code = evidence::run(&rest);
159                if code != 0 {
160                    std::process::exit(code);
161                }
162                return;
163            }
164            "shadow" => {
165                super::cmd_shadow(&rest);
166                return;
167            }
168            "triage" => {
169                super::cmd_triage(&rest);
170                return;
171            }
172            "scenario" => {
173                if let Err(error) = crate::cli::scenario_cmd::cmd_scenario_from_cli(&rest) {
174                    eprintln!("scenario: {error}");
175                    std::process::exit(2);
176                }
177                return;
178            }
179            "measure" => {
180                super::cmd_measure(&rest);
181                return;
182            }
183            "token-report" | "report-tokens" => {
184                let code = token_report::run_cli(&rest);
185                if code != 0 {
186                    std::process::exit(code);
187                }
188                return;
189            }
190            "pack" => {
191                crate::cli::cmd_pack(&rest);
192                return;
193            }
194            "migrate" => {
195                let Some(source) = rest.first() else {
196                    eprintln!("Usage: lean-ctx migrate <headroom|config|task-receipt> [source]");
197                    std::process::exit(2);
198                };
199                let migrate_args = crate::cli::migrate_cmd::MigrateArgs {
200                    source: source.clone(),
201                    input: rest
202                        .iter()
203                        .skip(1)
204                        .find(|arg| !arg.starts_with("--"))
205                        .map(Into::into),
206                    dry_run: rest.iter().any(|arg| arg == "--dry-run"),
207                    rollback: rest.iter().any(|arg| arg == "--rollback"),
208                    force: rest.iter().any(|arg| arg == "--force"),
209                };
210                if let Err(error) = crate::cli::migrate_cmd::cmd_migrate(&migrate_args) {
211                    eprintln!("Migration failed: {error}");
212                    std::process::exit(1);
213                }
214                return;
215            }
216            "policy" => {
217                crate::cli::cmd_policy(&rest);
218                return;
219            }
220            "addon" | "addons" => {
221                crate::cli::cmd_addon(&rest);
222                return;
223            }
224            // Subprocess plugins are not coming back. An addon is a signed
225            // package: a sandboxed WASM module, or a declared MCP server the
226            // user consents to by reading its argv — either way the trust
227            // decision is bounded and visible (`lean-ctx addon`).
228            "plugin" | "plugins" => {
229                eprintln!(
230                    "Plugin commands have been removed. Extensions are WASM addons now — \
231                     see `lean-ctx addon help`."
232                );
233                std::process::exit(1);
234            }
235            "embeddings" => {
236                crate::cli::embeddings_cmd::cmd_embeddings(&rest);
237                return;
238            }
239            "model" => {
240                crate::cli::model_cmd::cmd_model(&rest);
241                return;
242            }
243            "enable-gpu" | "gpu" => {
244                core::updater::enable_gpu(&rest);
245                return;
246            }
247            "rules" => {
248                crate::cli::rules_cmd::cmd_rules(&rest);
249                return;
250            }
251            "proof" => {
252                crate::cli::cmd_proof(&rest);
253                return;
254            }
255            "prove" => {
256                crate::cli::cmd_prove(&rest);
257                return;
258            }
259            "value" => {
260                crate::cli::cmd_value(&rest);
261                return;
262            }
263            "prompt-segment" => {
264                crate::cli::cmd_prompt_segment(&rest);
265                return;
266            }
267            // Hidden: run by the prepare-commit-msg hook from `init --git-trailer`.
268            "git-trailer" => {
269                crate::cli::cmd_git_trailer(&rest);
270                return;
271            }
272            "claude-mod" | "claude_mod" => {
273                crate::cli::claude_mod_cmd::cmd_claude_mod(&rest);
274                return;
275            }
276            "statusline" => {
277                crate::cli::cmd_statusline(&rest);
278                return;
279            }
280            "inspect" => {
281                crate::cli::cmd_inspect(&rest);
282                return;
283            }
284            "snapshot" => {
285                crate::cli::cmd_snapshot(&rest);
286                return;
287            }
288            "verify" => {
289                if verify::looks_like_bundle_command(&rest) {
290                    let code = verify::run(&rest);
291                    if code != 0 {
292                        std::process::exit(code);
293                    }
294                } else {
295                    crate::cli::cmd_verify(&rest);
296                }
297                return;
298            }
299            "eval" => {
300                crate::cli::eval_cmd::cmd_eval(&rest);
301                return;
302            }
303            "verify-cache" | "cache-selftest" => {
304                let code = crate::cli::verify_cache_cmd::cmd_verify_cache(&rest);
305                if code != 0 {
306                    std::process::exit(code);
307                }
308                return;
309            }
310            "visualize" => {
311                super::cmd_visualize(&rest);
312                return;
313            }
314            "audit" => {
315                match rest.first().map(String::as_str) {
316                    Some("evidence") => crate::cli::audit_report::cmd_evidence(&rest[1..]),
317                    Some("determinism") => crate::cli::audit_report::cmd_determinism(&rest[1..]),
318                    _ => println!("{}", crate::cli::audit_report::generate_report()),
319                }
320                return;
321            }
322            "compliance" => {
323                crate::cli::cmd_compliance(&rest);
324                return;
325            }
326            "agent" => {
327                crate::cli::cmd_agent(&rest);
328                return;
329            }
330            "instructions" => {
331                crate::cli::cmd_instructions(&rest);
332                return;
333            }
334            "index" => {
335                crate::cli::cmd_index(&rest);
336                return;
337            }
338            "semantic-search" | "search-code" => {
339                crate::cli::cmd_semantic_search(&rest);
340                core::stats::flush();
341                return;
342            }
343            "explore" => {
344                crate::cli::explore_cmd::cmd_explore(&rest);
345                core::stats::flush();
346                return;
347            }
348            "repomap" | "repo-map" => {
349                crate::cli::cmd_repomap(&rest);
350                core::stats::flush();
351                return;
352            }
353            "cep" => {
354                println!("{}", core::stats::format_cep_report());
355                return;
356            }
357            "demo" => {
358                super::cmd_demo(&rest);
359                return;
360            }
361            "dashboard" => {
362                cmd_dashboard(&rest);
363                return;
364            }
365            "team" => {
366                cmd_team(&rest);
367                return;
368            }
369            "provider" => {
370                cmd_provider(&rest);
371                return;
372            }
373            "serve" => {
374                cmd_serve(&rest);
375                return;
376            }
377            "watch" => {
378                cmd_watch(&rest);
379                return;
380            }
381            "proxy" => {
382                cmd_proxy(&rest);
383                return;
384            }
385            "daemon" => {
386                cmd_daemon(&rest);
387                return;
388            }
389            "init" => {
390                super::cmd_init(&rest);
391                return;
392            }
393            "setup" => {
394                handle_setup(&rest);
395                return;
396            }
397            "onboard" => {
398                handle_onboard(&rest);
399                return;
400            }
401            "install" => {
402                handle_install(&rest);
403                return;
404            }
405            "bootstrap" => {
406                handle_bootstrap(&rest);
407                return;
408            }
409            "wrap" => {
410                let code = crate::cli::wrap_cmd::cmd_wrap(&rest);
411                if code != 0 {
412                    std::process::exit(code);
413                }
414                return;
415            }
416            "unwrap" => {
417                let code = crate::cli::wrap_cmd::cmd_unwrap(&rest);
418                if code != 0 {
419                    std::process::exit(code);
420                }
421                return;
422            }
423            "status" => {
424                let code = status::run_cli(&rest);
425                if code != 0 {
426                    std::process::exit(code);
427                }
428                return;
429            }
430            "cognitive" => {
431                crate::cli::cognitive::run();
432                return;
433            }
434            "read" => {
435                let success = super::cmd_read(&rest);
436                if !success {
437                    std::process::exit(1);
438                }
439                return;
440            }
441            "call" => {
442                super::cmd_call(&rest);
443                return;
444            }
445            "diff" => {
446                super::cmd_diff(&rest);
447                return;
448            }
449            "grep" => {
450                super::cmd_grep(&rest);
451                return;
452            }
453            "glob" => {
454                super::cmd_glob(&rest);
455                return;
456            }
457            "find" => {
458                super::cmd_find(&rest);
459                return;
460            }
461            "ls" => {
462                super::cmd_ls(&rest);
463                return;
464            }
465            "deps" => {
466                super::cmd_deps(&rest);
467                return;
468            }
469            "discover" => {
470                super::cmd_discover(&rest);
471                return;
472            }
473            "engine" => {
474                super::cmd_engine(&rest);
475                return;
476            }
477            "ghost" => {
478                super::cmd_ghost(&rest);
479                return;
480            }
481            "filter" => {
482                super::cmd_filter(&rest);
483                return;
484            }
485            "heatmap" => {
486                heatmap::cmd_heatmap(&rest);
487                return;
488            }
489            "graph" => {
490                cmd_graph(&rest);
491                return;
492            }
493            "smells" => {
494                cmd_smells(&rest);
495                return;
496            }
497            "session" => {
498                super::cmd_session_action(&rest);
499                return;
500            }
501            "ledger" => {
502                super::cmd_ledger(&rest);
503                return;
504            }
505            "ocla" => {
506                super::cmd_ocla(&rest);
507                return;
508            }
509            "control" | "context-control" => {
510                super::cmd_control(&rest);
511                return;
512            }
513            "plan" | "context-plan" => {
514                super::cmd_plan(&rest);
515                return;
516            }
517            "compile" | "context-compile" => {
518                super::cmd_compile(&rest);
519                return;
520            }
521            "import" => {
522                crate::cli::import_cmd::cmd_import(&rest);
523                return;
524            }
525            "checkpoints" => {
526                crate::cli::checkpoint_cmd::cmd_checkpoints(&rest);
527                return;
528            }
529            "knowledge" => {
530                super::cmd_knowledge(&rest);
531                return;
532            }
533            "kit" | "kits" => {
534                super::cmd_kit(&rest);
535                return;
536            }
537            "skillify" => {
538                super::cmd_skillify(&rest);
539                return;
540            }
541            "summary" => {
542                super::cmd_summary(&rest);
543                return;
544            }
545            "overview" => {
546                super::cmd_overview(&rest);
547                return;
548            }
549            "compress" => {
550                super::cmd_compress(&rest);
551                return;
552            }
553            "wrapped" => {
554                eprintln!("'lean-ctx wrapped' has been removed. Use: lean-ctx gain --wrapped");
555                std::process::exit(1);
556            }
557            "sessions" | "session-store" => {
558                super::cmd_sessions(&rest);
559                return;
560            }
561            "benchmark" => {
562                if rest.is_empty()
563                    || rest.first().is_some_and(|arg| {
564                        matches!(
565                            arg.as_str(),
566                            "--real"
567                                | "--format"
568                                | "--json"
569                                | "--output"
570                                | "-o"
571                                | "--share"
572                                | "--help"
573                                | "-h"
574                        )
575                    })
576                {
577                    super::cmd_benchmark_real(&rest);
578                } else {
579                    super::cmd_benchmark(&rest);
580                }
581                return;
582            }
583            "benchmark-run" | "bench-run" => {
584                let code = benchmark_run::cmd_benchmark_run(&rest);
585                if code != 0 {
586                    std::process::exit(code);
587                }
588                return;
589            }
590            "calibrate" => {
591                let code = calibrate::cmd_calibrate(&rest);
592                if code != 0 {
593                    std::process::exit(code);
594                }
595                return;
596            }
597            "pair" => {
598                let code = pair::cmd_pair(&rest);
599                if code != 0 {
600                    std::process::exit(code);
601                }
602                return;
603            }
604            "compact" => {
605                cmd_compact(&rest);
606                return;
607            }
608            "profile" => {
609                super::cmd_profile(&rest);
610                return;
611            }
612            "tools" => {
613                // `tools health` is the token-budget / rot report (#848); it is
614                // distinct from tool *profiles* and routed before the forward.
615                if rest.first().map(String::as_str) == Some("health") {
616                    super::cmd_tools_health(&rest[1..]);
617                    return;
618                }
619                // Canonical, unambiguous entry point for MCP *tool* profiles
620                // (how many tools the agent sees). Disambiguates from
621                // `lean-ctx profile`, which manages *context* profiles.
622                let mut forwarded = vec!["tools".to_string()];
623                forwarded.extend(rest.iter().cloned());
624                super::cmd_profile(&forwarded);
625                return;
626            }
627            "config" => {
628                super::cmd_config(&rest);
629                return;
630            }
631            "allow" => {
632                super::cmd_allow(&rest);
633                return;
634            }
635            "security" => {
636                super::cmd_security(&rest);
637                return;
638            }
639            "yolo" => {
640                super::cmd_yolo(&rest);
641                return;
642            }
643            "secure" | "lockdown" => {
644                super::cmd_secure(&rest);
645                return;
646            }
647            "trust" => {
648                super::cmd_trust(&rest);
649                return;
650            }
651            "untrust" => {
652                super::cmd_untrust(&rest);
653                return;
654            }
655            "stats" => {
656                super::cmd_stats(&rest);
657                return;
658            }
659            "introspect" => {
660                super::cmd_introspect(&rest);
661                return;
662            }
663            "cache" => {
664                super::cmd_cache(&rest);
665                return;
666            }
667            "theme" => {
668                super::cmd_theme(&rest);
669                return;
670            }
671            "enterprise" => {
672                super::cmd_enterprise(&rest);
673                return;
674            }
675            "tee" => {
676                super::cmd_tee(&rest);
677                return;
678            }
679            "terse" | "compression" => {
680                super::cmd_compression(&rest);
681                return;
682            }
683            "slow-log" => {
684                super::cmd_slow_log(&rest);
685                return;
686            }
687            "debug-log" => {
688                super::cmd_debug_log(&rest);
689                return;
690            }
691            // Editor focus ingress (#500): called by the VS Code extension on
692            // tab change; <10ms, no daemon required.
693            "editor-signal" => {
694                let file = rest
695                    .iter()
696                    .position(|a| a == "--file")
697                    .and_then(|i| rest.get(i + 1));
698                if let Some(path) = file {
699                    if let Err(e) = core::editor_signal::record_focus(path) {
700                        eprintln!("editor-signal: {e}");
701                        std::process::exit(1);
702                    }
703                } else {
704                    eprintln!("usage: lean-ctx editor-signal --file <path>");
705                    std::process::exit(2);
706                }
707                return;
708            }
709            "editor-session" => {
710                handle_editor_session(&rest);
711                return;
712            }
713            // Editor semantic bridge (VS Code/Cursor/Windsurf extension):
714            // where the extension announces its loopback bridge.
715            "editor-bridge" => {
716                if rest.first().map(String::as_str) != Some("dir") {
717                    eprintln!("usage: lean-ctx editor-bridge dir");
718                    std::process::exit(2);
719                }
720                match crate::lsp::editor_bridge::ensure_bridge_dir() {
721                    Ok(dir) => println!("{}", dir.display()),
722                    Err(e) => {
723                        eprintln!("editor-bridge: {e}");
724                        std::process::exit(1);
725                    }
726                }
727                return;
728            }
729            "update" | "--self-update" => {
730                core::updater::run(&rest);
731                return;
732            }
733            "restart" => {
734                cmd_restart();
735                return;
736            }
737            "stop" => {
738                cmd_stop();
739                return;
740            }
741            "dev-install" => {
742                cmd_dev_install();
743                return;
744            }
745            "codesign-setup" => {
746                cmd_codesign_setup();
747                return;
748            }
749            "doctor" => {
750                let code = doctor::run_cli(&rest);
751                if code != 0 {
752                    std::process::exit(code);
753                }
754                return;
755            }
756            "codex-protected" => {
757                let code = super::cmd_codex_protected(&rest);
758                if code != 0 {
759                    std::process::exit(code);
760                }
761                return;
762            }
763            "harden" => {
764                super::harden::run(&rest);
765                return;
766            }
767            "export-rules" => {
768                super::export_rules::run(&rest);
769                return;
770            }
771            "completions" => {
772                super::completions::run_completions(&rest);
773                return;
774            }
775            "__complete" => {
776                #[allow(non_snake_case)]
777                super::completions::run___complete(&rest);
778                return;
779            }
780            "gotchas" | "bugs" => {
781                super::cloud::cmd_gotchas(&rest);
782                return;
783            }
784            "learn" => {
785                super::cmd_learn(&rest);
786                return;
787            }
788            "buddy" | "pet" => {
789                super::cloud::cmd_buddy(&rest);
790                return;
791            }
792            "hook" => {
793                hook_handlers::mark_hook_environment();
794                let action = rest.first().map_or("help", std::string::String::as_str);
795                // Security admission precedes compression bypasses, runtime-env
796                // capture, and the legacy fail-open watchdogs.
797                if hook_handlers::handle_protected_gate(action) {
798                    return;
799                }
800                // Hooks run inside the agent shell environment, so they can see
801                // runtime/session vars (e.g. CODEX_THREAD_ID) that the long-lived
802                // MCP server process never receives. Bridge them for ctx_shell (#370).
803                core::agent_runtime_env::capture();
804                // Gating hooks (rewrite/redirect) self-bound their work and FAIL OPEN
805                // inside the handler (#1035), so they must NOT also carry the
806                // force-exit watchdog (which would `exit(1)` with no decision and
807                // wedge the host). The remaining hooks keep the simple zombie-guard.
808                match action {
809                    // Observation is loss-tolerant telemetry. It gets a shorter,
810                    // successful fail-open watchdog so it can never make Codex
811                    // report a PostToolUse timeout under load.
812                    "observe" => {
813                        hook_handlers::arm_fail_open_watchdog(hook_handlers::OBSERVE_HOOK_BUDGET);
814                    }
815                    // Gating hooks self-bound and fail open inside their handlers.
816                    "rewrite" | "redirect" | "deny" | "vibe-pre-tool" => {}
817                    _ => hook_handlers::arm_watchdog(std::time::Duration::from_secs(5)),
818                }
819                match action {
820                    "rewrite" => hook_handlers::handle_rewrite(),
821                    "redirect" => hook_handlers::handle_redirect(),
822                    "deny" => hook_handlers::handle_deny(),
823                    "read-dedup" => hook_handlers::handle_read_dedup(),
824                    "observe" => {
825                        let lifecycle = external_lifecycle_guard(
826                            "hook_observe",
827                            None,
828                            core::execution_lifecycle::ToolSurface::Hook,
829                        );
830                        let _ = lifecycle
831                            .context()
832                            .advance(core::execution_lifecycle::LifecycleStage::DispatchPrimitive);
833                        hook_handlers::handle_observe();
834                        let _ = lifecycle.context().skip(
835                            core::execution_lifecycle::LifecycleStage::ReversiblePostProcess,
836                            "hook observation has no output transform",
837                        );
838                        let _ = lifecycle.context().skip(
839                            core::execution_lifecycle::LifecycleStage::RecordContextIr,
840                            "hook observation has no Context IR intent",
841                        );
842                        let _ = lifecycle.context().skip(
843                            core::execution_lifecycle::LifecycleStage::RecordLedger,
844                            "hook observation has no ledger intent",
845                        );
846                        let _ = lifecycle.complete(
847                            core::execution_lifecycle::CompletionObservation::tool_result(
848                                0, 0, "hook", true,
849                            ),
850                        );
851                    }
852                    "post-commit" => hook_handlers::handle_post_commit(),
853                    "copilot" => hook_handlers::handle_copilot(),
854                    "codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
855                    "codex-session-start" => hook_handlers::handle_codex_session_start(),
856                    "rewrite-inline" => hook_handlers::handle_rewrite_inline(),
857                    "vibe-pre-tool" => hook_handlers::handle_vibe_pre_tool(),
858                    _ => {
859                        eprintln!(
860                            "Usage: lean-ctx hook <rewrite|redirect|deny|read-dedup|observe|post-commit|copilot|codex-pretooluse|codex-session-start|rewrite-inline|vibe-pre-tool>"
861                        );
862                        eprintln!(
863                            "  Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)"
864                        );
865                        std::process::exit(1);
866                    }
867                }
868                return;
869            }
870            "report-issue" | "report" => {
871                report::run(&rest);
872                return;
873            }
874            "uninstall" => {
875                // Safety: `--help`/`-h` must NEVER fall through to a real
876                // uninstall (issue #476). Short-circuit before any removal.
877                if rest.iter().any(|a| a == "--help" || a == "-h") {
878                    uninstall::print_help();
879                    return;
880                }
881                let dry_run = rest.iter().any(|a| a == "--dry-run");
882                let keep_config = rest.iter().any(|a| a == "--keep-config");
883                let keep_binary = rest.iter().any(|a| a == "--keep-binary");
884                uninstall::run(dry_run, keep_config, keep_binary);
885                return;
886            }
887            // `raw` is the primary name; `bypass` is kept as a back-compat alias.
888            // The old "bypass" wording read to a model like a *security* bypass,
889            // but this only skips compression — the shell allowlist and path jail
890            // still apply (GH security audit, finding 5).
891            "raw" | "bypass" => handle_raw(&args, &rest),
892            "safety-levels" | "safety" => {
893                println!("{}", core::compression_safety::format_safety_table());
894                return;
895            }
896            "cheat" | "cheatsheet" | "cheat-sheet" => {
897                super::cmd_cheatsheet();
898                return;
899            }
900            "login" => {
901                super::cloud::cmd_login(&rest);
902                return;
903            }
904            "register" => {
905                super::cloud::cmd_register(&rest);
906                return;
907            }
908            "forgot-password" => {
909                super::cloud::cmd_forgot_password(&rest);
910                return;
911            }
912            "sync" => {
913                super::cloud::cmd_sync(&rest);
914                return;
915            }
916            "contribute" => {
917                super::cloud::cmd_contribute();
918                return;
919            }
920            "telemetry" => {
921                super::telemetry_cmd::cmd_telemetry(&rest);
922                return;
923            }
924            "cloud" => {
925                super::cloud::cmd_cloud(&rest);
926                return;
927            }
928            "upgrade" => {
929                super::cloud::cmd_upgrade(&rest);
930                return;
931            }
932            "--version" | "-V" => {
933                println!("{}", core::integrity::origin_line());
934                return;
935            }
936            "help" => {
937                let want_all = rest
938                    .iter()
939                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
940                if want_all {
941                    print_help();
942                } else {
943                    print_help_concise();
944                }
945                return;
946            }
947            "--help" | "-h" => {
948                if rest
949                    .iter()
950                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
951                {
952                    print_help();
953                } else {
954                    print_help_concise();
955                }
956                return;
957            }
958            "mcp" => {}
959            _ => {
960                let unknown = &args[1];
961                eprintln!("lean-ctx: unknown command '{unknown}'");
962                if let Some(suggestion) = suggest::closest_command(unknown) {
963                    eprintln!("       did you mean '{suggestion}'?");
964                }
965                eprintln!("       run 'lean-ctx help' for the full command list");
966                std::process::exit(1);
967            }
968        }
969    }
970
971    // Bare `lean-ctx` on an interactive terminal: a human almost certainly did
972    // not mean to start a silent stdio MCP server, so print the quickstart.
973    //
974    // #1595: the TTY test alone is not a safe *stop* condition. An MCP client
975    // that spawns the server under a PTY (Devin, several containerized agent
976    // runners, anything driving the child through `script`/`expect`) hands it a
977    // terminal on stdin and is then answered with the quickstart instead of a
978    // server — the connection simply never comes up, with no error to see.
979    // A TTY tells us a human *might* be watching; it never tells us a client is
980    // not. So the guidance goes to stderr, which MCP clients log rather than
981    // parse, and the server starts either way: the human reads what is going on
982    // and presses Ctrl-C, the client completes its handshake on stdout.
983    if args.len() == 1 && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
984        eprint!("{}", quickstart_text());
985    }
986
987    if let Err(e) = run_mcp_server() {
988        tracing::error!("lean-ctx: {e}");
989        std::process::exit(1);
990    }
991}
992
993fn handle_editor_session(args: &[String]) {
994    let value_for = |flag: &str| {
995        args.iter()
996            .position(|argument| argument == flag)
997            .and_then(|index| args.get(index + 1))
998    };
999    let fields = (
1000        value_for("--event"),
1001        value_for("--source"),
1002        value_for("--workspace"),
1003        value_for("--session-id"),
1004    );
1005    let (Some(event), Some(source), Some(workspace), Some(session_id)) = fields else {
1006        eprintln!(
1007            "usage: lean-ctx editor-session --event <open|heartbeat|close> \
1008             --source <editor> --workspace <path> --session-id <id>"
1009        );
1010        std::process::exit(2);
1011    };
1012
1013    if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
1014        event, source, workspace, session_id,
1015    ) {
1016        eprintln!("editor-session: {error}");
1017        std::process::exit(1);
1018    }
1019}
1020
1021/// Help for `lean-ctx setup`. Printed for `--help`/`-h` and unknown flags so
1022/// asking about setup can never accidentally *run* setup (#476 class, #658).
1023fn print_setup_help() {
1024    println!("Usage: lean-ctx setup [options]");
1025    println!();
1026    println!("Guided setup: shell hook, agent hooks/rules, MCP registrations.");
1027    println!("Protected Codex: setup codex-protected --project <DIR> [--policy-pack <NAME>]");
1028    println!(
1029        "  Checks a separate protected session; add --start to launch. See subcommand --help."
1030    );
1031    println!(
1032        "Optional proprietary runtime: setup runtime <configure|status|sync-configured|rollback-configured|activate-configured|activate-personal|renew-configured|deactivate>. Installation/activation requires --accept-proprietary; rollback-configured restores the retained production version. Staging-only operator commands additionally require --staging.\nSharing (requires --accept-proprietary): share-identity; share-invite --recipient ACCOUNT_UUID --output ABSOLUTE_PRIVATE_FILE [--context-id UUID --revision N --expires-at RFC3339]; share-publish --project ABSOLUTE_DIRECTORY --invitation ABSOLUTE_PRIVATE_FILE; share-continue --project ABSOLUTE_DIRECTORY --invitation ABSOLUTE_PRIVATE_FILE [--expected-head SHA256]. Omit expected-head only for an empty destination. Transfer invitation files confidentially to their named recipient."
1033    );
1034    println!("Interactive by default; runs non-interactively without a TTY.");
1035    println!();
1036    println!("Options:");
1037    println!("  --non-interactive   No prompts; apply defaults");
1038    println!("  --yes, -y           Assume yes for all prompts");
1039    println!("  --fix               Repair an existing installation");
1040    println!("  --json              Machine-readable report (implies non-interactive)");
1041    println!("  --no-auto-approve   Skip auto-approve configuration");
1042    println!("  --skip-rules        Do not write agent rules files");
1043    println!("  --help, -h          Show this help (never runs setup)");
1044    println!();
1045    println!("See also: lean-ctx onboard (one-command setup), lean-ctx doctor");
1046}
1047
1048/// Long-lived server entry points keep Rust's default ignored SIGPIPE: they
1049/// must survive peers closing sockets/pipes early. Bare `lean-ctx` counts as
1050/// a server because MCP clients spawn the binary without a subcommand.
1051fn is_server_mode(args: &[String]) -> bool {
1052    args.len() == 1
1053        || args.get(1).is_some_and(|a| {
1054            matches!(
1055                a.as_str(),
1056                "mcp" | "daemon" | "proxy" | "serve" | "watch" | "dashboard" | "gateway"
1057            )
1058        })
1059}
1060
1061/// Extract `KEY=VALUE` prefixes from a command string and promote lean-ctx control variables
1062/// (`LEAN_CTX_*`) into the process environment.
1063/// Returns the remaining command string without the extracted prefixes.
1064///
1065/// Only `LEAN_CTX_*` variables are set in the process env — arbitrary user vars like `FOO=bar`
1066/// are left for the child shell to handle.
1067fn extract_and_apply_env_prefix(cmd: &str) -> String {
1068    let mut rest = cmd.trim_start();
1069    let mut last_rest = rest;
1070
1071    loop {
1072        if let Some(eq_pos) = rest.find('=') {
1073            let key = &rest[..eq_pos];
1074            if !key.is_empty()
1075                && key
1076                    .bytes()
1077                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1078            {
1079                let after_eq = &rest[eq_pos + 1..];
1080                if let Some(space_pos) = after_eq.find(' ') {
1081                    let value = &after_eq[..space_pos];
1082                    if key.starts_with("LEAN_CTX_") {
1083                        // SAFETY: runs before tokio runtime spawns threads.
1084                        unsafe { std::env::set_var(key, value) };
1085                    }
1086                    rest = after_eq[space_pos..].trim_start();
1087                    last_rest = rest;
1088                    continue;
1089                }
1090            }
1091        }
1092        break;
1093    }
1094
1095    last_rest.to_string()
1096}
1097
1098fn handle_exec(args: &[String], rest: &[String]) -> ! {
1099    let raw = rest.first().is_some_and(|a| a == "--raw");
1100    let cmd_args = if raw { &args[3..] } else { &args[2..] };
1101    let command = if cmd_args.len() == 1 {
1102        cmd_args[0].clone()
1103    } else {
1104        shell::join_command(cmd_args)
1105    };
1106    // Extract LEAN_CTX_* env-var prefixes from the command string and set them in process env
1107    // so should_pass_through() / is_disabled() can see them. The child shell still gets the full
1108    // original command. (#1321)
1109    let _stripped_command = extract_and_apply_env_prefix(&command);
1110    // The `lean-ctx -c` wrapper runs inside the agent shell, which carries
1111    // runtime/session vars the MCP server never sees. Bridge them so ctx_shell
1112    // can forward them too (#370).
1113    core::agent_runtime_env::capture();
1114    if crate::shell::reentry::should_pass_through() {
1115        passthrough(&command);
1116    }
1117    if raw {
1118        core::runtime_flags::enable_raw();
1119    } else {
1120        core::runtime_flags::enable_compress();
1121    }
1122    let code = execute_cli_shell("exec", &command, None, false)
1123        .map_or_else(|code| code, |(observation, _)| observation.exit_code);
1124    std::process::exit(code);
1125}
1126
1127fn handle_track(args: &[String]) -> ! {
1128    let cmd_args = &args[2..];
1129    let command = shell::join_command(cmd_args);
1130    let is_passthrough = crate::shell::reentry::should_pass_through();
1131    if cmd_args.len() <= 1 && is_passthrough {
1132        passthrough(cmd_args.first().map_or("", String::as_str));
1133    }
1134    let (command, argv) = if cmd_args.len() > 1 {
1135        (command.as_str(), Some(cmd_args))
1136    } else {
1137        (cmd_args.first().map_or("", String::as_str), None)
1138    };
1139    let code = execute_cli_shell("track", command, argv, is_passthrough)
1140        .map_or_else(|code| code, |(observation, _)| observation.exit_code);
1141    std::process::exit(code);
1142}
1143
1144fn execute_cli_shell(
1145    name: &str,
1146    command: &str,
1147    argv: Option<&[String]>,
1148    is_passthrough: bool,
1149) -> Result<
1150    (
1151        shell::ShellDispatchObservation,
1152        Option<core::execution_lifecycle::LifecycleGuard<'static>>,
1153    ),
1154    i32,
1155> {
1156    let prepared = match argv {
1157        Some(args) => shell::prepare_exec_argv(args),
1158        None => shell::prepare_exec(command),
1159    }?;
1160    let lifecycle = (!is_passthrough).then(|| {
1161        external_lifecycle_guard(
1162            name,
1163            Some(command),
1164            core::execution_lifecycle::ToolSurface::Cli,
1165        )
1166    });
1167    if let Some(guard) = &lifecycle {
1168        let _ = guard
1169            .context()
1170            .advance(core::execution_lifecycle::LifecycleStage::DispatchPrimitive);
1171    }
1172    let observation = shell::execute_prepared(prepared);
1173    if let Some(guard) = &lifecycle {
1174        use core::execution_lifecycle::LifecycleStage;
1175        for stage in [
1176            LifecycleStage::ReversiblePostProcess,
1177            LifecycleStage::RecordContextIr,
1178            LifecycleStage::RecordLedger,
1179            LifecycleStage::RecordEvidence,
1180        ] {
1181            let _ = guard
1182                .context()
1183                .skip(stage, "CLI shell adapter has no artifact observation");
1184        }
1185        let _ = guard.complete(cli_shell_completion(observation.exit_code));
1186    }
1187    Ok((observation, lifecycle))
1188}
1189
1190fn cli_shell_completion(code: i32) -> core::execution_lifecycle::CompletionObservation {
1191    let mut observation =
1192        core::execution_lifecycle::CompletionObservation::tool_result(0, 0, "cli-shell", code == 0);
1193    "local".clone_into(&mut observation.provider);
1194    observation.outcome_signals.clear();
1195    observation
1196}
1197
1198#[cfg(all(test, unix))]
1199#[path = "cli_shell_admission_tests.rs"]
1200mod cli_shell_admission_tests;
1201
1202pub(super) fn external_lifecycle_guard(
1203    tool_name: &str,
1204    query: Option<&str>,
1205    surface: core::execution_lifecycle::ToolSurface,
1206) -> core::execution_lifecycle::LifecycleGuard<'static> {
1207    let session_id = std::env::var("CODEX_THREAD_ID")
1208        .or_else(|_| std::env::var("CLAUDE_SESSION_ID"))
1209        .unwrap_or_else(|_| format!("cli-{}", std::process::id()));
1210    let project_root = std::env::current_dir()
1211        .ok()
1212        .map(|path| path.to_string_lossy().into_owned());
1213    let lifecycle = core::execution_lifecycle::ExecutionLifecycle::global();
1214    let context = lifecycle.begin(
1215        core::execution_lifecycle::ToolRequest {
1216            tool_name: tool_name.to_owned(),
1217            query: query.map(str::to_owned),
1218            session_id,
1219            agent_id: "cli".to_owned(),
1220            surface,
1221            idempotency_key: None,
1222        },
1223        core::execution_lifecycle::RuntimeContext {
1224            client_name: Some("lean-ctx-cli".to_owned()),
1225            project_root,
1226        },
1227        core::execution_lifecycle::ProductEntitlements::default(),
1228    );
1229    core::execution_lifecycle::LifecycleGuard::new(lifecycle, context)
1230}
1231
1232fn handle_setup(rest: &[String]) {
1233    if rest.first().map(String::as_str) == Some("codex-protected") {
1234        let code = super::cmd_setup_codex_protected(&rest[1..]);
1235        if code != 0 {
1236            std::process::exit(code);
1237        }
1238        return;
1239    }
1240    // Safety (#476 class): `--help`/`-h` — or any unknown flag — must NEVER
1241    // fall through to a real setup run that mutates shell + agent configs.
1242    if rest.iter().any(|a| a == "--help" || a == "-h") {
1243        print_setup_help();
1244        return;
1245    }
1246    if rest == ["runtime", "configure"] || rest == ["runtime", "configure", "--staging"] {
1247        if !setup::configure_runtime() {
1248            std::process::exit(2);
1249        }
1250        return;
1251    }
1252    if rest.first().map(String::as_str) == Some("runtime") {
1253        crate::cli::cmd_engine(rest);
1254        return;
1255    }
1256    const KNOWN: &[&str] = &[
1257        "--non-interactive",
1258        "--yes",
1259        "-y",
1260        "--fix",
1261        "--json",
1262        "--no-auto-approve",
1263        "--skip-rules",
1264        "--no-agent-aliases",
1265    ];
1266    if let Some(unknown) = rest.iter().find(|a| !KNOWN.contains(&a.as_str())) {
1267        eprintln!("setup: unknown flag or argument '{unknown}'\n");
1268        print_setup_help();
1269        std::process::exit(2);
1270    }
1271    let non_interactive = rest.iter().any(|a| a == "--non-interactive");
1272    let yes = rest.iter().any(|a| a == "--yes" || a == "-y");
1273    let fix = rest.iter().any(|a| a == "--fix");
1274    let json = rest.iter().any(|a| a == "--json");
1275    let no_auto_approve = rest.iter().any(|a| a == "--no-auto-approve");
1276    let skip_rules = rest.iter().any(|a| a == "--skip-rules");
1277    let no_agent_aliases = rest.iter().any(|a| a == "--no-agent-aliases");
1278
1279    if no_agent_aliases {
1280        let _ = crate::core::config::setter::set_by_key("skip_agent_aliases", "true");
1281    }
1282
1283    if non_interactive || fix || json || yes {
1284        let opts = setup::SetupOptions {
1285            non_interactive,
1286            yes,
1287            fix,
1288            json,
1289            no_auto_approve,
1290            skip_rules,
1291            ..Default::default()
1292        };
1293        run_setup_options(opts, json);
1294    } else {
1295        setup::run_setup();
1296    }
1297}
1298
1299fn handle_onboard(rest: &[String]) {
1300    if rest.iter().any(|a| a == "--help" || a == "-h") {
1301        println!("Usage: lean-ctx onboard [--no-agent-aliases]");
1302        println!("Connect your AI tools with one command: detects installed");
1303        println!("agents, installs hooks/rules/MCP registrations, verifies.");
1304        println!();
1305        println!("  --no-agent-aliases  Do not install claude/codex/gemini shell aliases");
1306        println!();
1307        println!("Fine-grained control: lean-ctx setup --help");
1308        return;
1309    }
1310    if rest.iter().any(|a| a == "--no-agent-aliases") {
1311        let _ = crate::core::config::setter::set_by_key("skip_agent_aliases", "true");
1312    }
1313    setup::run_onboard();
1314}
1315
1316fn handle_install(rest: &[String]) {
1317    // Plain `lean-ctx install` is a natural thing to type after installing the
1318    // binary; keep it as guided setup unless repair mode was explicitly asked.
1319    let repair = rest.iter().any(|a| a == "--repair" || a == "--fix");
1320    let json = rest.iter().any(|a| a == "--json");
1321    if !repair {
1322        setup::run_setup();
1323        return;
1324    }
1325    run_repair_setup(json);
1326}
1327
1328fn handle_bootstrap(rest: &[String]) {
1329    let json = rest.iter().any(|a| a == "--json");
1330    run_repair_setup(json);
1331}
1332
1333fn run_repair_setup(json: bool) {
1334    let opts = setup::SetupOptions {
1335        non_interactive: true,
1336        yes: true,
1337        fix: true,
1338        json,
1339        ..Default::default()
1340    };
1341    run_setup_options(opts, json);
1342}
1343
1344fn handle_raw(args: &[String], rest: &[String]) -> ! {
1345    if rest.is_empty() {
1346        eprintln!("Usage: lean-ctx raw \"command\"");
1347        eprintln!(
1348            "Runs the command with output passed through unchanged (no compression). \
1349             The shell allowlist still applies."
1350        );
1351        std::process::exit(1);
1352    }
1353    let command = if rest.len() == 1 {
1354        rest[0].clone()
1355    } else {
1356        shell::join_command(&args[2..])
1357    };
1358    core::runtime_flags::enable_raw();
1359    let code = shell::exec(&command);
1360    std::process::exit(code);
1361}
1362
1363fn run_setup_options(opts: setup::SetupOptions, json: bool) {
1364    match setup::run_setup_with_options(opts) {
1365        Ok(report) => {
1366            if json {
1367                println!(
1368                    "{}",
1369                    serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_string())
1370                );
1371            }
1372            if !report.success {
1373                std::process::exit(1);
1374            }
1375        }
1376        Err(e) => {
1377            eprintln!("{e}");
1378            std::process::exit(1);
1379        }
1380    }
1381}
1382
1383/// Restore the default SIGPIPE disposition for short-lived CLI invocations.
1384///
1385/// Rust's runtime ignores SIGPIPE process-wide, so `lean-ctx doctor | head`
1386/// made `println!` panic with BrokenPipe; the LineWriter flush in stdout's
1387/// Drop then panicked again *during unwinding*, which aborts — the SIGABRT
1388/// (exit 134) of upstream #378 / GL#436. Real CLIs (cat, grep, rg) terminate
1389/// silently with exit 141 instead; SIG_DFL gives us exactly that. Children
1390/// spawned via std::process::Command are unaffected either way (std resets
1391/// their SIGPIPE disposition since Rust 1.65).
1392#[cfg(unix)]
1393fn restore_sigpipe_default() {
1394    // SAFETY: signal(2) with SIG_DFL has no preconditions and is called once
1395    // during single-threaded startup, before any I/O.
1396    unsafe {
1397        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
1398    }
1399}
1400
1401#[cfg(not(unix))]
1402fn restore_sigpipe_default() {}
1403
1404/// Run the command raw in the user's shell. Pass-through only skips lean-ctx
1405/// compression; the allowlist is a security boundary and applies exactly as on
1406/// the compress path. An agent process can inherit `LEAN_CTX_WRAPPED` from a
1407/// wrapped parent, so every Bash-hook rewrite to `lean-ctx -c` landed here and
1408/// ran unchecked (GH #2004, a regression of the #1408 fix).
1409fn passthrough(command: &str) -> ! {
1410    if let Some(code) = shell::exec::allowlist_gate(command) {
1411        std::process::exit(code);
1412    }
1413    let (shell, flag) = shell::shell_and_flag();
1414    let mut cmd = std::process::Command::new(&shell);
1415    cmd.arg(&flag).arg(command);
1416    shell::reentry::mark_child(&mut cmd);
1417    shell::platform::apply_utf8_locale(&mut cmd);
1418    let status = cmd.status().map_or(127, shell::exit_status::exit_code);
1419    std::process::exit(status);
1420}
1421
1422pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
1423    // A failed runtime build (e.g. exhausted FDs) must not abort with a panic
1424    // backtrace the user can't act on — report it plainly and exit.
1425    match tokio::runtime::Runtime::new() {
1426        Ok(rt) => rt.block_on(future),
1427        Err(e) => {
1428            eprintln!("lean-ctx: failed to create async runtime: {e}");
1429            std::process::exit(1);
1430        }
1431    }
1432}
1433
1434#[cfg(test)]
1435mod tests;
1436
1437#[cfg(test)]
1438mod env_prefix_tests;