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