Skip to main content

lean_ctx_cli/cli/dispatch/
mod.rs

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