lean-ctx 3.9.19

Context Runtime for AI Agents with CCP. 79 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
use crate::{
    core, doctor, heatmap, hook_handlers, report, setup, shell, status, token_report, uninstall,
};

mod analytics;
mod help;
mod lifecycle;
mod network;
mod server;
pub(crate) mod suggest;

#[allow(clippy::wildcard_imports)]
use analytics::*;
#[allow(clippy::wildcard_imports)]
use help::*;
#[allow(clippy::wildcard_imports)]
use lifecycle::*;
#[allow(clippy::wildcard_imports)]
use network::*;
#[allow(clippy::wildcard_imports)]
use server::*;

pub fn run() {
    let mut args: Vec<String> = std::env::args().collect();

    // On Linux, if the binary was replaced while running, systemd may write
    // the path with " (deleted)" suffix into ExecStart, causing "(deleted)"
    // to appear as an argument. Strip it defensively.
    if args.get(1).is_some_and(|a| a == "(deleted)") {
        args.remove(1);
    }

    if !is_server_mode(&args) {
        restore_sigpipe_default();
    }

    let enters_mcp = args.len() == 1 || args.get(1).is_some_and(|a| a == "mcp");
    if !enters_mcp {
        crate::core::logging::init_logging();
    }

    if args.len() > 1 {
        let rest = args[2..].to_vec();

        match args[1].as_str() {
            "-c" | "exec" => handle_exec(&args, &rest),
            "-t" | "--track" => handle_track(&args),
            "badge" => {
                crate::cli::badge_cmd::cmd_badge(&rest);
                return;
            }
            "shell" | "--shell" => {
                shell::interactive();
                return;
            }
            "gain" => {
                cmd_gain(&rest);
                return;
            }
            "spend" => {
                cmd_spend(&rest);
                return;
            }
            "savings" => {
                cmd_savings(&rest);
                return;
            }
            "learning" => {
                cmd_learning(&rest);
                return;
            }
            "conformance" | "selftest" => {
                cmd_conformance(&rest);
                return;
            }
            "health" => {
                let code = crate::cli::health_cmd::cmd_health(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "quality-lab" | "quality_lab" => {
                let code = crate::cli::quality_lab_cmd::cmd_quality_lab(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "billing" => {
                cmd_billing(&rest);
                return;
            }
            "finops" => {
                cmd_finops(&rest);
                return;
            }
            "roi" => {
                // Local ROI is individual + free. The team roll-up lives on its own
                // surface (`savings team` / the web account), not under `roi`.
                super::cmd_roi(&rest);
                return;
            }
            "output-savings" | "output_savings" => {
                // #895 Track B: measured (A/B holdout) or estimated output-token
                // reduction. Local + free, like `roi`.
                super::cmd_output_savings(&rest);
                return;
            }
            "value-report" | "value_report" => {
                super::cmd_value_report(&rest);
                return;
            }
            "evidence-export" => {
                super::cmd_evidence_export(&rest);
                return;
            }
            "shadow" => {
                super::cmd_shadow(&rest);
                return;
            }
            "triage" => {
                super::cmd_triage(&rest);
                return;
            }
            "scenario" => {
                if let Err(error) = crate::cli::scenario_cmd::cmd_scenario_from_cli(&rest) {
                    eprintln!("scenario: {error}");
                    std::process::exit(2);
                }
                return;
            }
            "measure" => {
                super::cmd_measure(&rest);
                return;
            }
            "token-report" | "report-tokens" => {
                let code = token_report::run_cli(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "pack" => {
                crate::cli::cmd_pack(&rest);
                return;
            }
            "policy" => {
                crate::cli::cmd_policy(&rest);
                return;
            }
            "plugin" | "plugins" => {
                crate::cli::plugin_cmd::cmd_plugin(&rest);
                return;
            }
            "addon" | "addons" => {
                let code = crate::cli::addon_cmd::cmd_addon(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "embeddings" => {
                crate::cli::embeddings_cmd::cmd_embeddings(&rest);
                return;
            }
            "model" => {
                crate::cli::model_cmd::cmd_model(&rest);
                return;
            }
            "enable-gpu" | "gpu" => {
                core::updater::enable_gpu(&rest);
                return;
            }
            "rules" => {
                crate::cli::rules_cmd::cmd_rules(&rest);
                return;
            }
            "proof" => {
                crate::cli::cmd_proof(&rest);
                return;
            }
            "prove" => {
                crate::cli::cmd_prove(&rest);
                return;
            }
            "snapshot" => {
                crate::cli::cmd_snapshot(&rest);
                return;
            }
            "verify" => {
                crate::cli::cmd_verify(&rest);
                return;
            }
            "eval" => {
                crate::cli::eval_cmd::cmd_eval(&rest);
                return;
            }
            "verify-cache" | "cache-selftest" => {
                let code = crate::cli::verify_cache_cmd::cmd_verify_cache(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "visualize" => {
                super::cmd_visualize(&rest);
                return;
            }
            "audit" => {
                match rest.first().map(String::as_str) {
                    Some("evidence") => crate::cli::audit_report::cmd_evidence(&rest[1..]),
                    Some("determinism") => crate::cli::audit_report::cmd_determinism(&rest[1..]),
                    _ => println!("{}", crate::cli::audit_report::generate_report()),
                }
                return;
            }
            "compliance" => {
                crate::cli::cmd_compliance(&rest);
                return;
            }
            "agent" => {
                crate::cli::cmd_agent(&rest);
                return;
            }
            "instructions" => {
                crate::cli::cmd_instructions(&rest);
                return;
            }
            "index" => {
                crate::cli::cmd_index(&rest);
                return;
            }
            "semantic-search" | "search-code" => {
                crate::cli::cmd_semantic_search(&rest);
                core::stats::flush();
                return;
            }
            "explore" => {
                crate::cli::explore_cmd::cmd_explore(&rest);
                core::stats::flush();
                return;
            }
            "repomap" | "repo-map" => {
                crate::cli::cmd_repomap(&rest);
                core::stats::flush();
                return;
            }
            "cep" => {
                println!("{}", core::stats::format_cep_report());
                return;
            }
            "demo" => {
                super::cmd_demo(&rest);
                return;
            }
            "dashboard" => {
                cmd_dashboard(&rest);
                return;
            }
            "team" => {
                cmd_team(&rest);
                return;
            }
            "provider" => {
                cmd_provider(&rest);
                return;
            }
            "serve" => {
                cmd_serve(&rest);
                return;
            }
            "watch" => {
                cmd_watch(&rest);
                return;
            }
            "proxy" => {
                cmd_proxy(&rest);
                return;
            }
            "daemon" => {
                cmd_daemon(&rest);
                return;
            }
            "init" => {
                super::cmd_init(&rest);
                return;
            }
            "setup" => {
                handle_setup(&rest);
                return;
            }
            "onboard" => {
                handle_onboard(&rest);
                return;
            }
            "install" => {
                handle_install(&rest);
                return;
            }
            "bootstrap" => {
                handle_bootstrap(&rest);
                return;
            }
            "wrap" => {
                crate::cli::wrap_cmd::cmd_wrap(&rest);
                return;
            }
            "unwrap" => {
                crate::cli::wrap_cmd::cmd_unwrap(&rest);
                return;
            }
            "status" => {
                let code = status::run_cli(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "cognitive" => {
                crate::cli::cognitive::run();
                return;
            }
            "read" => {
                super::cmd_read(&rest);
                core::tool_lifecycle::flush_all();
                return;
            }
            "call" => {
                super::cmd_call(&rest);
                return;
            }
            "diff" => {
                super::cmd_diff(&rest);
                core::tool_lifecycle::flush_all();
                return;
            }
            "grep" => {
                super::cmd_grep(&rest);
                core::tool_lifecycle::flush_all();
                return;
            }
            "glob" => {
                super::cmd_glob(&rest);
                core::stats::flush();
                return;
            }
            "find" => {
                super::cmd_find(&rest);
                core::tool_lifecycle::flush_all();
                return;
            }
            "ls" => {
                super::cmd_ls(&rest);
                core::tool_lifecycle::flush_all();
                return;
            }
            "deps" => {
                super::cmd_deps(&rest);
                core::tool_lifecycle::flush_all();
                return;
            }
            "discover" => {
                super::cmd_discover(&rest);
                return;
            }
            "ghost" => {
                super::cmd_ghost(&rest);
                return;
            }
            "filter" => {
                super::cmd_filter(&rest);
                return;
            }
            "heatmap" => {
                heatmap::cmd_heatmap(&rest);
                return;
            }
            "graph" => {
                cmd_graph(&rest);
                return;
            }
            "smells" => {
                cmd_smells(&rest);
                return;
            }
            "session" => {
                super::cmd_session_action(&rest);
                return;
            }
            "ledger" => {
                super::cmd_ledger(&rest);
                return;
            }
            "ocla" => {
                super::cmd_ocla(&rest);
                return;
            }
            "control" | "context-control" => {
                super::cmd_control(&rest);
                return;
            }
            "plan" | "context-plan" => {
                super::cmd_plan(&rest);
                return;
            }
            "compile" | "context-compile" => {
                super::cmd_compile(&rest);
                return;
            }
            "import" => {
                crate::cli::import_cmd::cmd_import(&rest);
            }
            "checkpoints" => {
                crate::cli::checkpoint_cmd::cmd_checkpoints(&rest);
            }
            "knowledge" => {
                super::cmd_knowledge(&rest);
                return;
            }
            "skillify" => {
                super::cmd_skillify(&rest);
                return;
            }
            "summary" => {
                super::cmd_summary(&rest);
                return;
            }
            "overview" => {
                super::cmd_overview(&rest);
                return;
            }
            "compress" => {
                super::cmd_compress(&rest);
                return;
            }
            "wrapped" => {
                eprintln!("'lean-ctx wrapped' has been removed. Use: lean-ctx gain --wrapped");
                std::process::exit(1);
            }
            "sessions" | "session-store" => {
                super::cmd_sessions(&rest);
                return;
            }
            "benchmark" => {
                if rest.is_empty()
                    || rest.first().is_some_and(|arg| {
                        matches!(
                            arg.as_str(),
                            "--real"
                                | "--format"
                                | "--json"
                                | "--output"
                                | "-o"
                                | "--share"
                                | "--help"
                                | "-h"
                        )
                    })
                {
                    super::cmd_benchmark_real(&rest);
                } else {
                    super::cmd_benchmark(&rest);
                }
                return;
            }
            "compact" => {
                cmd_compact(&rest);
                return;
            }
            "profile" => {
                super::cmd_profile(&rest);
                return;
            }
            "tools" => {
                // `tools health` is the token-budget / rot report (#848); it is
                // distinct from tool *profiles* and routed before the forward.
                if rest.first().map(String::as_str) == Some("health") {
                    super::cmd_tools_health(&rest[1..]);
                    return;
                }
                // Canonical, unambiguous entry point for MCP *tool* profiles
                // (how many tools the agent sees). Disambiguates from
                // `lean-ctx profile`, which manages *context* profiles.
                let mut forwarded = vec!["tools".to_string()];
                forwarded.extend(rest.iter().cloned());
                super::cmd_profile(&forwarded);
                return;
            }
            "config" => {
                super::cmd_config(&rest);
                return;
            }
            "allow" => {
                super::cmd_allow(&rest);
                return;
            }
            "security" => {
                super::cmd_security(&rest);
                return;
            }
            "yolo" => {
                super::cmd_yolo(&rest);
                return;
            }
            "secure" | "lockdown" => {
                super::cmd_secure(&rest);
                return;
            }
            "trust" => {
                super::cmd_trust(&rest);
                return;
            }
            "untrust" => {
                super::cmd_untrust(&rest);
                return;
            }
            "stats" => {
                super::cmd_stats(&rest);
                return;
            }
            "introspect" => {
                super::cmd_introspect(&rest);
                return;
            }
            "cache" => {
                super::cmd_cache(&rest);
                return;
            }
            "theme" => {
                super::cmd_theme(&rest);
                return;
            }
            "enterprise" => {
                super::cmd_enterprise(&rest);
                return;
            }
            "tee" => {
                super::cmd_tee(&rest);
                return;
            }
            "terse" | "compression" => {
                super::cmd_compression(&rest);
                return;
            }
            "slow-log" => {
                super::cmd_slow_log(&rest);
                return;
            }
            "debug-log" => {
                super::cmd_debug_log(&rest);
                return;
            }
            // Editor focus ingress (#500): called by the VS Code extension on
            // tab change; <10ms, no daemon required.
            "editor-signal" => {
                let file = rest
                    .iter()
                    .position(|a| a == "--file")
                    .and_then(|i| rest.get(i + 1));
                if let Some(path) = file {
                    if let Err(e) = core::editor_signal::record_focus(path) {
                        eprintln!("editor-signal: {e}");
                        std::process::exit(1);
                    }
                } else {
                    eprintln!("usage: lean-ctx editor-signal --file <path>");
                    std::process::exit(2);
                }
                return;
            }
            "editor-session" => {
                handle_editor_session(&rest);
                return;
            }
            "update" | "--self-update" => {
                core::updater::run(&rest);
                return;
            }
            "restart" => {
                cmd_restart();
                return;
            }
            "stop" => {
                cmd_stop();
                return;
            }
            "dev-install" => {
                cmd_dev_install();
                return;
            }
            "codesign-setup" => {
                cmd_codesign_setup();
                return;
            }
            "doctor" => {
                let code = doctor::run_cli(&rest);
                if code != 0 {
                    std::process::exit(code);
                }
                return;
            }
            "harden" => {
                super::harden::run(&rest);
                return;
            }
            "export-rules" => {
                super::export_rules::run(&rest);
                return;
            }
            "completions" => {
                super::completions::run_completions(&rest);
                return;
            }
            "__complete" => {
                #[allow(non_snake_case)]
                super::completions::run___complete(&rest);
                return;
            }
            "gotchas" | "bugs" => {
                super::cloud::cmd_gotchas(&rest);
                return;
            }
            "learn" => {
                super::cmd_learn(&rest);
                return;
            }
            "buddy" | "pet" => {
                super::cloud::cmd_buddy(&rest);
                return;
            }
            "hook" => {
                hook_handlers::mark_hook_environment();
                // Hooks run inside the agent shell environment, so they can see
                // runtime/session vars (e.g. CODEX_THREAD_ID) that the long-lived
                // MCP server process never receives. Bridge them for ctx_shell (#370).
                core::agent_runtime_env::capture();
                let action = rest.first().map_or("help", std::string::String::as_str);
                // Gating hooks (rewrite/redirect) self-bound their work and FAIL OPEN
                // inside the handler (#1035), so they must NOT also carry the
                // force-exit watchdog (which would `exit(1)` with no decision and
                // wedge the host). The remaining hooks keep the simple zombie-guard.
                if !matches!(action, "rewrite" | "redirect" | "deny" | "vibe-pre-tool") {
                    hook_handlers::arm_watchdog(std::time::Duration::from_secs(5));
                }
                match action {
                    "rewrite" => hook_handlers::handle_rewrite(),
                    "redirect" => hook_handlers::handle_redirect(),
                    "deny" => hook_handlers::handle_deny(),
                    "read-dedup" => hook_handlers::handle_read_dedup(),
                    "observe" => hook_handlers::handle_observe(),
                    "post-commit" => hook_handlers::handle_post_commit(),
                    "copilot" => hook_handlers::handle_copilot(),
                    "codex-pretooluse" => hook_handlers::handle_codex_pretooluse(),
                    "codex-session-start" => hook_handlers::handle_codex_session_start(),
                    "rewrite-inline" => hook_handlers::handle_rewrite_inline(),
                    "vibe-pre-tool" => hook_handlers::handle_vibe_pre_tool(),
                    _ => {
                        eprintln!(
                            "Usage: lean-ctx hook <rewrite|redirect|deny|read-dedup|observe|post-commit|copilot|codex-pretooluse|codex-session-start|rewrite-inline|vibe-pre-tool>"
                        );
                        eprintln!(
                            "  Internal commands used by agent hooks (Claude, Cursor, Copilot, etc.)"
                        );
                        std::process::exit(1);
                    }
                }
                return;
            }
            "report-issue" | "report" => {
                report::run(&rest);
                return;
            }
            "uninstall" => {
                // Safety: `--help`/`-h` must NEVER fall through to a real
                // uninstall (issue #476). Short-circuit before any removal.
                if rest.iter().any(|a| a == "--help" || a == "-h") {
                    uninstall::print_help();
                    return;
                }
                let dry_run = rest.iter().any(|a| a == "--dry-run");
                let keep_config = rest.iter().any(|a| a == "--keep-config");
                let keep_binary = rest.iter().any(|a| a == "--keep-binary");
                uninstall::run(dry_run, keep_config, keep_binary);
                return;
            }
            // `raw` is the primary name; `bypass` is kept as a back-compat alias.
            // The old "bypass" wording read to a model like a *security* bypass,
            // but this only skips compression — the shell allowlist and path jail
            // still apply (GH security audit, finding 5).
            "raw" | "bypass" => handle_raw(&args, &rest),
            "safety-levels" | "safety" => {
                println!("{}", core::compression_safety::format_safety_table());
                return;
            }
            "cheat" | "cheatsheet" | "cheat-sheet" => {
                super::cmd_cheatsheet();
                return;
            }
            "login" => {
                super::cloud::cmd_login(&rest);
                return;
            }
            "register" => {
                super::cloud::cmd_register(&rest);
                return;
            }
            "forgot-password" => {
                super::cloud::cmd_forgot_password(&rest);
                return;
            }
            "sync" => {
                super::cloud::cmd_sync(&rest);
                return;
            }
            "contribute" => {
                super::cloud::cmd_contribute();
                return;
            }
            "telemetry" => {
                super::telemetry_cmd::cmd_telemetry(&rest);
                return;
            }
            "cloud" => {
                super::cloud::cmd_cloud(&rest);
                return;
            }
            "upgrade" => {
                super::cloud::cmd_upgrade();
                return;
            }
            "--version" | "-V" => {
                println!("{}", core::integrity::origin_line());
                return;
            }
            "help" => {
                let want_all = rest
                    .iter()
                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"));
                if want_all {
                    print_help();
                } else {
                    print_help_concise();
                }
                return;
            }
            "--help" | "-h" => {
                if rest
                    .iter()
                    .any(|a| matches!(a.as_str(), "all" | "full" | "--all" | "-a"))
                {
                    print_help();
                } else {
                    print_help_concise();
                }
                return;
            }
            "mcp" => {}
            _ => {
                let unknown = &args[1];
                eprintln!("lean-ctx: unknown command '{unknown}'");
                if let Some(suggestion) = suggest::closest_command(unknown) {
                    eprintln!("       did you mean '{suggestion}'?");
                }
                eprintln!("       run 'lean-ctx help' for the full command list");
                std::process::exit(1);
            }
        }
    }

    // Bare `lean-ctx` in an interactive terminal: a human almost certainly did
    // not mean to start a silent stdio MCP server (which just hangs waiting for
    // JSON-RPC). Show a short quickstart instead. MCP clients pipe stdin (not a
    // TTY) so they still get the server, and explicit `lean-ctx mcp` always
    // serves regardless of TTY.
    if args.len() == 1 && std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        print_quickstart();
        return;
    }

    if let Err(e) = run_mcp_server() {
        tracing::error!("lean-ctx: {e}");
        std::process::exit(1);
    }
}

fn handle_editor_session(args: &[String]) {
    let value_for = |flag: &str| {
        args.iter()
            .position(|argument| argument == flag)
            .and_then(|index| args.get(index + 1))
    };
    let fields = (
        value_for("--event"),
        value_for("--source"),
        value_for("--workspace"),
        value_for("--session-id"),
    );
    let (Some(event), Some(source), Some(workspace), Some(session_id)) = fields else {
        eprintln!(
            "usage: lean-ctx editor-session --event <open|heartbeat|close> \
             --source <editor> --workspace <path> --session-id <id>"
        );
        std::process::exit(2);
    };

    if let Err(error) = crate::core::agents::AgentRegistry::record_logical_session_presence(
        event, source, workspace, session_id,
    ) {
        eprintln!("editor-session: {error}");
        std::process::exit(1);
    }
}

/// Long-lived server entry points keep Rust's default ignored SIGPIPE: they
/// must survive peers closing sockets/pipes early. Bare `lean-ctx` counts as
/// a server because MCP clients spawn the binary without a subcommand.
/// Help for `lean-ctx setup`. Printed for `--help`/`-h` and unknown flags so
/// asking about setup can never accidentally *run* setup (#476 class, #658).
fn print_setup_help() {
    println!("Usage: lean-ctx setup [options]");
    println!();
    println!("Guided setup: shell hook, agent hooks/rules, MCP registrations.");
    println!("Interactive by default; runs non-interactively without a TTY.");
    println!();
    println!("Options:");
    println!("  --non-interactive   No prompts; apply defaults");
    println!("  --yes, -y           Assume yes for all prompts");
    println!("  --fix               Repair an existing installation");
    println!("  --json              Machine-readable report (implies non-interactive)");
    println!("  --no-auto-approve   Skip auto-approve configuration");
    println!("  --skip-rules        Do not write agent rules files");
    println!("  --help, -h          Show this help (never runs setup)");
    println!();
    println!("See also: lean-ctx onboard (one-command setup), lean-ctx doctor");
}

fn is_server_mode(args: &[String]) -> bool {
    args.len() == 1
        || args.get(1).is_some_and(|a| {
            matches!(
                a.as_str(),
                "mcp" | "daemon" | "proxy" | "serve" | "watch" | "dashboard" | "gateway"
            )
        })
}

/// Extract `KEY=VALUE` prefixes from a command string and promote lean-ctx control variables
/// (`LEAN_CTX_*`) into the process environment.
/// Returns the remaining command string without the extracted prefixes.
///
/// Only `LEAN_CTX_*` variables are set in the process env — arbitrary user vars like `FOO=bar`
/// are left for the child shell to handle.
fn extract_and_apply_env_prefix(cmd: &str) -> String {
    let mut rest = cmd.trim_start();
    let mut last_rest = rest;

    loop {
        if let Some(eq_pos) = rest.find('=') {
            let key = &rest[..eq_pos];
            if !key.is_empty()
                && key
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
            {
                let after_eq = &rest[eq_pos + 1..];
                if let Some(space_pos) = after_eq.find(' ') {
                    let value = &after_eq[..space_pos];
                    if key.starts_with("LEAN_CTX_") {
                        // SAFETY: runs before tokio runtime spawns threads.
                        unsafe { std::env::set_var(key, value) };
                    }
                    rest = after_eq[space_pos..].trim_start();
                    last_rest = rest;
                    continue;
                }
            }
        }
        break;
    }

    last_rest.to_string()
}

fn handle_exec(args: &[String], rest: &[String]) -> ! {
    let raw = rest.first().is_some_and(|a| a == "--raw");
    let cmd_args = if raw { &args[3..] } else { &args[2..] };
    let command = if cmd_args.len() == 1 {
        cmd_args[0].clone()
    } else {
        shell::join_command(cmd_args)
    };
    // Extract LEAN_CTX_* env-var prefixes from the command string and set them in process env
    // so should_pass_through() / is_disabled() can see them. The child shell still gets the full
    // original command. (#1321)
    let _stripped_command = extract_and_apply_env_prefix(&command);
    // The `lean-ctx -c` wrapper runs inside the agent shell, which carries
    // runtime/session vars the MCP server never sees. Bridge them so ctx_shell
    // can forward them too (#370).
    core::agent_runtime_env::capture();
    if crate::shell::reentry::should_pass_through() {
        passthrough(&command);
    }
    if raw {
        core::runtime_flags::enable_raw();
    } else {
        core::runtime_flags::enable_compress();
    }
    let code = shell::exec(&command);
    core::tool_lifecycle::flush_all();
    std::process::exit(code);
}

fn handle_track(args: &[String]) -> ! {
    let cmd_args = &args[2..];
    let code = if cmd_args.len() > 1 {
        shell::exec_argv(cmd_args)
    } else {
        let command = cmd_args[0].clone();
        if crate::shell::reentry::should_pass_through() {
            passthrough(&command);
        }
        shell::exec(&command)
    };
    core::tool_lifecycle::flush_all();
    std::process::exit(code);
}

fn handle_setup(rest: &[String]) {
    // Safety (#476 class): `--help`/`-h` — or any unknown flag — must NEVER
    // fall through to a real setup run that mutates shell + agent configs.
    if rest.iter().any(|a| a == "--help" || a == "-h") {
        print_setup_help();
        return;
    }
    const KNOWN: &[&str] = &[
        "--non-interactive",
        "--yes",
        "-y",
        "--fix",
        "--json",
        "--no-auto-approve",
        "--skip-rules",
        "--no-agent-aliases",
    ];
    if let Some(unknown) = rest
        .iter()
        .find(|a| a.starts_with('-') && !KNOWN.contains(&a.as_str()))
    {
        eprintln!("setup: unknown flag '{unknown}'\n");
        print_setup_help();
        std::process::exit(2);
    }
    let non_interactive = rest.iter().any(|a| a == "--non-interactive");
    let yes = rest.iter().any(|a| a == "--yes" || a == "-y");
    let fix = rest.iter().any(|a| a == "--fix");
    let json = rest.iter().any(|a| a == "--json");
    let no_auto_approve = rest.iter().any(|a| a == "--no-auto-approve");
    let skip_rules = rest.iter().any(|a| a == "--skip-rules");
    let no_agent_aliases = rest.iter().any(|a| a == "--no-agent-aliases");

    if no_agent_aliases {
        let _ = crate::core::config::setter::set_by_key("skip_agent_aliases", "true");
    }

    if non_interactive || fix || json || yes {
        let opts = setup::SetupOptions {
            non_interactive,
            yes,
            fix,
            json,
            no_auto_approve,
            skip_rules,
            ..Default::default()
        };
        run_setup_options(opts, json);
    } else {
        setup::run_setup();
    }
}

fn handle_onboard(rest: &[String]) {
    if rest.iter().any(|a| a == "--help" || a == "-h") {
        println!("Usage: lean-ctx onboard [--no-agent-aliases]");
        println!("Connect your AI tools with one command: detects installed");
        println!("agents, installs hooks/rules/MCP registrations, verifies.");
        println!();
        println!("  --no-agent-aliases  Do not install claude/codex/gemini shell aliases");
        println!();
        println!("Fine-grained control: lean-ctx setup --help");
        return;
    }
    if rest.iter().any(|a| a == "--no-agent-aliases") {
        let _ = crate::core::config::setter::set_by_key("skip_agent_aliases", "true");
    }
    setup::run_onboard();
}

fn handle_install(rest: &[String]) {
    // Plain `lean-ctx install` is a natural thing to type after installing the
    // binary; keep it as guided setup unless repair mode was explicitly asked.
    let repair = rest.iter().any(|a| a == "--repair" || a == "--fix");
    let json = rest.iter().any(|a| a == "--json");
    if !repair {
        setup::run_setup();
        return;
    }
    run_repair_setup(json);
}

fn handle_bootstrap(rest: &[String]) {
    let json = rest.iter().any(|a| a == "--json");
    run_repair_setup(json);
}

fn run_repair_setup(json: bool) {
    let opts = setup::SetupOptions {
        non_interactive: true,
        yes: true,
        fix: true,
        json,
        ..Default::default()
    };
    run_setup_options(opts, json);
}

fn handle_raw(args: &[String], rest: &[String]) -> ! {
    if rest.is_empty() {
        eprintln!("Usage: lean-ctx raw \"command\"");
        eprintln!(
            "Runs the command with output passed through unchanged (no compression). \
             The shell allowlist still applies."
        );
        std::process::exit(1);
    }
    let command = if rest.len() == 1 {
        rest[0].clone()
    } else {
        shell::join_command(&args[2..])
    };
    core::runtime_flags::enable_raw();
    let code = shell::exec(&command);
    std::process::exit(code);
}

fn run_setup_options(opts: setup::SetupOptions, json: bool) {
    match setup::run_setup_with_options(opts) {
        Ok(report) => {
            if json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&report).unwrap_or_else(|_| "{}".to_string())
                );
            }
            if !report.success {
                std::process::exit(1);
            }
        }
        Err(e) => {
            eprintln!("{e}");
            std::process::exit(1);
        }
    }
}

/// Restore the default SIGPIPE disposition for short-lived CLI invocations.
///
/// Rust's runtime ignores SIGPIPE process-wide, so `lean-ctx doctor | head`
/// made `println!` panic with BrokenPipe; the LineWriter flush in stdout's
/// Drop then panicked again *during unwinding*, which aborts — the SIGABRT
/// (exit 134) of upstream #378 / GL#436. Real CLIs (cat, grep, rg) terminate
/// silently with exit 141 instead; SIG_DFL gives us exactly that. Children
/// spawned via std::process::Command are unaffected either way (std resets
/// their SIGPIPE disposition since Rust 1.65).
#[cfg(unix)]
fn restore_sigpipe_default() {
    // SAFETY: signal(2) with SIG_DFL has no preconditions and is called once
    // during single-threaded startup, before any I/O.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}

#[cfg(not(unix))]
fn restore_sigpipe_default() {}

fn passthrough(command: &str) -> ! {
    let (shell, flag) = shell::shell_and_flag();
    let mut cmd = std::process::Command::new(&shell);
    cmd.arg(&flag).arg(command);
    shell::reentry::mark_child(&mut cmd);
    shell::platform::apply_utf8_locale(&mut cmd);
    let status = cmd.status().map_or(127, |s| s.code().unwrap_or(1));
    std::process::exit(status);
}

pub(super) fn run_async<F: std::future::Future>(future: F) -> F::Output {
    // A failed runtime build (e.g. exhausted FDs) must not abort with a panic
    // backtrace the user can't act on — report it plainly and exit.
    match tokio::runtime::Runtime::new() {
        Ok(rt) => rt.block_on(future),
        Err(e) => {
            eprintln!("lean-ctx: failed to create async runtime: {e}");
            std::process::exit(1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        capability_banner, concise_help_text, is_server_mode, quickstart_text,
        resolve_worker_threads,
    };
    use serial_test::serial;

    fn args_of(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| (*s).to_string()).collect()
    }

    #[test]
    fn server_modes_keep_ignored_sigpipe() {
        for mode in ["mcp", "daemon", "proxy", "serve", "watch", "dashboard"] {
            assert!(
                is_server_mode(&args_of(&["lean-ctx", mode])),
                "{mode} must count as server mode"
            );
        }
        // Bare invocation = MCP server spawned by a client.
        assert!(is_server_mode(&args_of(&["lean-ctx"])));
    }

    #[test]
    fn cli_modes_restore_default_sigpipe() {
        for mode in ["doctor", "-c", "status", "ls", "grep", "gain", "help"] {
            assert!(
                !is_server_mode(&args_of(&["lean-ctx", mode])),
                "{mode} must count as CLI mode (SIGPIPE default)"
            );
        }
    }

    #[test]
    fn quickstart_is_short_and_points_to_setup() {
        let q = quickstart_text();
        assert!(q.contains("lean-ctx wrap"), "quickstart must point to wrap");
        assert!(q.contains("lean-ctx help"), "quickstart must point to help");
        // Must stay a *quickstart*, not the full reference — keep it tight.
        assert!(
            q.lines().count() <= 16,
            "quickstart should be short; got {} lines",
            q.lines().count()
        );
        assert!(
            !q.contains("COMMANDS:"),
            "quickstart must not inline the full command reference"
        );
    }

    #[test]
    fn concise_help_is_short_and_points_to_full() {
        let h = concise_help_text();
        assert!(h.contains("lean-ctx wrap"), "must lead with wrap");
        assert!(
            h.contains("lean-ctx help all"),
            "must point to full reference"
        );
        assert!(
            h.contains("lean-ctx tools"),
            "must surface the tools profile command"
        );
        // Concise means concise — keep it well under the full reference.
        assert!(
            h.lines().count() <= 40,
            "concise help should stay short; got {} lines",
            h.lines().count()
        );
        assert!(
            !h.contains("SHELL HOOK PATTERNS"),
            "concise help must not inline the full pattern catalog"
        );
    }

    #[test]
    fn capability_banner_tool_count_matches_registry() {
        let n = crate::server::registry::tool_count();
        let banner = capability_banner();
        assert!(
            banner.contains(&format!("{n} MCP tools")),
            "banner must show the live registry count ({n}); got: {banner}"
        );
    }

    #[test]
    #[serial]
    fn worker_threads_default_clamps_low() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
        assert_eq!(resolve_worker_threads(1), 1);
    }

    #[test]
    #[serial]
    fn worker_threads_default_clamps_high() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
        assert_eq!(resolve_worker_threads(32), 4);
    }

    #[test]
    #[serial]
    fn worker_threads_default_passthrough() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
        assert_eq!(resolve_worker_threads(3), 3);
    }

    #[test]
    #[serial]
    fn worker_threads_env_override() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_WORKER_THREADS", "12");
        assert_eq!(resolve_worker_threads(2), 12);
        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
    }

    #[test]
    #[serial]
    fn worker_threads_env_invalid_falls_back() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::set_var("LEAN_CTX_WORKER_THREADS", "not_a_number");
        assert_eq!(resolve_worker_threads(3), 3);
        crate::test_env::remove_var("LEAN_CTX_WORKER_THREADS");
    }
}

#[cfg(test)]
mod env_prefix_tests {
    use super::extract_and_apply_env_prefix;
    use serial_test::serial;

    #[test]
    #[serial]
    fn extracts_lean_ctx_disabled() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("LEAN_CTX_DISABLED");
        let result = extract_and_apply_env_prefix("LEAN_CTX_DISABLED=1 cargo test --lib");
        assert_eq!(result, "cargo test --lib");
        assert_eq!(std::env::var("LEAN_CTX_DISABLED").unwrap(), "1");
        crate::test_env::remove_var("LEAN_CTX_DISABLED");
    }

    #[test]
    #[serial]
    fn ignores_non_lean_ctx_vars() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("FOO");
        let result = extract_and_apply_env_prefix("FOO=bar cargo test --lib");
        assert_eq!(result, "cargo test --lib");
        assert!(
            std::env::var("FOO").is_err(),
            "FOO must not be set in process env"
        );
    }

    #[test]
    #[serial]
    fn extracts_multiple_lean_ctx_vars() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("LEAN_CTX_DISABLED");
        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
        let result =
            extract_and_apply_env_prefix("LEAN_CTX_DISABLED=1 LEAN_CTX_ACTIVE=1 cargo test --lib");
        assert_eq!(result, "cargo test --lib");
        assert_eq!(std::env::var("LEAN_CTX_DISABLED").unwrap(), "1");
        assert_eq!(std::env::var("LEAN_CTX_ACTIVE").unwrap(), "1");
        crate::test_env::remove_var("LEAN_CTX_DISABLED");
        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
    }

    #[test]
    #[serial]
    fn no_prefix_returns_unchanged() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        let result = extract_and_apply_env_prefix("cargo test --lib");
        assert_eq!(result, "cargo test --lib");
    }

    #[test]
    #[serial]
    fn mixed_vars_extracts_only_lean_ctx() {
        let _env_lock = crate::core::data_dir::test_env_lock();
        crate::test_env::remove_var("FOO");
        crate::test_env::remove_var("LEAN_CTX_DISABLED");
        let result = extract_and_apply_env_prefix("FOO=bar LEAN_CTX_DISABLED=1 cargo test --lib");
        assert_eq!(result, "cargo test --lib");
        assert_eq!(std::env::var("LEAN_CTX_DISABLED").unwrap(), "1");
        assert!(std::env::var("FOO").is_err());
        crate::test_env::remove_var("LEAN_CTX_DISABLED");
    }
}