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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::SystemTime;
use super::memory_policy::MemoryPolicy;
mod defaults_allowlist;
mod enums;
mod memory;
mod proxy;
pub mod schema;
mod sections;
mod serde_defaults;
pub mod setter;
mod shell_activation;
pub use sections::*;
#[cfg(test)]
mod tests;
pub(crate) use defaults_allowlist::default_shell_allowlist;
pub use enums::{
CompressionLevel, OutputDensity, ResponseVerbosity, RulesScope, TeeMode, TerseAgent,
};
pub use memory::{MemoryCleanup, MemoryGuardConfig, MemoryProfile, SavingsFooter};
pub use proxy::{is_local_proxy_url, normalize_url, normalize_url_opt, ProxyConfig, ProxyProvider};
pub use shell_activation::ShellActivation;
/// Default BM25 cache cap from config (also used by `bm25_index` heuristics).
pub fn default_bm25_max_cache_mb() -> u64 {
serde_defaults::default_bm25_max_cache_mb()
}
/// Effective on-disk ceiling (MB) for the persisted BM25 index when nothing is
/// explicitly configured (no `bm25_max_cache_mb`, no `max_disk_mb` budget).
///
/// Deliberately decoupled from the RAM `MemoryProfile` (64/128/512 MB): this is
/// a *disk* file, and tying it to the profile silently refused persistence on
/// large repos under Low/Balanced, forcing a cold rebuild on every call (the
/// perpetual "index warming" of issue #249). 512 MB compressed covers
/// essentially every real repo; RAM pressure is governed separately by the
/// eviction orchestrator (which measures real heap).
pub const DEFAULT_BM25_PERSIST_MB: u64 = 512;
// Compile-time regression guard (#249): the default disk ceiling must stay well
// above the old RAM-profile caps (64/128 MB) that starved large repos.
const _: () = assert!(DEFAULT_BM25_PERSIST_MB >= 512);
/// Global lean-ctx configuration loaded from `config.toml`, merged with project-local overrides.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub ultra_compact: bool,
#[serde(default, deserialize_with = "serde_defaults::deserialize_tee_mode")]
pub tee_mode: TeeMode,
#[serde(default)]
pub output_density: OutputDensity,
pub checkpoint_interval: u32,
pub excluded_commands: Vec<String>,
pub passthrough_urls: Vec<String>,
pub custom_aliases: Vec<AliasEntry>,
/// Output formats that are already compact/token-oriented and must be
/// preserved verbatim instead of being recompressed (#342). Matched against
/// the *output shape* (not the command name), so any tool emitting the
/// format is covered without enumerating commands in `excluded_commands`.
/// Default: `["toon"]`. Set to `[]` to disable and always recompress.
#[serde(default = "serde_defaults::default_preserve_compact_formats")]
pub preserve_compact_formats: Vec<String>,
/// Commands taking longer than this threshold (ms) are recorded in the slow log.
/// Set to 0 to disable slow logging.
pub slow_command_threshold_ms: u64,
#[serde(default = "serde_defaults::default_theme")]
pub theme: String,
#[serde(default)]
pub cloud: CloudConfig,
#[serde(default)]
pub gain: GainConfig,
#[serde(default)]
pub autonomy: AutonomyConfig,
#[serde(default)]
pub providers: ProvidersConfig,
#[serde(default)]
pub proxy: ProxyConfig,
/// Whether the API proxy is enabled. Tri-state:
/// - None: undecided (fresh install, will prompt on interactive setup)
/// - Some(true): user opted in, proxy managed by lean-ctx
/// - Some(false): user opted out, never touch proxy or endpoints
#[serde(default)]
pub proxy_enabled: Option<bool>,
#[serde(default)]
pub proxy_port: Option<u16>,
/// Proxy reachability timeout in milliseconds. Default: 200.
/// Override via LEAN_CTX_PROXY_TIMEOUT_MS env var.
#[serde(default)]
pub proxy_timeout_ms: Option<u64>,
#[serde(default = "serde_defaults::default_buddy_enabled")]
pub buddy_enabled: bool,
#[serde(default = "serde_defaults::default_true")]
pub enable_wakeup_ctx: bool,
#[serde(default)]
pub redirect_exclude: Vec<String>,
/// Tools to exclude from the MCP tool list returned by list_tools.
/// Accepts exact tool names (e.g. `["ctx_graph", "ctx_agent"]`).
/// Empty by default — all tools listed, no behaviour change.
#[serde(default)]
pub disabled_tools: Vec<String>,
/// Tool categories to activate by default for dynamic-tool-capable clients.
/// Values: "core" (always on), "arch", "debug", "memory", "metrics", "session".
/// Example: `default_tool_categories = ["core", "arch", "memory"]`
/// Override via LCTX_DEFAULT_CATEGORIES env var (comma-separated).
/// Empty = lean-ctx default (core + session).
#[serde(default)]
pub default_tool_categories: Vec<String>,
/// Disable all automatic read-mode degradation (auto_degrade + context_gate pressure).
/// When true, lean-ctx never downgrades requested read modes regardless of pressure.
/// Override via LCTX_NO_DEGRADE=1 env var.
#[serde(default)]
pub no_degrade: bool,
/// Persistent profile name. Checked after LEAN_CTX_PROFILE env var.
/// Set via `lean-ctx config set profile passthrough` or editing config.toml.
#[serde(default)]
pub profile: Option<String>,
/// Tool visibility profile: "minimal" (6), "standard" (21), or "power" (all).
/// Override via LEAN_CTX_TOOL_PROFILE env var.
/// Existing installs default to "power" (backward compat).
#[serde(default)]
pub tool_profile: Option<String>,
/// Explicit list of enabled tool names (overrides tool_profile when non-empty).
/// Example: `tools_enabled = ["ctx_read", "ctx_shell", "ctx_search"]`
#[serde(default)]
pub tools_enabled: Vec<String>,
#[serde(default)]
pub loop_detection: LoopDetectionConfig,
/// Controls where lean-ctx installs agent rule files.
/// Values: "both" (default), "global" (home-dir only), "project" (repo-local only).
/// Override via LEAN_CTX_RULES_SCOPE env var.
#[serde(default)]
pub rules_scope: Option<String>,
/// Extra glob patterns to ignore in graph/overview/preload (repo-local).
/// Example: `["externals/**", "target/**", "temp/**"]`
#[serde(default)]
pub extra_ignore_patterns: Vec<String>,
/// Controls agent output verbosity via instructions injection.
/// Values: "off" (default), "lite", "full", "ultra".
/// Override via LEAN_CTX_TERSE_AGENT env var.
#[serde(default)]
pub terse_agent: TerseAgent,
/// Unified compression level (replaces separate terse_agent + output_density).
/// Values: "off" (default), "lite", "standard", "max".
/// Override via LEAN_CTX_COMPRESSION env var.
#[serde(default)]
pub compression_level: CompressionLevel,
/// Archive configuration for zero-loss compression.
#[serde(default)]
pub archive: ArchiveConfig,
/// Memory policy (knowledge/episodic/procedural/lifecycle budgets & thresholds).
#[serde(default)]
pub memory: MemoryPolicy,
/// Additional paths allowed by PathJail (absolute).
/// Useful for multi-project workspaces where the jail root is a parent directory.
/// Override via LEAN_CTX_ALLOW_PATH env var (path-list separator).
#[serde(default)]
pub allow_paths: Vec<String>,
/// Extra project roots for multi-root workspaces.
/// Tools like ctx_tree and ctx_search can scan across all roots in a single call.
/// These paths are automatically added to PathJail's allow-list.
/// Override via LEAN_CTX_EXTRA_ROOTS env var (path-list separator).
#[serde(default)]
pub extra_roots: Vec<String>,
/// Enable content-defined chunking (Rabin-Karp) for cache-optimal output ordering.
/// Stable chunks are emitted first to maximize prompt cache hits.
#[serde(default)]
pub content_defined_chunking: bool,
/// Skip session/knowledge/gotcha blocks in MCP instructions to minimize token overhead.
/// Override via LEAN_CTX_MINIMAL env var.
#[serde(default)]
pub minimal_overhead: bool,
/// Opt-in: substitute long identifiers with short α-codes (+ a `§MAP` table)
/// in `aggressive` reads for projects with >50 source files. Off by default —
/// the abbreviated form is confusing for editing/refactoring, where the agent
/// needs the real package and symbol names. Enable for max exploration savings.
#[serde(default)]
pub symbol_map_auto: bool,
/// Team server URL for opt-in savings roll-up.
/// Set via `lean-ctx config set team_url https://...` or `[team] url` in config.toml.
/// Override via LEAN_CTX_TEAM_URL env var.
#[serde(default)]
pub team_url: Option<String>,
/// Enable human-readable activity journal (~/.lean-ctx/journal.md).
#[serde(default)]
pub journal_enabled: bool,
/// Opt-in: auto-persist interesting findings as knowledge facts.
#[serde(default)]
pub auto_capture: bool,
/// Hybrid search weights (BM25/dense/candidates).
#[serde(default)]
pub search: crate::core::hybrid_search::HybridConfig,
/// Optional LLM enhancement (query expansion, contradiction explanation).
#[serde(default)]
pub llm: crate::core::llm_enhance::LlmConfig,
/// Semantic-embedding engine settings (which local ONNX model to use).
#[serde(default)]
pub embedding: EmbeddingConfig,
/// Disable shell hook injection (the _lc() function that wraps CLI commands).
/// Override via LEAN_CTX_NO_HOOK env var.
#[serde(default)]
pub shell_hook_disabled: bool,
/// Shadow mode: transparently intercepts native tool calls (Read/Grep/Shell)
/// via hooks, strengthens MCP instructions to MUST-level, and activates
/// immediate bypass hints on first native tool use. Enables "transparent
/// replacement" so agents use ctx_* without explicit opt-in.
#[serde(default)]
pub shadow_mode: bool,
/// Controls when the shell hook auto-activates aliases.
/// - `always`: (Default) Aliases active in every interactive shell.
/// - `agents-only`: Aliases only active when an AI agent env var is detected.
/// - `off`: Aliases never auto-activate (user must call `lean-ctx-on` manually).
///
/// Override via `LEAN_CTX_SHELL_ACTIVATION` env var.
#[serde(default)]
pub shell_activation: ShellActivation,
/// Disable the daily version check against leanctx.com/version.txt.
/// Override via LEAN_CTX_NO_UPDATE_CHECK env var.
#[serde(default)]
pub update_check_disabled: bool,
#[serde(default)]
pub updates: UpdatesConfig,
/// Maximum BM25 cache file size in MB. Indexes exceeding this are quarantined on load
/// and refused on save. Override via LEAN_CTX_BM25_MAX_CACHE_MB env var.
#[serde(default = "serde_defaults::default_bm25_max_cache_mb")]
pub bm25_max_cache_mb: u64,
/// Maximum number of files scanned by the lightweight JSON graph index.
/// 0 = unlimited (default). Set >0 to cap for constrained systems.
#[serde(default = "serde_defaults::default_graph_index_max_files")]
pub graph_index_max_files: u64,
/// Controls RAM vs feature trade-off. Values: "low", "balanced" (default), "performance".
/// Override via LEAN_CTX_MEMORY_PROFILE env var.
#[serde(default)]
pub memory_profile: MemoryProfile,
/// Controls how aggressively memory is freed when idle.
/// Values: "aggressive" (default, 5 min TTL), "shared" (30 min TTL for multi-IDE use).
/// Override via LEAN_CTX_MEMORY_CLEANUP env var.
#[serde(default)]
pub memory_cleanup: MemoryCleanup,
/// Maximum percentage of system RAM that lean-ctx may use (default: 5).
/// Override via LEAN_CTX_MAX_RAM_PERCENT env var.
#[serde(default = "serde_defaults::default_max_ram_percent")]
pub max_ram_percent: u8,
/// Simplified disk budget (MB). When set and detail values are at defaults,
/// distributes proportionally: archive=25%, bm25=10%, remainder for stores.
/// 0 = disabled (use individual settings). Override via LEAN_CTX_MAX_DISK_MB.
#[serde(default)]
pub max_disk_mb: u64,
/// Auto-purge data older than this many days. 0 = disabled.
/// Flows into archive.max_age_hours and lifecycle idle TTL.
#[serde(default)]
pub max_staleness_days: u32,
/// Controls visibility of token savings footers in tool output.
/// Values: "always" (default, show on every response), "never", "auto" (legacy compatibility).
/// Override via LEAN_CTX_SAVINGS_FOOTER or LEAN_CTX_SHOW_SAVINGS=1|0 env var.
#[serde(default)]
pub savings_footer: SavingsFooter,
/// Explicit project root override. When set, lean-ctx uses this instead of auto-detection.
/// This prevents accidental home-directory scans when running from $HOME.
/// Override via LEAN_CTX_PROJECT_ROOT env var.
#[serde(default)]
pub project_root: Option<String>,
/// LSP server overrides. Map language name to custom binary path.
/// Example: `[lsp]\nrust = "/opt/rust-analyzer"\npython = "~/.venvs/main/bin/pylsp"`
#[serde(default)]
pub lsp: std::collections::HashMap<String, String>,
/// Per-IDE allowed paths. Restricts which directories lean-ctx will scan/index for each IDE.
/// Example: `[ide_paths]\ncursor = ["/home/user/projects/app1"]\ncodex = ["/home/user/codex"]`
/// When set, only these paths are indexed for the matching agent. Global `allow_paths` still applies.
#[serde(default)]
pub ide_paths: HashMap<String, Vec<String>>,
/// Custom model context window overrides.
/// Example: `[model_context_windows]\n"my-custom-model" = 500000`
#[serde(default)]
pub model_context_windows: HashMap<String, usize>,
/// Controls how much detail tool responses include.
///
/// - `full` (default): complete compressed output
/// - `headers_only`: metadata line only (path, mode, token count)
///
/// Override via `LEAN_CTX_RESPONSE_VERBOSITY` env var.
#[serde(default)]
pub response_verbosity: ResponseVerbosity,
/// Bypass hint mode. When agents use native Read/Grep instead of lean-ctx tools,
/// a hint is appended to the next tool response.
/// Values: "on" (default), "off", "aggressive" (hint on every call, no cooldown).
/// Override via LEAN_CTX_BYPASS_HINTS env var.
#[serde(default)]
pub bypass_hints: Option<String>,
/// Cache policy for ctx_read. Controls behavior on cache hits.
/// Values: "aggressive" (default, 13-tok stubs + compaction-aware reset),
/// "safe" (delivers map instead of stub), "off" (no caching, always disk read).
/// Override via LEAN_CTX_CACHE_POLICY env var.
#[serde(default)]
pub cache_policy: Option<String>,
/// Cross-project boundary policy.
/// Controls whether cross-project search/import is allowed and whether access is audited.
#[serde(default)]
pub boundary_policy: crate::core::memory_boundary::BoundaryPolicy,
#[serde(default)]
pub secret_detection: SecretDetectionConfig,
/// Allow automatic project-root re-rooting when absolute paths outside the jail are seen.
/// When false (default), absolute paths outside the jail are rejected without re-rooting.
/// Override via LEAN_CTX_ALLOW_REROOT env var.
#[serde(default)]
pub allow_auto_reroot: bool,
/// Disable PathJail entirely. Set to false to allow all paths.
/// Useful in container/Docker environments. Override via LEAN_CTX_NO_JAIL=1.
#[serde(default)]
pub path_jail: Option<bool>,
/// Sandbox level for code execution (ctx_exec).
/// 0 = subprocess only (current), 1 = OS-level restriction (Seatbelt/Landlock).
/// Override via LEAN_CTX_SANDBOX_LEVEL env var.
#[serde(default)]
pub sandbox_level: u8,
/// When true, large tool outputs (>4000 chars) are stored as references
/// and a short URI is returned instead of the full content.
/// Override via LEAN_CTX_REFERENCE_RESULTS env var.
#[serde(default)]
pub reference_results: bool,
/// Default per-agent token budget. 0 means unlimited.
/// Override per-agent via ctx_session or programmatically.
#[serde(default)]
pub agent_token_budget: usize,
/// Optional shell command allowlist. When non-empty, only commands whose base binary
/// is in this list are permitted by ctx_shell. Empty = disable allowlist (allow all).
/// Default includes common dev tools. Set to `[]` to disable.
/// Override via LEAN_CTX_SHELL_ALLOWLIST env var (comma-separated).
#[serde(default = "default_shell_allowlist")]
pub shell_allowlist: Vec<String>,
/// Extra commands MERGED on top of the effective `shell_allowlist` without replacing
/// the defaults. Setting `shell_allowlist` replaces the whole built-in list (a common
/// footgun); entries here are purely additive, which is what `lean-ctx allow <cmd>`
/// writes. Only applied in restricted mode (when the base allowlist is non-empty).
#[serde(default)]
pub shell_allowlist_extra: Vec<String>,
/// When true, block command substitution ($(), backticks) and process substitution
/// (<(), >()) in shell arguments. When false (default), only warn via tracing.
/// Default false preserves backward compatibility — set true for maximum security.
#[serde(default)]
pub shell_strict_mode: bool,
/// Setup behavior: controls what gets injected during setup and updates.
#[serde(default)]
pub setup: SetupConfig,
}
impl Default for Config {
fn default() -> Self {
Self {
ultra_compact: false,
tee_mode: TeeMode::default(),
output_density: OutputDensity::default(),
checkpoint_interval: 15,
excluded_commands: Vec::new(),
passthrough_urls: Vec::new(),
custom_aliases: Vec::new(),
preserve_compact_formats: serde_defaults::default_preserve_compact_formats(),
slow_command_threshold_ms: 5000,
theme: serde_defaults::default_theme(),
cloud: CloudConfig::default(),
gain: GainConfig::default(),
autonomy: AutonomyConfig::default(),
providers: ProvidersConfig::default(),
proxy: ProxyConfig::default(),
proxy_enabled: None,
proxy_port: None,
proxy_timeout_ms: None,
buddy_enabled: serde_defaults::default_buddy_enabled(),
enable_wakeup_ctx: true,
redirect_exclude: Vec::new(),
disabled_tools: Vec::new(),
default_tool_categories: Vec::new(),
no_degrade: false,
profile: None,
tool_profile: None,
tools_enabled: Vec::new(),
loop_detection: LoopDetectionConfig::default(),
rules_scope: None,
extra_ignore_patterns: Vec::new(),
terse_agent: TerseAgent::default(),
compression_level: CompressionLevel::default(),
archive: ArchiveConfig::default(),
memory: MemoryPolicy::default(),
allow_paths: Vec::new(),
extra_roots: Vec::new(),
content_defined_chunking: false,
minimal_overhead: true,
symbol_map_auto: false,
team_url: None,
journal_enabled: true,
auto_capture: true,
search: crate::core::hybrid_search::HybridConfig::default(),
llm: crate::core::llm_enhance::LlmConfig::default(),
embedding: EmbeddingConfig::default(),
shell_hook_disabled: false,
shadow_mode: false,
shell_activation: ShellActivation::default(),
update_check_disabled: false,
updates: UpdatesConfig::default(),
graph_index_max_files: serde_defaults::default_graph_index_max_files(),
bm25_max_cache_mb: serde_defaults::default_bm25_max_cache_mb(),
memory_profile: MemoryProfile::default(),
memory_cleanup: MemoryCleanup::default(),
max_ram_percent: serde_defaults::default_max_ram_percent(),
max_disk_mb: 0,
max_staleness_days: 0,
savings_footer: SavingsFooter::default(),
project_root: None,
lsp: std::collections::HashMap::new(),
ide_paths: HashMap::new(),
model_context_windows: HashMap::new(),
response_verbosity: ResponseVerbosity::default(),
bypass_hints: None,
cache_policy: None,
boundary_policy: crate::core::memory_boundary::BoundaryPolicy::default(),
secret_detection: SecretDetectionConfig::default(),
allow_auto_reroot: false,
path_jail: None,
sandbox_level: 0,
reference_results: false,
agent_token_budget: 0,
shell_allowlist: default_shell_allowlist(),
shell_allowlist_extra: Vec::new(),
shell_strict_mode: false,
setup: SetupConfig::default(),
}
}
}
/// Holds the most recent global `config.toml` parse error, if the file currently
/// fails to parse. When that happens `Config::load()` silently falls back to the
/// built-in defaults and only logs to stderr — which is invisible over an MCP/stdio
/// transport. Recording it here lets callers (e.g. the shell-allowlist diagnostic
/// and `lean-ctx doctor`) surface "you're on defaults because your config is broken".
static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
/// Returns the most recent global config parse error, or `None` if the current
/// `config.toml` parsed successfully (or no config file exists).
#[must_use]
pub fn last_config_parse_error() -> Option<String> {
LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
}
fn record_parse_error(err: Option<String>) {
if let Ok(mut guard) = LAST_PARSE_ERROR.lock() {
*guard = err;
}
}
impl Config {
/// Returns the effective rules scope, preferring env var over config file.
pub fn rules_scope_effective(&self) -> RulesScope {
let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
.ok()
.or_else(|| self.rules_scope.clone())
.unwrap_or_default();
match raw.trim().to_lowercase().as_str() {
"global" => RulesScope::Global,
"project" => RulesScope::Project,
_ => RulesScope::Both,
}
}
fn parse_disabled_tools_env(val: &str) -> Vec<String> {
val.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
/// Returns the effective disabled tools list, preferring env var over config file.
pub fn disabled_tools_effective(&self) -> Vec<String> {
if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
Self::parse_disabled_tools_env(&val)
} else {
self.disabled_tools.clone()
}
}
/// Returns `true` if minimal overhead is enabled via env var or config.
pub fn minimal_overhead_effective(&self) -> bool {
std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
}
/// Returns `true` if minimal overhead should be enabled for this MCP client.
///
/// This is a superset of `minimal_overhead_effective()`:
/// - `LEAN_CTX_OVERHEAD_MODE=minimal` forces minimal overhead
/// - `LEAN_CTX_OVERHEAD_MODE=full` disables client/model heuristics (still honors LEAN_CTX_MINIMAL / config)
/// - In auto mode (default), certain low-context clients/models are treated as minimal to prevent
/// large metadata blocks from destabilizing smaller context windows (e.g. Hermes + MiniMax).
pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool {
if let Ok(raw) = std::env::var("LEAN_CTX_OVERHEAD_MODE") {
match raw.trim().to_lowercase().as_str() {
"minimal" => return true,
"full" => return self.minimal_overhead_effective(),
_ => {}
}
}
if self.minimal_overhead_effective() {
return true;
}
let client_lower = client_name.trim().to_lowercase();
if !client_lower.is_empty() {
if let Ok(list) = std::env::var("LEAN_CTX_MINIMAL_CLIENTS") {
for needle in list.split(',').map(|s| s.trim().to_lowercase()) {
if !needle.is_empty() && client_lower.contains(&needle) {
return true;
}
}
} else if client_lower.contains("hermes") || client_lower.contains("minimax") {
return true;
}
}
let model = std::env::var("LEAN_CTX_MODEL")
.or_else(|_| std::env::var("LCTX_MODEL"))
.unwrap_or_default();
let model = model.trim().to_lowercase();
if !model.is_empty() {
let m = model.replace(['_', ' '], "-");
if m.contains("minimax")
|| m.contains("mini-max")
|| m.contains("m2.7")
|| m.contains("m2-7")
{
return true;
}
}
false
}
/// Returns `true` if shell hook injection is disabled via env var or config.
pub fn shell_hook_disabled_effective(&self) -> bool {
std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
}
/// Returns the effective shell activation mode (env var > config > default).
pub fn shell_activation_effective(&self) -> ShellActivation {
ShellActivation::effective(self)
}
/// Returns `true` if the daily update check is disabled via env var or config.
pub fn update_check_disabled_effective(&self) -> bool {
std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
}
pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
let mut policy = self.memory.clone();
policy.apply_env_overrides();
// Scale memory limits proportionally when max_disk_mb is set
// and individual limits are still at their defaults.
let budget = self.max_disk_mb_effective();
if budget > 0 {
let scale_factor = (budget as f64 / 500.0).clamp(0.5, 10.0);
let default_policy = MemoryPolicy::default();
if policy.knowledge.max_facts == default_policy.knowledge.max_facts {
policy.knowledge.max_facts = (200.0 * scale_factor) as usize;
}
if policy.knowledge.max_patterns == default_policy.knowledge.max_patterns {
policy.knowledge.max_patterns = (50.0 * scale_factor) as usize;
}
if policy.episodic.max_episodes == default_policy.episodic.max_episodes {
policy.episodic.max_episodes = (500.0 * scale_factor) as usize;
}
if policy.procedural.max_procedures == default_policy.procedural.max_procedures {
policy.procedural.max_procedures = (100.0 * scale_factor) as usize;
}
}
policy.validate()?;
Ok(policy)
}
/// Returns the effective set of default tool categories.
/// Priority: LCTX_DEFAULT_CATEGORIES env var > config.toml > hardcoded default.
pub fn default_tool_categories_effective(&self) -> Vec<String> {
if let Ok(val) = std::env::var("LCTX_DEFAULT_CATEGORIES") {
return val
.split(',')
.map(|s| s.trim().to_lowercase())
.filter(|s| !s.is_empty())
.collect();
}
if !self.default_tool_categories.is_empty() {
return self
.default_tool_categories
.iter()
.map(|s| s.to_lowercase())
.collect();
}
vec!["core".to_string(), "session".to_string()]
}
/// Returns the effective tool profile.
/// Priority: LEAN_CTX_TOOL_PROFILE env > config tool_profile > config tools_enabled > power.
pub fn tool_profile_effective(&self) -> super::tool_profiles::ToolProfile {
super::tool_profiles::ToolProfile::from_config(self)
}
/// Returns `true` if all automatic read-mode degradation is disabled.
/// Checks LCTX_NO_DEGRADE env var first, then config.toml field.
pub fn no_degrade_effective(&self) -> bool {
if let Ok(val) = std::env::var("LCTX_NO_DEGRADE") {
return val == "1" || val.eq_ignore_ascii_case("true");
}
self.no_degrade
}
/// Effective max_disk_mb from env or config.
pub fn max_disk_mb_effective(&self) -> u64 {
std::env::var("LEAN_CTX_MAX_DISK_MB")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(self.max_disk_mb)
}
/// Effective max_staleness_days from env or config.
pub fn max_staleness_days_effective(&self) -> u32 {
std::env::var("LEAN_CTX_MAX_STALENESS_DAYS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(self.max_staleness_days)
}
/// Archive max_disk_mb derived from simplified max_disk_mb if the detail
/// value is still at its default. Explicit overrides take priority.
pub fn archive_max_disk_mb_effective(&self) -> u64 {
let budget = self.max_disk_mb_effective();
if budget > 0 && self.archive.max_disk_mb == ArchiveConfig::default().max_disk_mb {
budget * 25 / 100
} else {
self.archive.max_disk_mb
}
}
/// Archive max_age_hours derived from max_staleness_days if the detail
/// value is still at its default. Explicit overrides take priority.
pub fn archive_max_age_hours_effective(&self) -> u64 {
let staleness = self.max_staleness_days_effective();
if staleness > 0 && self.archive.max_age_hours == ArchiveConfig::default().max_age_hours {
staleness as u64 * 24
} else {
self.archive.max_age_hours
}
}
/// Effective on-disk ceiling (MB) for the persisted BM25 index. Single source
/// of truth for `save`/`load`, `cache prune`, and the doctor health check.
///
/// Priority: explicit `bm25_max_cache_mb` › `max_disk_mb` budget (10%) ›
/// generous default ([`DEFAULT_BM25_PERSIST_MB`]). The default is decoupled
/// from the RAM profile so large repos persist instead of rebuilding forever
/// (issue #249).
pub fn bm25_max_cache_mb_effective(&self) -> u64 {
// Explicit per-key override always wins.
if self.bm25_max_cache_mb != serde_defaults::default_bm25_max_cache_mb() {
return self.bm25_max_cache_mb;
}
// Otherwise derive from an explicit overall disk budget when present …
let budget = self.max_disk_mb_effective();
if budget > 0 {
return budget * 10 / 100;
}
// … else fall back to the generous, profile-independent disk default.
DEFAULT_BM25_PERSIST_MB
}
}
impl Config {
/// Returns the path to the global config file (`~/.lean-ctx/config.toml`).
pub fn path() -> Option<PathBuf> {
crate::core::data_dir::lean_ctx_data_dir()
.ok()
.map(|d| d.join("config.toml"))
}
/// Returns the path to the project-local config override file.
pub fn local_path(project_root: &str) -> PathBuf {
PathBuf::from(project_root).join(".lean-ctx.toml")
}
fn find_project_root() -> Option<String> {
static ROOT_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
ROOT_CACHE
.get_or_init(Self::find_project_root_inner)
.clone()
}
fn find_project_root_inner() -> Option<String> {
if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT") {
if !env_root.is_empty() {
return Some(env_root);
}
}
let cwd = std::env::current_dir().ok();
if let Some(root) =
crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
{
let root_path = std::path::Path::new(&root);
let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
let has_marker = root_path.join(".git").exists()
|| root_path.join("Cargo.toml").exists()
|| root_path.join("package.json").exists()
|| root_path.join("go.mod").exists()
|| root_path.join("pyproject.toml").exists()
|| root_path.join(".lean-ctx.toml").exists();
if cwd_is_under_root || has_marker {
return Some(root);
}
}
if let Some(ref cwd) = cwd {
let git_root = std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.current_dir(cwd)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.output()
.ok()
.and_then(|o| {
if o.status.success() {
String::from_utf8(o.stdout)
.ok()
.map(|s| s.trim().to_string())
} else {
None
}
});
if let Some(root) = git_root {
return Some(root);
}
if !crate::core::pathutil::is_broad_or_unsafe_root(cwd) {
return Some(cwd.to_string_lossy().to_string());
}
}
None
}
/// Loads config from disk with caching, merging global + project-local overrides.
pub fn load() -> Self {
static CACHE: Mutex<Option<(Config, SystemTime, Option<SystemTime>)>> = Mutex::new(None);
let Some(path) = Self::path() else {
return Self::default();
};
let local_path = Self::find_project_root().map(|r| Self::local_path(&r));
let mtime = std::fs::metadata(&path)
.and_then(|m| m.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
let local_mtime = local_path
.as_ref()
.and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok());
if let Ok(guard) = CACHE.lock() {
if let Some((ref cfg, ref cached_mtime, ref cached_local_mtime)) = *guard {
if *cached_mtime == mtime && *cached_local_mtime == local_mtime {
return cfg.clone();
}
}
}
let mut cfg: Config = if let Ok(content) = std::fs::read_to_string(&path) {
match toml::from_str(&content) {
Ok(c) => {
record_parse_error(None);
c
}
Err(e) => {
record_parse_error(Some(format!("{e}")));
tracing::warn!("config parse error in {}: {e}", path.display());
eprintln!(
"\x1b[33m[lean-ctx] WARNING: config parse error in {}: {e}\n \
Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
path.display()
);
Self::default()
}
}
} else {
record_parse_error(None);
Self::default()
};
if let Some(ref lp) = local_path {
if let Ok(local_content) = std::fs::read_to_string(lp) {
cfg.merge_local(&local_content);
}
}
if let Ok(mut guard) = CACHE.lock() {
*guard = Some((cfg.clone(), mtime, local_mtime));
}
cfg
}
fn merge_local(&mut self, local_toml: &str) {
let local: Config = match toml::from_str(local_toml) {
Ok(c) => c,
Err(e) => {
tracing::warn!("local config parse error: {e}");
eprintln!(
"\x1b[33m[lean-ctx] WARNING: local .lean-ctx.toml parse error: {e}\n \
Local overrides skipped.\x1b[0m"
);
return;
}
};
if local.ultra_compact {
self.ultra_compact = true;
}
if local.tee_mode != TeeMode::default() {
self.tee_mode = local.tee_mode;
}
if local.output_density != OutputDensity::default() {
self.output_density = local.output_density;
}
if local.checkpoint_interval != 15 {
self.checkpoint_interval = local.checkpoint_interval;
}
if !local.excluded_commands.is_empty() {
self.excluded_commands.extend(local.excluded_commands);
}
if !local.passthrough_urls.is_empty() {
self.passthrough_urls.extend(local.passthrough_urls);
}
if !local.custom_aliases.is_empty() {
self.custom_aliases.extend(local.custom_aliases);
}
// Additive merge with dedup: project-local config can add formats on top
// of the global default (`["toon"]`) without re-listing it.
for fmt in local.preserve_compact_formats {
if !self
.preserve_compact_formats
.iter()
.any(|f| f.eq_ignore_ascii_case(&fmt))
{
self.preserve_compact_formats.push(fmt);
}
}
if local.slow_command_threshold_ms != 5000 {
self.slow_command_threshold_ms = local.slow_command_threshold_ms;
}
if local.theme != "default" {
self.theme = local.theme;
}
if !local.buddy_enabled {
self.buddy_enabled = false;
}
if !local.enable_wakeup_ctx {
self.enable_wakeup_ctx = false;
}
if !local.redirect_exclude.is_empty() {
self.redirect_exclude.extend(local.redirect_exclude);
}
if !local.disabled_tools.is_empty() {
self.disabled_tools.extend(local.disabled_tools);
}
if !local.extra_ignore_patterns.is_empty() {
self.extra_ignore_patterns
.extend(local.extra_ignore_patterns);
}
if local.rules_scope.is_some() {
self.rules_scope = local.rules_scope;
}
if local.proxy.anthropic_upstream.is_some() {
self.proxy.anthropic_upstream = local.proxy.anthropic_upstream;
}
if local.proxy.openai_upstream.is_some() {
self.proxy.openai_upstream = local.proxy.openai_upstream;
}
if local.proxy.gemini_upstream.is_some() {
self.proxy.gemini_upstream = local.proxy.gemini_upstream;
}
if !local.autonomy.enabled {
self.autonomy.enabled = false;
}
if !local.autonomy.auto_preload {
self.autonomy.auto_preload = false;
}
if !local.autonomy.auto_dedup {
self.autonomy.auto_dedup = false;
}
if !local.autonomy.auto_related {
self.autonomy.auto_related = false;
}
if !local.autonomy.auto_consolidate {
self.autonomy.auto_consolidate = false;
}
if local.autonomy.silent_preload {
self.autonomy.silent_preload = true;
}
if !local.autonomy.silent_preload && self.autonomy.silent_preload {
self.autonomy.silent_preload = false;
}
if local.autonomy.dedup_threshold != AutonomyConfig::default().dedup_threshold {
self.autonomy.dedup_threshold = local.autonomy.dedup_threshold;
}
if local.autonomy.consolidate_every_calls
!= AutonomyConfig::default().consolidate_every_calls
{
self.autonomy.consolidate_every_calls = local.autonomy.consolidate_every_calls;
}
if local.autonomy.consolidate_cooldown_secs
!= AutonomyConfig::default().consolidate_cooldown_secs
{
self.autonomy.consolidate_cooldown_secs = local.autonomy.consolidate_cooldown_secs;
}
if !local.autonomy.cognition_loop_enabled {
self.autonomy.cognition_loop_enabled = false;
}
if local.autonomy.cognition_loop_interval_secs
!= AutonomyConfig::default().cognition_loop_interval_secs
{
self.autonomy.cognition_loop_interval_secs =
local.autonomy.cognition_loop_interval_secs;
}
if local.autonomy.cognition_loop_max_steps
!= AutonomyConfig::default().cognition_loop_max_steps
{
self.autonomy.cognition_loop_max_steps = local.autonomy.cognition_loop_max_steps;
}
if local_toml.contains("compression_level") {
self.compression_level = local.compression_level;
}
if local_toml.contains("terse_agent") {
self.terse_agent = local.terse_agent;
}
if !local.archive.enabled {
self.archive.enabled = false;
}
if local.archive.threshold_chars != ArchiveConfig::default().threshold_chars {
self.archive.threshold_chars = local.archive.threshold_chars;
}
if local.archive.max_age_hours != ArchiveConfig::default().max_age_hours {
self.archive.max_age_hours = local.archive.max_age_hours;
}
if local.archive.max_disk_mb != ArchiveConfig::default().max_disk_mb {
self.archive.max_disk_mb = local.archive.max_disk_mb;
}
if !local.archive.ephemeral {
self.archive.ephemeral = false;
}
let mem_def = MemoryPolicy::default();
if local.memory.knowledge.max_facts != mem_def.knowledge.max_facts {
self.memory.knowledge.max_facts = local.memory.knowledge.max_facts;
}
if local.memory.knowledge.max_patterns != mem_def.knowledge.max_patterns {
self.memory.knowledge.max_patterns = local.memory.knowledge.max_patterns;
}
if local.memory.knowledge.max_history != mem_def.knowledge.max_history {
self.memory.knowledge.max_history = local.memory.knowledge.max_history;
}
if local.memory.knowledge.contradiction_threshold
!= mem_def.knowledge.contradiction_threshold
{
self.memory.knowledge.contradiction_threshold =
local.memory.knowledge.contradiction_threshold;
}
if local.memory.episodic.max_episodes != mem_def.episodic.max_episodes {
self.memory.episodic.max_episodes = local.memory.episodic.max_episodes;
}
if local.memory.episodic.max_actions_per_episode != mem_def.episodic.max_actions_per_episode
{
self.memory.episodic.max_actions_per_episode =
local.memory.episodic.max_actions_per_episode;
}
if local.memory.episodic.summary_max_chars != mem_def.episodic.summary_max_chars {
self.memory.episodic.summary_max_chars = local.memory.episodic.summary_max_chars;
}
if local.memory.procedural.min_repetitions != mem_def.procedural.min_repetitions {
self.memory.procedural.min_repetitions = local.memory.procedural.min_repetitions;
}
if local.memory.procedural.min_sequence_len != mem_def.procedural.min_sequence_len {
self.memory.procedural.min_sequence_len = local.memory.procedural.min_sequence_len;
}
if local.memory.procedural.max_procedures != mem_def.procedural.max_procedures {
self.memory.procedural.max_procedures = local.memory.procedural.max_procedures;
}
if local.memory.procedural.max_window_size != mem_def.procedural.max_window_size {
self.memory.procedural.max_window_size = local.memory.procedural.max_window_size;
}
if local.memory.lifecycle.decay_rate != mem_def.lifecycle.decay_rate {
self.memory.lifecycle.decay_rate = local.memory.lifecycle.decay_rate;
}
if local.memory.lifecycle.low_confidence_threshold
!= mem_def.lifecycle.low_confidence_threshold
{
self.memory.lifecycle.low_confidence_threshold =
local.memory.lifecycle.low_confidence_threshold;
}
if local.memory.lifecycle.stale_days != mem_def.lifecycle.stale_days {
self.memory.lifecycle.stale_days = local.memory.lifecycle.stale_days;
}
if local.memory.lifecycle.similarity_threshold != mem_def.lifecycle.similarity_threshold {
self.memory.lifecycle.similarity_threshold =
local.memory.lifecycle.similarity_threshold;
}
if local.memory.embeddings.max_facts != mem_def.embeddings.max_facts {
self.memory.embeddings.max_facts = local.memory.embeddings.max_facts;
}
if !local.allow_paths.is_empty() {
self.allow_paths.extend(local.allow_paths);
}
if !local.extra_roots.is_empty() {
self.extra_roots.extend(local.extra_roots);
}
if local.minimal_overhead {
self.minimal_overhead = true;
}
if local.shell_hook_disabled {
self.shell_hook_disabled = true;
}
if local.shell_activation != ShellActivation::default() {
self.shell_activation = local.shell_activation.clone();
}
if local.bm25_max_cache_mb != default_bm25_max_cache_mb() {
self.bm25_max_cache_mb = local.bm25_max_cache_mb;
}
if local.memory_profile != MemoryProfile::default() {
self.memory_profile = local.memory_profile;
}
if local.memory_cleanup != MemoryCleanup::default() {
self.memory_cleanup = local.memory_cleanup;
}
if !local.shell_allowlist.is_empty() {
self.shell_allowlist = local.shell_allowlist;
}
if !local.shell_allowlist_extra.is_empty() {
self.shell_allowlist_extra
.extend(local.shell_allowlist_extra);
}
if !local.default_tool_categories.is_empty() {
self.default_tool_categories = local.default_tool_categories;
}
if local.tool_profile.is_some() {
self.tool_profile = local.tool_profile;
}
if !local.tools_enabled.is_empty() {
self.tools_enabled = local.tools_enabled;
}
if local.no_degrade {
self.no_degrade = true;
}
if local.profile.is_some() {
self.profile = local.profile;
}
if local.proxy_timeout_ms.is_some() {
self.proxy_timeout_ms = local.proxy_timeout_ms;
}
}
/// Persists the current config to the global config file.
///
/// Preserves user comments, formatting, and unknown keys, keeps the file
/// minimal (defaults that were never set on disk stay implicit), and writes
/// atomically with a `.bak` backup so customizations are always recoverable.
pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
let path = Self::path().ok_or_else(|| {
super::error::LeanCtxError::Config("cannot determine home directory".into())
})?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let content = toml::to_string_pretty(self)
.map_err(|e| super::error::LeanCtxError::Config(e.to_string()))?;
// Baseline = what loading an empty config yields. This honors serde's
// field-level `#[serde(default)]` (which can diverge from the struct's
// `Default` impl), so minimal mode skips exactly the keys that a fresh
// load would produce — no spurious lines on save.
let baseline = toml::from_str::<Self>("").unwrap_or_else(|_| Self::default());
let defaults = toml::to_string_pretty(&baseline)
.map_err(|e| super::error::LeanCtxError::Config(e.to_string()))?;
crate::config_io::write_toml_preserving_minimal(&path, &content, &defaults)
.map_err(super::error::LeanCtxError::Config)?;
Ok(())
}
/// Formats the current config as a human-readable string with file paths.
pub fn show(&self) -> String {
let global_path = Self::path().map_or_else(
|| "~/.lean-ctx/config.toml".to_string(),
|p| p.to_string_lossy().to_string(),
);
let content = toml::to_string_pretty(self).unwrap_or_default();
let mut out = format!("Global config: {global_path}\n\n{content}");
if let Some(root) = Self::find_project_root() {
let local = Self::local_path(&root);
if local.exists() {
out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
} else {
out.push_str(&format!(
"\n\nLocal config: not found (create {} to override per-project)\n",
local.display()
));
}
}
out
}
}