Skip to main content

lean_ctx_cli/cli/dispatch/
mod.rs

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