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