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