Skip to main content

lean_ctx/cli/dispatch/
mod.rs

1use crate::{
2    core, doctor, heatmap, hook_handlers, report, setup, shell, status, token_report, tools,
3    uninstall,
4};
5
6mod analytics;
7mod help;
8mod lifecycle;
9mod network;
10mod server;
11
12#[allow(clippy::wildcard_imports)]
13use analytics::*;
14#[allow(clippy::wildcard_imports)]
15use help::*;
16#[allow(clippy::wildcard_imports)]
17use lifecycle::*;
18#[allow(clippy::wildcard_imports)]
19use network::*;
20#[allow(clippy::wildcard_imports)]
21use server::*;
22
23pub fn run() {
24    let mut args: Vec<String> = std::env::args().collect();
25
26    // On Linux, if the binary was replaced while running, systemd may write
27    // the path with " (deleted)" suffix into ExecStart, causing "(deleted)"
28    // to appear as an argument. Strip it defensively.
29    if args.get(1).is_some_and(|a| a == "(deleted)") {
30        args.remove(1);
31    }
32
33    let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
34    if !enters_mcp {
35        crate::core::logging::init_logging();
36    }
37
38    if args.len() > 1 {
39        let rest = args[2..].to_vec();
40
41        match args[1].as_str() {
42            "-c" | "exec" => {
43                let raw = rest.first().is_some_and(|a| a == "--raw");
44                let cmd_args = if raw { &args[3..] } else { &args[2..] };
45                let command = if cmd_args.len() == 1 {
46                    cmd_args[0].clone()
47                } else {
48                    shell::join_command(cmd_args)
49                };
50                if std::env::var("LEAN_CTX_ACTIVE").is_ok()
51                    || std::env::var("LEAN_CTX_DISABLED").is_ok()
52                {
53                    passthrough(&command);
54                }
55                if raw {
56                    std::env::set_var("LEAN_CTX_RAW", "1");
57                } else {
58                    std::env::set_var("LEAN_CTX_COMPRESS", "1");
59                }
60                let code = shell::exec(&command);
61                core::stats::flush();
62                core::heatmap::flush();
63                std::process::exit(code);
64            }
65            "-t" | "--track" => {
66                let cmd_args = &args[2..];
67                let code = if cmd_args.len() > 1 {
68                    shell::exec_argv(cmd_args)
69                } else {
70                    let command = cmd_args[0].clone();
71                    if std::env::var("LEAN_CTX_ACTIVE").is_ok()
72                        || std::env::var("LEAN_CTX_DISABLED").is_ok()
73                    {
74                        passthrough(&command);
75                    }
76                    shell::exec(&command)
77                };
78                core::stats::flush();
79                core::heatmap::flush();
80                std::process::exit(code);
81            }
82            "shell" | "--shell" => {
83                shell::interactive();
84                return;
85            }
86            "gain" => {
87                cmd_gain(&rest);
88                return;
89            }
90            "token-report" | "report-tokens" => {
91                let code = token_report::run_cli(&rest);
92                if code != 0 {
93                    std::process::exit(code);
94                }
95                return;
96            }
97            "pack" => {
98                crate::cli::cmd_pack(&rest);
99                return;
100            }
101            "plugin" | "plugins" => {
102                crate::cli::plugin_cmd::cmd_plugin(&rest);
103                return;
104            }
105            "rules" => {
106                crate::cli::rules_cmd::cmd_rules(&rest);
107                return;
108            }
109            "proof" => {
110                crate::cli::cmd_proof(&rest);
111                return;
112            }
113            "verify" => {
114                crate::cli::cmd_verify(&rest);
115                return;
116            }
117            "visualize" => {
118                super::cmd_visualize(&rest);
119                return;
120            }
121            "audit" => {
122                println!("{}", crate::cli::audit_report::generate_report());
123                return;
124            }
125            "instructions" => {
126                crate::cli::cmd_instructions(&rest);
127                return;
128            }
129            "index" => {
130                crate::cli::cmd_index(&rest);
131                return;
132            }
133            "cep" => {
134                println!("{}", tools::ctx_gain::handle("score", None, None, Some(10)));
135                return;
136            }
137            "dashboard" => {
138                cmd_dashboard(&rest);
139                return;
140            }
141            "team" => {
142                cmd_team(&rest);
143                return;
144            }
145            "provider" => {
146                cmd_provider(&rest);
147                return;
148            }
149            "serve" => {
150                cmd_serve(&rest);
151                return;
152            }
153            "watch" => {
154                cmd_watch(&rest);
155                return;
156            }
157            "proxy" => {
158                cmd_proxy(&rest);
159                return;
160            }
161            "daemon" => {
162                cmd_daemon(&rest);
163                return;
164            }
165            "init" => {
166                super::cmd_init(&rest);
167                return;
168            }
169            "setup" => {
170                let non_interactive = rest.iter().any(|a| a == "--non-interactive");
171                let yes = rest.iter().any(|a| a == "--yes" || a == "-y");
172                let fix = rest.iter().any(|a| a == "--fix");
173                let json = rest.iter().any(|a| a == "--json");
174                let no_auto_approve = rest.iter().any(|a| a == "--no-auto-approve");
175                let skip_rules = rest.iter().any(|a| a == "--skip-rules");
176
177                if non_interactive || fix || json || yes {
178                    let opts = setup::SetupOptions {
179                        non_interactive,
180                        yes,
181                        fix,
182                        json,
183                        no_auto_approve,
184                        skip_rules,
185                        ..Default::default()
186                    };
187                    match setup::run_setup_with_options(opts) {
188                        Ok(report) => {
189                            if json {
190                                println!(
191                                    "{}",
192                                    serde_json::to_string_pretty(&report)
193                                        .unwrap_or_else(|_| "{}".to_string())
194                                );
195                            }
196                            if !report.success {
197                                std::process::exit(1);
198                            }
199                        }
200                        Err(e) => {
201                            eprintln!("{e}");
202                            std::process::exit(1);
203                        }
204                    }
205                } else {
206                    setup::run_setup();
207                }
208                return;
209            }
210            "onboard" => {
211                setup::run_onboard();
212                return;
213            }
214            "install" => {
215                // Plain `lean-ctx install` is a natural thing to type after
216                // installing the binary — treat it as the guided setup rather
217                // than failing with a usage error. `--repair`/`--fix` keeps the
218                // non-interactive, merge-based repair path.
219                let repair = rest.iter().any(|a| a == "--repair" || a == "--fix");
220                let json = rest.iter().any(|a| a == "--json");
221                if !repair {
222                    setup::run_setup();
223                    return;
224                }
225                let opts = setup::SetupOptions {
226                    non_interactive: true,
227                    yes: true,
228                    fix: true,
229                    json,
230                    ..Default::default()
231                };
232                match setup::run_setup_with_options(opts) {
233                    Ok(report) => {
234                        if json {
235                            println!(
236                                "{}",
237                                serde_json::to_string_pretty(&report)
238                                    .unwrap_or_else(|_| "{}".to_string())
239                            );
240                        }
241                        if !report.success {
242                            std::process::exit(1);
243                        }
244                    }
245                    Err(e) => {
246                        eprintln!("{e}");
247                        std::process::exit(1);
248                    }
249                }
250                return;
251            }
252            "bootstrap" => {
253                let json = rest.iter().any(|a| a == "--json");
254                let opts = setup::SetupOptions {
255                    non_interactive: true,
256                    yes: true,
257                    fix: true,
258                    json,
259                    ..Default::default()
260                };
261                match setup::run_setup_with_options(opts) {
262                    Ok(report) => {
263                        if json {
264                            println!(
265                                "{}",
266                                serde_json::to_string_pretty(&report)
267                                    .unwrap_or_else(|_| "{}".to_string())
268                            );
269                        }
270                        if !report.success {
271                            std::process::exit(1);
272                        }
273                    }
274                    Err(e) => {
275                        eprintln!("{e}");
276                        std::process::exit(1);
277                    }
278                }
279                return;
280            }
281            "status" => {
282                let code = status::run_cli(&rest);
283                if code != 0 {
284                    std::process::exit(code);
285                }
286                return;
287            }
288            "read" => {
289                super::cmd_read(&rest);
290                core::stats::flush();
291                return;
292            }
293            "diff" => {
294                super::cmd_diff(&rest);
295                core::stats::flush();
296                return;
297            }
298            "grep" => {
299                super::cmd_grep(&rest);
300                core::stats::flush();
301                return;
302            }
303            "find" => {
304                super::cmd_find(&rest);
305                core::stats::flush();
306                return;
307            }
308            "ls" => {
309                super::cmd_ls(&rest);
310                core::stats::flush();
311                return;
312            }
313            "deps" => {
314                super::cmd_deps(&rest);
315                core::stats::flush();
316                return;
317            }
318            "discover" => {
319                super::cmd_discover(&rest);
320                return;
321            }
322            "ghost" => {
323                super::cmd_ghost(&rest);
324                return;
325            }
326            "filter" => {
327                super::cmd_filter(&rest);
328                return;
329            }
330            "heatmap" => {
331                heatmap::cmd_heatmap(&rest);
332                return;
333            }
334            "graph" => {
335                cmd_graph(&rest);
336                return;
337            }
338            "smells" => {
339                cmd_smells(&rest);
340                return;
341            }
342            "session" => {
343                super::cmd_session_action(&rest);
344                return;
345            }
346            "ledger" => {
347                super::cmd_ledger(&rest);
348                return;
349            }
350            "control" | "context-control" => {
351                super::cmd_control(&rest);
352                return;
353            }
354            "plan" | "context-plan" => {
355                super::cmd_plan(&rest);
356                return;
357            }
358            "compile" | "context-compile" => {
359                super::cmd_compile(&rest);
360                return;
361            }
362            "knowledge" => {
363                super::cmd_knowledge(&rest);
364                return;
365            }
366            "overview" => {
367                super::cmd_overview(&rest);
368                return;
369            }
370            "compress" => {
371                super::cmd_compress(&rest);
372                return;
373            }
374            "wrapped" => {
375                super::cmd_wrapped(&rest);
376                return;
377            }
378            "sessions" | "session-store" => {
379                super::cmd_sessions(&rest);
380                return;
381            }
382            "benchmark" => {
383                super::cmd_benchmark(&rest);
384                return;
385            }
386            "compact" => {
387                cmd_compact(&rest);
388                return;
389            }
390            "profile" => {
391                super::cmd_profile(&rest);
392                return;
393            }
394            "tools" => {
395                // Canonical, unambiguous entry point for MCP *tool* profiles
396                // (how many tools the agent sees). Disambiguates from
397                // `lean-ctx profile`, which manages *context* profiles.
398                let mut forwarded = vec!["tools".to_string()];
399                forwarded.extend(rest.iter().cloned());
400                super::cmd_profile(&forwarded);
401                return;
402            }
403            "config" => {
404                super::cmd_config(&rest);
405                return;
406            }
407            "stats" => {
408                super::cmd_stats(&rest);
409                return;
410            }
411            "cache" => {
412                super::cmd_cache(&rest);
413                return;
414            }
415            "theme" => {
416                super::cmd_theme(&rest);
417                return;
418            }
419            "tee" => {
420                super::cmd_tee(&rest);
421                return;
422            }
423            "terse" | "compression" => {
424                super::cmd_compression(&rest);
425                return;
426            }
427            "slow-log" => {
428                super::cmd_slow_log(&rest);
429                return;
430            }
431            "update" | "--self-update" => {
432                core::updater::run(&rest);
433                return;
434            }
435            "restart" => {
436                cmd_restart();
437                return;
438            }
439            "stop" => {
440                cmd_stop();
441                return;
442            }
443            "dev-install" => {
444                cmd_dev_install();
445                return;
446            }
447            "doctor" => {
448                let code = doctor::run_cli(&rest);
449                if code != 0 {
450                    std::process::exit(code);
451                }
452                return;
453            }
454            "harden" => {
455                super::harden::run(&rest);
456                return;
457            }
458            "export-rules" => {
459                super::export_rules::run(&rest);
460                return;
461            }
462            "gotchas" | "bugs" => {
463                super::cloud::cmd_gotchas(&rest);
464                return;
465            }
466            "learn" => {
467                super::cmd_learn(&rest);
468                return;
469            }
470            "buddy" | "pet" => {
471                super::cloud::cmd_buddy(&rest);
472                return;
473            }
474            "hook" => {
475                hook_handlers::mark_hook_environment();
476                hook_handlers::arm_watchdog(std::time::Duration::from_secs(5));
477                let action = rest.first().map_or("help", std::string::String::as_str);
478                match action {
479                    "rewrite" => hook_handlers::handle_rewrite(),
480                    "redirect" => hook_handlers::handle_redirect(),
481                    "observe" => hook_handlers::handle_observe(),
482                    "copilot" => hook_handlers::handle_copilot(),
483                    "codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
484                    "codex-session-start" => hook_handlers::handle_codex_session_start(),
485                    "rewrite-inline" => hook_handlers::handle_rewrite_inline(),
486                    _ => {
487                        eprintln!("Usage: lean-ctx hook <rewrite|redirect|observe|copilot|codex-pretooluse|codex-session-start|rewrite-inline>");
488                        eprintln!("  Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)");
489                        std::process::exit(1);
490                    }
491                }
492                return;
493            }
494            "report-issue" | "report" => {
495                report::run(&rest);
496                return;
497            }
498            "uninstall" => {
499                let dry_run = rest.iter().any(|a| a == "--dry-run");
500                let keep_config = rest.iter().any(|a| a == "--keep-config");
501                uninstall::run(dry_run, keep_config);
502                return;
503            }
504            "bypass" => {
505                if rest.is_empty() {
506                    eprintln!("Usage: lean-ctx bypass \"command\"");
507                    eprintln!("Runs the command with zero compression (raw passthrough).");
508                    std::process::exit(1);
509                }
510                let command = if rest.len() == 1 {
511                    rest[0].clone()
512                } else {
513                    shell::join_command(&args[2..])
514                };
515                std::env::set_var("LEAN_CTX_RAW", "1");
516                let code = shell::exec(&command);
517                std::process::exit(code);
518            }
519            "safety-levels" | "safety" => {
520                println!("{}", core::compression_safety::format_safety_table());
521                return;
522            }
523            "cheat" | "cheatsheet" | "cheat-sheet" => {
524                super::cmd_cheatsheet();
525                return;
526            }
527            "login" => {
528                super::cloud::cmd_login(&rest);
529                return;
530            }
531            "register" => {
532                super::cloud::cmd_register(&rest);
533                return;
534            }
535            "forgot-password" => {
536                super::cloud::cmd_forgot_password(&rest);
537                return;
538            }
539            "sync" => {
540                super::cloud::cmd_sync();
541                return;
542            }
543            "contribute" => {
544                super::cloud::cmd_contribute();
545                return;
546            }
547            "cloud" => {
548                super::cloud::cmd_cloud(&rest);
549                return;
550            }
551            "upgrade" => {
552                super::cloud::cmd_upgrade();
553                return;
554            }
555            "--version" | "-V" => {
556                println!("{}", core::integrity::origin_line());
557                return;
558            }
559            "help" => {
560                let want_all = rest
561                    .iter()
562                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
563                if want_all {
564                    print_help();
565                } else {
566                    print_help_concise();
567                }
568                return;
569            }
570            "--help" | "-h" => {
571                if rest
572                    .iter()
573                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
574                {
575                    print_help();
576                } else {
577                    print_help_concise();
578                }
579                return;
580            }
581            "mcp" => {}
582            _ => {
583                tracing::error!("lean-ctx: unknown command '{}'", args[1]);
584                print_help_concise();
585                std::process::exit(1);
586            }
587        }
588    }
589
590    // Bare `lean-ctx` in an interactive terminal: a human almost certainly did
591    // not mean to start a silent stdio MCP server (which just hangs waiting for
592    // JSON-RPC). Show a short quickstart instead. MCP clients pipe stdin (not a
593    // TTY) so they still get the server, and explicit `lean-ctx mcp` always
594    // serves regardless of TTY.
595    if args.len() == 1 && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
596        print_quickstart();
597        return;
598    }
599
600    if let Err(e) = run_mcp_server() {
601        tracing::error!("lean-ctx: {e}");
602        std::process::exit(1);
603    }
604}
605
606fn passthrough(command: &str) -> ! {
607    let (shell, flag) = shell::shell_and_flag();
608    let mut cmd = std::process::Command::new(&shell);
609    cmd.arg(&flag).arg(command).env("LEAN_CTX_ACTIVE", "1");
610    shell::platform::apply_utf8_locale(&mut cmd);
611    let status = cmd.status().map_or(127, |s| s.code().unwrap_or(1));
612    std::process::exit(status);
613}
614
615pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
616    tokio::runtime::Runtime::new()
617        .expect("failed to create async runtime")
618        .block_on(future)
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624    use serial_test::serial;
625
626    #[test]
627    fn quickstart_is_short_and_points_to_setup() {
628        let q = quickstart_text();
629        assert!(
630            q.contains("lean-ctx onboard"),
631            "quickstart must point to onboard"
632        );
633        assert!(q.contains("lean-ctx help"), "quickstart must point to help");
634        // Must stay a *quickstart*, not the full reference — keep it tight.
635        assert!(
636            q.lines().count() <= 16,
637            "quickstart should be short; got {} lines",
638            q.lines().count()
639        );
640        assert!(
641            !q.contains("COMMANDS:"),
642            "quickstart must not inline the full command reference"
643        );
644    }
645
646    #[test]
647    fn concise_help_is_short_and_points_to_full() {
648        let h = concise_help_text();
649        assert!(h.contains("lean-ctx onboard"), "must lead with onboard");
650        assert!(
651            h.contains("lean-ctx help all"),
652            "must point to full reference"
653        );
654        assert!(
655            h.contains("lean-ctx tools"),
656            "must surface the tools profile command"
657        );
658        // Concise means concise — keep it well under the full reference.
659        assert!(
660            h.lines().count() <= 40,
661            "concise help should stay short; got {} lines",
662            h.lines().count()
663        );
664        assert!(
665            !h.contains("SHELL HOOK PATTERNS"),
666            "concise help must not inline the full pattern catalog"
667        );
668    }
669
670    #[test]
671    fn capability_banner_tool_count_matches_registry() {
672        let n = crate::server::registry::tool_count();
673        let banner = capability_banner();
674        assert!(
675            banner.contains(&format!("{n} MCP tools")),
676            "banner must show the live registry count ({n}); got: {banner}"
677        );
678    }
679
680    #[test]
681    #[serial]
682    fn worker_threads_default_clamps_low() {
683        std::env::remove_var("LEAN_CTX_WORKER_THREADS");
684        assert_eq!(resolve_worker_threads(1), 1);
685    }
686
687    #[test]
688    #[serial]
689    fn worker_threads_default_clamps_high() {
690        std::env::remove_var("LEAN_CTX_WORKER_THREADS");
691        assert_eq!(resolve_worker_threads(32), 4);
692    }
693
694    #[test]
695    #[serial]
696    fn worker_threads_default_passthrough() {
697        std::env::remove_var("LEAN_CTX_WORKER_THREADS");
698        assert_eq!(resolve_worker_threads(3), 3);
699    }
700
701    #[test]
702    #[serial]
703    fn worker_threads_env_override() {
704        std::env::set_var("LEAN_CTX_WORKER_THREADS", "12");
705        assert_eq!(resolve_worker_threads(2), 12);
706        std::env::remove_var("LEAN_CTX_WORKER_THREADS");
707    }
708
709    #[test]
710    #[serial]
711    fn worker_threads_env_invalid_falls_back() {
712        std::env::set_var("LEAN_CTX_WORKER_THREADS", "not_a_number");
713        assert_eq!(resolve_worker_threads(3), 3);
714        std::env::remove_var("LEAN_CTX_WORKER_THREADS");
715    }
716}