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