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