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
5mod analytics;
6mod help;
7mod lifecycle;
8mod network;
9mod server;
10
11#[allow(clippy::wildcard_imports)]
12use analytics::*;
13#[allow(clippy::wildcard_imports)]
14use help::*;
15#[allow(clippy::wildcard_imports)]
16use lifecycle::*;
17#[allow(clippy::wildcard_imports)]
18use network::*;
19#[allow(clippy::wildcard_imports)]
20use server::*;
21
22pub fn run() {
23    let mut args: Vec<String> = std::env::args().collect();
24
25    // On Linux, if the binary was replaced while running, systemd may write
26    // the path with " (deleted)" suffix into ExecStart, causing "(deleted)"
27    // to appear as an argument. Strip it defensively.
28    if args.get(1).is_some_and(|a| a == "(deleted)") {
29        args.remove(1);
30    }
31
32    if !is_server_mode(&args) {
33        restore_sigpipe_default();
34    }
35
36    let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
37    if !enters_mcp {
38        crate::core::logging::init_logging();
39    }
40
41    if args.len() > 1 {
42        let rest = args[2..].to_vec();
43
44        match args[1].as_str() {
45            "-c" | "exec" => {
46                let raw = rest.first().is_some_and(|a| a == "--raw");
47                let cmd_args = if raw { &args[3..] } else { &args[2..] };
48                let command = if cmd_args.len() == 1 {
49                    cmd_args[0].clone()
50                } else {
51                    shell::join_command(cmd_args)
52                };
53                // The `lean-ctx -c` wrapper runs inside the agent shell, which
54                // carries runtime/session vars the MCP server never sees. Bridge
55                // them so ctx_shell can forward them too (#370).
56                core::agent_runtime_env::capture();
57                if std::env::var("LEAN_CTX_ACTIVE").is_ok()
58                    || std::env::var("LEAN_CTX_DISABLED").is_ok()
59                {
60                    passthrough(&command);
61                }
62                if raw {
63                    // SAFETY: CLI dispatch is single-threaded; this runs before any
64                    // worker threads start (the process hands off to shell::exec below).
65                    unsafe { std::env::set_var("LEAN_CTX_RAW", "1") };
66                } else {
67                    // SAFETY: CLI dispatch is single-threaded; this runs before any
68                    // worker threads start (the process hands off to shell::exec below).
69                    unsafe { std::env::set_var("LEAN_CTX_COMPRESS", "1") };
70                }
71                let code = shell::exec(&command);
72                core::stats::flush();
73                core::heatmap::flush();
74                core::path_mode_memory::flush();
75                core::auto_mode_resolver::flush_sources();
76                std::process::exit(code);
77            }
78            "-t" | "--track" => {
79                let cmd_args = &args[2..];
80                let code = if cmd_args.len() > 1 {
81                    shell::exec_argv(cmd_args)
82                } else {
83                    let command = cmd_args[0].clone();
84                    if std::env::var("LEAN_CTX_ACTIVE").is_ok()
85                        || std::env::var("LEAN_CTX_DISABLED").is_ok()
86                    {
87                        passthrough(&command);
88                    }
89                    shell::exec(&command)
90                };
91                core::stats::flush();
92                core::heatmap::flush();
93                core::path_mode_memory::flush();
94                core::auto_mode_resolver::flush_sources();
95                std::process::exit(code);
96            }
97            "shell" | "--shell" => {
98                shell::interactive();
99                return;
100            }
101            "gain" => {
102                cmd_gain(&rest);
103                return;
104            }
105            "savings" => {
106                cmd_savings(&rest);
107                return;
108            }
109            "learning" => {
110                cmd_learning(&rest);
111                return;
112            }
113            "conformance" | "selftest" => {
114                cmd_conformance(&rest);
115                return;
116            }
117            "billing" => {
118                cmd_billing(&rest);
119                return;
120            }
121            "finops" => {
122                cmd_finops(&rest);
123                return;
124            }
125            "roi" => {
126                // Local ROI is individual + free. The team roll-up lives on its own
127                // surface (`savings team` / the web account), not under `roi`.
128                super::cmd_roi(&rest);
129                return;
130            }
131            "token-report" | "report-tokens" => {
132                let code = token_report::run_cli(&rest);
133                if code != 0 {
134                    std::process::exit(code);
135                }
136                return;
137            }
138            "pack" => {
139                crate::cli::cmd_pack(&rest);
140                return;
141            }
142            "policy" => {
143                crate::cli::cmd_policy(&rest);
144                return;
145            }
146            "plugin" | "plugins" => {
147                crate::cli::plugin_cmd::cmd_plugin(&rest);
148                return;
149            }
150            "rules" => {
151                crate::cli::rules_cmd::cmd_rules(&rest);
152                return;
153            }
154            "proof" => {
155                crate::cli::cmd_proof(&rest);
156                return;
157            }
158            "verify" => {
159                crate::cli::cmd_verify(&rest);
160                return;
161            }
162            "eval" => {
163                crate::cli::eval_cmd::cmd_eval(&rest);
164                return;
165            }
166            "verify-cache" | "cache-selftest" => {
167                let code = crate::cli::verify_cache_cmd::cmd_verify_cache(&rest);
168                if code != 0 {
169                    std::process::exit(code);
170                }
171                return;
172            }
173            "visualize" => {
174                super::cmd_visualize(&rest);
175                return;
176            }
177            "audit" => {
178                if rest.first().map(String::as_str) == Some("evidence") {
179                    crate::cli::audit_report::cmd_evidence(&rest[1..]);
180                } else {
181                    println!("{}", crate::cli::audit_report::generate_report());
182                }
183                return;
184            }
185            "agent" => {
186                crate::cli::cmd_agent(&rest);
187                return;
188            }
189            "instructions" => {
190                crate::cli::cmd_instructions(&rest);
191                return;
192            }
193            "index" => {
194                crate::cli::cmd_index(&rest);
195                return;
196            }
197            "semantic-search" | "search-code" => {
198                crate::cli::cmd_semantic_search(&rest);
199                core::stats::flush();
200                return;
201            }
202            "repomap" | "repo-map" => {
203                crate::cli::cmd_repomap(&rest);
204                core::stats::flush();
205                return;
206            }
207            "cep" => {
208                println!("{}", core::stats::format_cep_report());
209                return;
210            }
211            "dashboard" => {
212                cmd_dashboard(&rest);
213                return;
214            }
215            "team" => {
216                cmd_team(&rest);
217                return;
218            }
219            "provider" => {
220                cmd_provider(&rest);
221                return;
222            }
223            "serve" => {
224                cmd_serve(&rest);
225                return;
226            }
227            "watch" => {
228                cmd_watch(&rest);
229                return;
230            }
231            "proxy" => {
232                cmd_proxy(&rest);
233                return;
234            }
235            "daemon" => {
236                cmd_daemon(&rest);
237                return;
238            }
239            "init" => {
240                super::cmd_init(&rest);
241                return;
242            }
243            "setup" => {
244                let non_interactive = rest.iter().any(|a| a == "--non-interactive");
245                let yes = rest.iter().any(|a| a == "--yes" || a == "-y");
246                let fix = rest.iter().any(|a| a == "--fix");
247                let json = rest.iter().any(|a| a == "--json");
248                let no_auto_approve = rest.iter().any(|a| a == "--no-auto-approve");
249                let skip_rules = rest.iter().any(|a| a == "--skip-rules");
250
251                if non_interactive || fix || json || yes {
252                    let opts = setup::SetupOptions {
253                        non_interactive,
254                        yes,
255                        fix,
256                        json,
257                        no_auto_approve,
258                        skip_rules,
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                } else {
280                    setup::run_setup();
281                }
282                return;
283            }
284            "onboard" => {
285                setup::run_onboard();
286                return;
287            }
288            "install" => {
289                // Plain `lean-ctx install` is a natural thing to type after
290                // installing the binary — treat it as the guided setup rather
291                // than failing with a usage error. `--repair`/`--fix` keeps the
292                // non-interactive, merge-based repair path.
293                let repair = rest.iter().any(|a| a == "--repair" || a == "--fix");
294                let json = rest.iter().any(|a| a == "--json");
295                if !repair {
296                    setup::run_setup();
297                    return;
298                }
299                let opts = setup::SetupOptions {
300                    non_interactive: true,
301                    yes: true,
302                    fix: true,
303                    json,
304                    ..Default::default()
305                };
306                match setup::run_setup_with_options(opts) {
307                    Ok(report) => {
308                        if json {
309                            println!(
310                                "{}",
311                                serde_json::to_string_pretty(&report)
312                                    .unwrap_or_else(|_| "{}".to_string())
313                            );
314                        }
315                        if !report.success {
316                            std::process::exit(1);
317                        }
318                    }
319                    Err(e) => {
320                        eprintln!("{e}");
321                        std::process::exit(1);
322                    }
323                }
324                return;
325            }
326            "bootstrap" => {
327                let json = rest.iter().any(|a| a == "--json");
328                let opts = setup::SetupOptions {
329                    non_interactive: true,
330                    yes: true,
331                    fix: true,
332                    json,
333                    ..Default::default()
334                };
335                match setup::run_setup_with_options(opts) {
336                    Ok(report) => {
337                        if json {
338                            println!(
339                                "{}",
340                                serde_json::to_string_pretty(&report)
341                                    .unwrap_or_else(|_| "{}".to_string())
342                            );
343                        }
344                        if !report.success {
345                            std::process::exit(1);
346                        }
347                    }
348                    Err(e) => {
349                        eprintln!("{e}");
350                        std::process::exit(1);
351                    }
352                }
353                return;
354            }
355            "status" => {
356                let code = status::run_cli(&rest);
357                if code != 0 {
358                    std::process::exit(code);
359                }
360                return;
361            }
362            "read" => {
363                super::cmd_read(&rest);
364                core::stats::flush();
365                return;
366            }
367            "call" => {
368                super::cmd_call(&rest);
369                return;
370            }
371            "diff" => {
372                super::cmd_diff(&rest);
373                core::stats::flush();
374                return;
375            }
376            "grep" => {
377                super::cmd_grep(&rest);
378                core::stats::flush();
379                return;
380            }
381            "find" => {
382                super::cmd_find(&rest);
383                core::stats::flush();
384                return;
385            }
386            "ls" => {
387                super::cmd_ls(&rest);
388                core::stats::flush();
389                return;
390            }
391            "deps" => {
392                super::cmd_deps(&rest);
393                core::stats::flush();
394                return;
395            }
396            "discover" => {
397                super::cmd_discover(&rest);
398                return;
399            }
400            "ghost" => {
401                super::cmd_ghost(&rest);
402                return;
403            }
404            "filter" => {
405                super::cmd_filter(&rest);
406                return;
407            }
408            "heatmap" => {
409                heatmap::cmd_heatmap(&rest);
410                return;
411            }
412            "graph" => {
413                cmd_graph(&rest);
414                return;
415            }
416            "smells" => {
417                cmd_smells(&rest);
418                return;
419            }
420            "session" => {
421                super::cmd_session_action(&rest);
422                return;
423            }
424            "ledger" => {
425                super::cmd_ledger(&rest);
426                return;
427            }
428            "control" | "context-control" => {
429                super::cmd_control(&rest);
430                return;
431            }
432            "plan" | "context-plan" => {
433                super::cmd_plan(&rest);
434                return;
435            }
436            "compile" | "context-compile" => {
437                super::cmd_compile(&rest);
438                return;
439            }
440            "knowledge" => {
441                super::cmd_knowledge(&rest);
442                return;
443            }
444            "skillify" => {
445                super::cmd_skillify(&rest);
446                return;
447            }
448            "summary" => {
449                super::cmd_summary(&rest);
450                return;
451            }
452            "overview" => {
453                super::cmd_overview(&rest);
454                return;
455            }
456            "compress" => {
457                super::cmd_compress(&rest);
458                return;
459            }
460            "wrapped" => {
461                eprintln!("'lean-ctx wrapped' has been removed. Use: lean-ctx gain --wrapped");
462                std::process::exit(1);
463            }
464            "sessions" | "session-store" => {
465                super::cmd_sessions(&rest);
466                return;
467            }
468            "benchmark" => {
469                super::cmd_benchmark(&rest);
470                return;
471            }
472            "compact" => {
473                cmd_compact(&rest);
474                return;
475            }
476            "profile" => {
477                super::cmd_profile(&rest);
478                return;
479            }
480            "tools" => {
481                // Canonical, unambiguous entry point for MCP *tool* profiles
482                // (how many tools the agent sees). Disambiguates from
483                // `lean-ctx profile`, which manages *context* profiles.
484                let mut forwarded = vec!["tools".to_string()];
485                forwarded.extend(rest.iter().cloned());
486                super::cmd_profile(&forwarded);
487                return;
488            }
489            "config" => {
490                super::cmd_config(&rest);
491                return;
492            }
493            "allow" => {
494                super::cmd_allow(&rest);
495                return;
496            }
497            "stats" => {
498                super::cmd_stats(&rest);
499                return;
500            }
501            "cache" => {
502                super::cmd_cache(&rest);
503                return;
504            }
505            "theme" => {
506                super::cmd_theme(&rest);
507                return;
508            }
509            "tee" => {
510                super::cmd_tee(&rest);
511                return;
512            }
513            "terse" | "compression" => {
514                super::cmd_compression(&rest);
515                return;
516            }
517            "slow-log" => {
518                super::cmd_slow_log(&rest);
519                return;
520            }
521            // Editor focus ingress (#500): called by the VS Code extension on
522            // tab change; <10ms, no daemon required.
523            "editor-signal" => {
524                let file = rest
525                    .iter()
526                    .position(|a| a == "--file")
527                    .and_then(|i| rest.get(i + 1));
528                if let Some(path) = file {
529                    if let Err(e) = core::editor_signal::record_focus(path) {
530                        eprintln!("editor-signal: {e}");
531                        std::process::exit(1);
532                    }
533                } else {
534                    eprintln!("usage: lean-ctx editor-signal --file <path>");
535                    std::process::exit(2);
536                }
537                return;
538            }
539            "update" | "--self-update" => {
540                core::updater::run(&rest);
541                return;
542            }
543            "restart" => {
544                cmd_restart();
545                return;
546            }
547            "stop" => {
548                cmd_stop();
549                return;
550            }
551            "dev-install" => {
552                cmd_dev_install();
553                return;
554            }
555            "codesign-setup" => {
556                cmd_codesign_setup();
557                return;
558            }
559            "doctor" => {
560                let code = doctor::run_cli(&rest);
561                if code != 0 {
562                    std::process::exit(code);
563                }
564                return;
565            }
566            "harden" => {
567                super::harden::run(&rest);
568                return;
569            }
570            "export-rules" => {
571                super::export_rules::run(&rest);
572                return;
573            }
574            "gotchas" | "bugs" => {
575                super::cloud::cmd_gotchas(&rest);
576                return;
577            }
578            "learn" => {
579                super::cmd_learn(&rest);
580                return;
581            }
582            "buddy" | "pet" => {
583                super::cloud::cmd_buddy(&rest);
584                return;
585            }
586            "hook" => {
587                hook_handlers::mark_hook_environment();
588                // Hooks run inside the agent shell environment, so they can see
589                // runtime/session vars (e.g. CODEX_THREAD_ID) that the long-lived
590                // MCP server process never receives. Bridge them for ctx_shell (#370).
591                core::agent_runtime_env::capture();
592                hook_handlers::arm_watchdog(std::time::Duration::from_secs(5));
593                let action = rest.first().map_or("help", std::string::String::as_str);
594                match action {
595                    "rewrite" => hook_handlers::handle_rewrite(),
596                    "redirect" => hook_handlers::handle_redirect(),
597                    "observe" => hook_handlers::handle_observe(),
598                    "copilot" => hook_handlers::handle_copilot(),
599                    "codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
600                    "codex-session-start" => hook_handlers::handle_codex_session_start(),
601                    "rewrite-inline" => hook_handlers::handle_rewrite_inline(),
602                    _ => {
603                        eprintln!(
604                            "Usage: lean-ctx hook <rewrite|redirect|observe|copilot|codex-pretooluse|codex-session-start|rewrite-inline>"
605                        );
606                        eprintln!(
607                            "  Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)"
608                        );
609                        std::process::exit(1);
610                    }
611                }
612                return;
613            }
614            "report-issue" | "report" => {
615                report::run(&rest);
616                return;
617            }
618            "uninstall" => {
619                let dry_run = rest.iter().any(|a| a == "--dry-run");
620                let keep_config = rest.iter().any(|a| a == "--keep-config");
621                let keep_binary = rest.iter().any(|a| a == "--keep-binary");
622                uninstall::run(dry_run, keep_config, keep_binary);
623                return;
624            }
625            "bypass" => {
626                if rest.is_empty() {
627                    eprintln!("Usage: lean-ctx bypass \"command\"");
628                    eprintln!("Runs the command with zero compression (raw passthrough).");
629                    std::process::exit(1);
630                }
631                let command = if rest.len() == 1 {
632                    rest[0].clone()
633                } else {
634                    shell::join_command(&args[2..])
635                };
636                // SAFETY: CLI dispatch is single-threaded; this runs before the
637                // process hands off to shell::exec and exits below.
638                unsafe { std::env::set_var("LEAN_CTX_RAW", "1") };
639                let code = shell::exec(&command);
640                std::process::exit(code);
641            }
642            "safety-levels" | "safety" => {
643                println!("{}", core::compression_safety::format_safety_table());
644                return;
645            }
646            "cheat" | "cheatsheet" | "cheat-sheet" => {
647                super::cmd_cheatsheet();
648                return;
649            }
650            "login" => {
651                super::cloud::cmd_login(&rest);
652                return;
653            }
654            "register" => {
655                super::cloud::cmd_register(&rest);
656                return;
657            }
658            "forgot-password" => {
659                super::cloud::cmd_forgot_password(&rest);
660                return;
661            }
662            "sync" => {
663                super::cloud::cmd_sync(&rest);
664                return;
665            }
666            "contribute" => {
667                super::cloud::cmd_contribute();
668                return;
669            }
670            "cloud" => {
671                super::cloud::cmd_cloud(&rest);
672                return;
673            }
674            "upgrade" => {
675                super::cloud::cmd_upgrade();
676                return;
677            }
678            "--version" | "-V" => {
679                println!("{}", core::integrity::origin_line());
680                return;
681            }
682            "help" => {
683                let want_all = rest
684                    .iter()
685                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
686                if want_all {
687                    print_help();
688                } else {
689                    print_help_concise();
690                }
691                return;
692            }
693            "--help" | "-h" => {
694                if rest
695                    .iter()
696                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
697                {
698                    print_help();
699                } else {
700                    print_help_concise();
701                }
702                return;
703            }
704            "mcp" => {}
705            _ => {
706                tracing::error!("lean-ctx: unknown command '{}'", args[1]);
707                print_help_concise();
708                std::process::exit(1);
709            }
710        }
711    }
712
713    // Bare `lean-ctx` in an interactive terminal: a human almost certainly did
714    // not mean to start a silent stdio MCP server (which just hangs waiting for
715    // JSON-RPC). Show a short quickstart instead. MCP clients pipe stdin (not a
716    // TTY) so they still get the server, and explicit `lean-ctx mcp` always
717    // serves regardless of TTY.
718    if args.len() == 1 && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
719        print_quickstart();
720        return;
721    }
722
723    if let Err(e) = run_mcp_server() {
724        tracing::error!("lean-ctx: {e}");
725        std::process::exit(1);
726    }
727}
728
729/// Long-lived server entry points keep Rust's default ignored SIGPIPE: they
730/// must survive peers closing sockets/pipes early. Bare `lean-ctx` counts as
731/// a server because MCP clients spawn the binary without a subcommand.
732fn is_server_mode(args: &[String]) -> bool {
733    args.len() == 1
734        || args.get(1).is_some_and(|a| {
735            matches!(
736                a.as_str(),
737                "mcp" | "daemon" | "proxy" | "serve" | "watch" | "dashboard"
738            )
739        })
740}
741
742/// Restore the default SIGPIPE disposition for short-lived CLI invocations.
743///
744/// Rust's runtime ignores SIGPIPE process-wide, so `lean-ctx doctor | head`
745/// made `println!` panic with BrokenPipe; the LineWriter flush in stdout's
746/// Drop then panicked again *during unwinding*, which aborts — the SIGABRT
747/// (exit 134) of upstream #378 / GL#436. Real CLIs (cat, grep, rg) terminate
748/// silently with exit 141 instead; SIG_DFL gives us exactly that. Children
749/// spawned via std::process::Command are unaffected either way (std resets
750/// their SIGPIPE disposition since Rust 1.65).
751#[cfg(unix)]
752fn restore_sigpipe_default() {
753    // SAFETY: signal(2) with SIG_DFL has no preconditions and is called once
754    // during single-threaded startup, before any I/O.
755    unsafe {
756        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
757    }
758}
759
760#[cfg(not(unix))]
761fn restore_sigpipe_default() {}
762
763fn passthrough(command: &str) -> ! {
764    let (shell, flag) = shell::shell_and_flag();
765    let mut cmd = std::process::Command::new(&shell);
766    cmd.arg(&flag).arg(command).env("LEAN_CTX_ACTIVE", "1");
767    shell::platform::apply_utf8_locale(&mut cmd);
768    let status = cmd.status().map_or(127, |s| s.code().unwrap_or(1));
769    std::process::exit(status);
770}
771
772pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
773    tokio::runtime::Runtime::new()
774        .expect("failed to create async runtime")
775        .block_on(future)
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781    use serial_test::serial;
782
783    fn args_of(parts: &[&str]) -> Vec<String> {
784        parts.iter().map(|s| (*s).to_string()).collect()
785    }
786
787    #[test]
788    fn server_modes_keep_ignored_sigpipe() {
789        for mode in ["mcp", "daemon", "proxy", "serve", "watch", "dashboard"] {
790            assert!(
791                is_server_mode(&args_of(&["lean-ctx", mode])),
792                "{mode} must count as server mode"
793            );
794        }
795        // Bare invocation = MCP server spawned by a client.
796        assert!(is_server_mode(&args_of(&["lean-ctx"])));
797    }
798
799    #[test]
800    fn cli_modes_restore_default_sigpipe() {
801        for mode in ["doctor", "-c", "status", "ls", "grep", "gain", "help"] {
802            assert!(
803                !is_server_mode(&args_of(&["lean-ctx", mode])),
804                "{mode} must count as CLI mode (SIGPIPE default)"
805            );
806        }
807    }
808
809    #[test]
810    fn quickstart_is_short_and_points_to_setup() {
811        let q = quickstart_text();
812        assert!(
813            q.contains("lean-ctx onboard"),
814            "quickstart must point to onboard"
815        );
816        assert!(q.contains("lean-ctx help"), "quickstart must point to help");
817        // Must stay a *quickstart*, not the full reference — keep it tight.
818        assert!(
819            q.lines().count() <= 16,
820            "quickstart should be short; got {} lines",
821            q.lines().count()
822        );
823        assert!(
824            !q.contains("COMMANDS:"),
825            "quickstart must not inline the full command reference"
826        );
827    }
828
829    #[test]
830    fn concise_help_is_short_and_points_to_full() {
831        let h = concise_help_text();
832        assert!(h.contains("lean-ctx onboard"), "must lead with onboard");
833        assert!(
834            h.contains("lean-ctx help all"),
835            "must point to full reference"
836        );
837        assert!(
838            h.contains("lean-ctx tools"),
839            "must surface the tools profile command"
840        );
841        // Concise means concise — keep it well under the full reference.
842        assert!(
843            h.lines().count() <= 40,
844            "concise help should stay short; got {} lines",
845            h.lines().count()
846        );
847        assert!(
848            !h.contains("SHELL HOOK PATTERNS"),
849            "concise help must not inline the full pattern catalog"
850        );
851    }
852
853    #[test]
854    fn capability_banner_tool_count_matches_registry() {
855        let n = crate::server::registry::tool_count();
856        let banner = capability_banner();
857        assert!(
858            banner.contains(&format!("{n} MCP tools")),
859            "banner must show the live registry count ({n}); got: {banner}"
860        );
861    }
862
863    #[test]
864    #[serial]
865    fn worker_threads_default_clamps_low() {
866        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
867        assert_eq!(resolve_worker_threads(1), 1);
868    }
869
870    #[test]
871    #[serial]
872    fn worker_threads_default_clamps_high() {
873        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
874        assert_eq!(resolve_worker_threads(32), 4);
875    }
876
877    #[test]
878    #[serial]
879    fn worker_threads_default_passthrough() {
880        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
881        assert_eq!(resolve_worker_threads(3), 3);
882    }
883
884    #[test]
885    #[serial]
886    fn worker_threads_env_override() {
887        crate::test_env::set_var("LEAN_CTX_WORKER_THREADS", "12");
888        assert_eq!(resolve_worker_threads(2), 12);
889        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
890    }
891
892    #[test]
893    #[serial]
894    fn worker_threads_env_invalid_falls_back() {
895        crate::test_env::set_var("LEAN_CTX_WORKER_THREADS", "not_a_number");
896        assert_eq!(resolve_worker_threads(3), 3);
897        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
898    }
899}