Skip to main content

lean_ctx/cli/dispatch/
mod.rs

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