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