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