Skip to main content

lean_ctx/cli/dispatch/
mod.rs

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