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