Skip to main content

lean_ctx_cli/cli/dispatch/
mod.rs

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