Skip to main content

lean_ctx/core/config/
logic.rs

1use std::path::Path;
2
3#[allow(clippy::wildcard_imports)]
4use super::*;
5impl Config {
6    /// Whether opt-in lossless JSON crushing of verbatim data commands (#936) is
7    /// active. `LEAN_CTX_CRUSH_VERBATIM_JSON` (any value) wins, then the
8    /// `crush_verbatim_json` config flag, else `false`.
9    pub fn crush_verbatim_json_enabled(&self) -> bool {
10        std::env::var("LEAN_CTX_CRUSH_VERBATIM_JSON").is_ok() || self.crush_verbatim_json
11    }
12
13    /// Effective proxy bind address (gateway mode, enterprise#8). Precedence:
14    /// `LEAN_CTX_PROXY_BIND_HOST` env > `proxy_bind_host` config > loopback.
15    /// The value must parse as an IP address; anything else (including a blank)
16    /// resolves to `127.0.0.1` — a typo can only ever *narrow* exposure, never
17    /// silently open the listener.
18    #[must_use]
19    pub fn resolved_proxy_bind_host(&self) -> std::net::IpAddr {
20        let raw = std::env::var("LEAN_CTX_PROXY_BIND_HOST")
21            .ok()
22            .filter(|v| !v.trim().is_empty())
23            .or_else(|| self.proxy_bind_host.clone());
24        match raw.as_deref().map(str::trim) {
25            Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
26                tracing::warn!(
27                    "proxy_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
28                );
29                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
30            }),
31            _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
32        }
33    }
34
35    /// Returns the effective rules scope, preferring env var over config file.
36    pub fn rules_scope_effective(&self) -> RulesScope {
37        let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
38            .ok()
39            .or_else(|| self.rules_scope.clone())
40            .unwrap_or_default();
41        match raw.trim().to_lowercase().as_str() {
42            "global" => RulesScope::Global,
43            "project" => RulesScope::Project,
44            _ => RulesScope::Both,
45        }
46    }
47
48    /// Returns the effective rules injection mode, preferring env var over config.
49    /// Default is `Shared` (zero-config discovery via a CLAUDE.md/CODEBUDDY.md/AGENTS.md block).
50    pub fn rules_injection_effective(&self) -> RulesInjection {
51        let raw = std::env::var("LEAN_CTX_RULES_INJECTION")
52            .ok()
53            .or_else(|| self.rules_injection.clone())
54            .unwrap_or_default();
55        match raw.trim().to_lowercase().as_str() {
56            "dedicated" => RulesInjection::Dedicated,
57            "off" | "none" | "disabled" => RulesInjection::Off,
58            _ => RulesInjection::Shared,
59        }
60    }
61
62    /// Provider prompt-cache hit rate for net-of-injection (#1104).
63    /// Returns the configured value or None (caller picks the default).
64    #[must_use]
65    pub fn dashboard_cache_hit_rate(&self) -> Option<f64> {
66        std::env::var("LEAN_CTX_CACHE_HIT_RATE")
67            .ok()
68            .and_then(|v| v.parse().ok())
69            .or(self.dashboard_cache_hit_rate)
70    }
71    /// Returns the user-configured hook mode override, or `None` for auto-detect.
72    /// Env var `LEAN_CTX_HOOK_MODE` takes priority over config.
73    #[must_use]
74    pub fn hook_mode_override(&self) -> Option<crate::hooks::HookMode> {
75        let raw = std::env::var("LEAN_CTX_HOOK_MODE")
76            .ok()
77            .or_else(|| self.hook_mode.clone())?;
78        crate::hooks::HookMode::from_str_loose(raw.trim())
79    }
80
81    /// Returns the effective permission-inheritance mode, preferring the
82    /// `LEAN_CTX_PERMISSION_INHERITANCE` env var over config. Default is `Off`.
83    /// Accepts `on`/`true`/`1` as enabled.
84    #[must_use]
85    pub fn permission_inheritance_effective(&self) -> PermissionInheritance {
86        let raw = std::env::var("LEAN_CTX_PERMISSION_INHERITANCE")
87            .ok()
88            .or_else(|| self.permission_inheritance.clone())
89            .unwrap_or_default();
90        match raw.trim().to_lowercase().as_str() {
91            "off" | "false" | "0" | "none" => PermissionInheritance::Off,
92            // GH #1428: default to On so IDE permission rules (e.g. "rm *": "ask")
93            // are honored by ctx_* tools out of the box. The check is read-only and
94            // only activates when an IDE with a permission system is detected
95            // (v1: OpenCode); undetected IDEs are always allowed through.
96            _ => PermissionInheritance::On,
97        }
98    }
99
100    /// True when lean-ctx should inject its rules via each agent's dedicated,
101    /// non-polluting auto-load path *and* global rules are in scope.
102    ///
103    /// Gates the Claude/Codex `SessionStart` `additionalContext` summary: it
104    /// stands in for the (now-skipped) shared CLAUDE.md/CODEBUDDY.md/AGENTS.md block, so it
105    /// only fires when injection is `Dedicated` and the scope isn't project-only.
106    #[must_use]
107    pub fn dedicated_session_context_active(&self) -> bool {
108        self.rules_injection_effective() == RulesInjection::Dedicated
109            && self.rules_scope_effective() != RulesScope::Project
110    }
111
112    pub(super) fn parse_disabled_tools_env(val: &str) -> Vec<String> {
113        val.split(',')
114            .map(|s| s.trim().to_string())
115            .filter(|s| !s.is_empty())
116            .collect()
117    }
118
119    /// Returns the effective disabled tools list, preferring env var over config
120    /// file. When `prefer_native_editor` is active, the lean-ctx edit tools are
121    /// folded in so they are hidden from `list_tools` (#454).
122    pub fn disabled_tools_effective(&self) -> Vec<String> {
123        let mut list = if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
124            Self::parse_disabled_tools_env(&val)
125        } else {
126            self.disabled_tools.clone()
127        };
128        if self.prefer_native_editor_effective() {
129            for name in EDIT_TOOL_NAMES {
130                if !list.iter().any(|t| t == name) {
131                    list.push((*name).to_string());
132                }
133            }
134        }
135        list
136    }
137
138    /// Whether lean-ctx edit operations are disabled in favour of the host's
139    /// native editor (#454). `LEAN_CTX_PREFER_NATIVE_EDITOR` wins over config.
140    pub fn prefer_native_editor_effective(&self) -> bool {
141        match std::env::var("LEAN_CTX_PREFER_NATIVE_EDITOR") {
142            Ok(raw) => matches!(
143                raw.trim().to_lowercase().as_str(),
144                "1" | "true" | "yes" | "on"
145            ),
146            Err(_) => self.prefer_native_editor,
147        }
148    }
149
150    /// Cap on the rayon index-build worker threads. `LEANCTX_INDEX_THREADS` wins
151    /// over config; `0` means "no cap" — rayon's all-cores default is kept.
152    pub fn max_index_threads_effective(&self) -> usize {
153        std::env::var("LEANCTX_INDEX_THREADS")
154            .ok()
155            .and_then(|raw| raw.trim().parse::<usize>().ok())
156            .unwrap_or(self.max_index_threads)
157    }
158
159    /// Whether `name` is a lean-ctx edit operation that must be blocked from
160    /// dispatch (direct and via `ctx_call`) when [`Self::prefer_native_editor_effective`]
161    /// is set (#454). Read/search/shell/memory tools are never blocked.
162    pub fn edit_tool_blocked(&self, name: &str) -> bool {
163        self.prefer_native_editor_effective() && EDIT_TOOL_NAMES.contains(&name)
164    }
165
166    /// Returns `true` if minimal overhead is enabled via env var or config.
167    pub fn minimal_overhead_effective(&self) -> bool {
168        std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
169    }
170
171    /// The `LEAN_CTX_MINIMAL` env var is the documented do-not-touch-anything
172    /// escape hatch (3.9.19 triage incident): only IT may skip the pipeline's
173    /// archive + ephemeral-firewall safety net. The `minimal_overhead` config
174    /// key (default `true`) trims MCP instruction overhead only and must never
175    /// disable archiving (#1540).
176    pub fn minimal_escape_hatch() -> bool {
177        std::env::var("LEAN_CTX_MINIMAL").is_ok()
178    }
179
180    /// Returns `true` if structure-first auto reads are enabled.
181    ///
182    /// The `LEAN_CTX_STRUCTURE_FIRST` env var wins over the config field, and
183    /// accepts the usual truthy/falsy spellings so a harness can flip it per run
184    /// (`LEAN_CTX_STRUCTURE_FIRST=0` forces it off even if config enables it).
185    pub fn structure_first_effective(&self) -> bool {
186        match std::env::var("LEAN_CTX_STRUCTURE_FIRST") {
187            Ok(raw) => matches!(
188                raw.trim().to_lowercase().as_str(),
189                "1" | "true" | "yes" | "on"
190            ),
191            Err(_) => self.structure_first,
192        }
193    }
194
195    /// Effective session token limit. 0 = unlimited.
196    pub fn session_token_limit_effective(&self) -> usize {
197        std::env::var("LEAN_CTX_SESSION_TOKEN_LIMIT")
198            .ok()
199            .and_then(|v| v.trim().parse().ok())
200            .unwrap_or(self.session_token_limit)
201    }
202
203    /// Effective turn budget (fresh token limit per response). 0 = unlimited.
204    pub fn turn_fresh_limit_effective(&self) -> usize {
205        std::env::var("LEAN_CTX_TURN_FRESH_LIMIT")
206            .ok()
207            .and_then(|v| v.trim().parse().ok())
208            .unwrap_or(self.turn_fresh_limit)
209    }
210
211    /// Effective turn budget for an explicitly verbatim response (#1582).
212    ///
213    /// 0 = unlimited. Never below `turn_fresh_limit_effective()`: raising the
214    /// ordinary budget above the verbatim one must not make `raw=true` deliver
215    /// *less* than a compressed read of the same file. An unlimited ordinary
216    /// budget stays unlimited here.
217    pub fn turn_fresh_limit_verbatim_effective(&self) -> usize {
218        let ordinary = self.turn_fresh_limit_effective();
219        if ordinary == 0 {
220            return 0;
221        }
222        let verbatim = std::env::var("LEAN_CTX_TURN_FRESH_LIMIT_VERBATIM")
223            .ok()
224            .and_then(|v| v.trim().parse().ok())
225            .unwrap_or(self.turn_fresh_limit_verbatim);
226        resolve_verbatim_limit(ordinary, verbatim)
227    }
228
229    /// Whether progressive disclosure is active. Default true. The env var
230    /// `LEAN_CTX_PROGRESSIVE_DISCLOSURE` overrides the config field.
231    pub fn progressive_disclosure_effective(&self) -> bool {
232        match std::env::var("LEAN_CTX_PROGRESSIVE_DISCLOSURE") {
233            Ok(raw) => matches!(
234                raw.trim().to_lowercase().as_str(),
235                "1" | "true" | "yes" | "on"
236            ),
237            Err(_) => self.progressive_disclosure,
238        }
239    }
240
241    /// Returns `true` when the adaptive learning signals may participate in
242    /// `auto` mode resolution (#683). Off by default for a deterministic,
243    /// I/O-light cascade; the `LEAN_CTX_AUTO_MODE_LEARNING` env var wins over the
244    /// config field and accepts the usual truthy/falsy spellings.
245    pub fn auto_mode_learning_effective(&self) -> bool {
246        match std::env::var("LEAN_CTX_AUTO_MODE_LEARNING") {
247            Ok(raw) => matches!(
248                raw.trim().to_lowercase().as_str(),
249                "1" | "true" | "yes" | "on"
250            ),
251            Err(_) => self.auto_mode_learning,
252        }
253    }
254
255    /// Returns `true` when probabilistic exploration (Thompson sampling,
256    /// Boltzmann-temperature eviction, simulated annealing) may influence
257    /// decisions. Off by default so tool output stays a deterministic, byte-
258    /// stable function of (content, mode, task) — the determinism contract
259    /// (#498) that lets provider prompt caching apply. The `LEAN_CTX_STOCHASTIC`
260    /// env var wins (the usual truthy/falsy spellings); otherwise it follows
261    /// [`Self::auto_mode_learning_effective`], which is itself off by default.
262    pub fn is_stochastic_enabled(&self) -> bool {
263        match std::env::var("LEAN_CTX_STOCHASTIC") {
264            Ok(raw) => matches!(
265                raw.trim().to_lowercase().as_str(),
266                "1" | "true" | "yes" | "on"
267            ),
268            Err(_) => self.auto_mode_learning_effective(),
269        }
270    }
271
272    /// Returns `true` if minimal overhead should be enabled for this MCP client.
273    ///
274    /// This is a superset of `minimal_overhead_effective()`:
275    /// - `LEAN_CTX_OVERHEAD_MODE=minimal` forces minimal overhead
276    /// - `LEAN_CTX_OVERHEAD_MODE=full` disables client/model heuristics (still honors LEAN_CTX_MINIMAL / config)
277    /// - In auto mode (default), certain low-context clients/models are treated as minimal to prevent
278    ///   large metadata blocks from destabilizing smaller context windows (e.g. Hermes + MiniMax).
279    pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool {
280        if let Ok(raw) = std::env::var("LEAN_CTX_OVERHEAD_MODE") {
281            match raw.trim().to_lowercase().as_str() {
282                "minimal" => return true,
283                "full" => return self.minimal_overhead_effective(),
284                _ => {}
285            }
286        }
287
288        if self.minimal_overhead_effective() {
289            return true;
290        }
291
292        let client_lower = client_name.trim().to_lowercase();
293        if !client_lower.is_empty() {
294            if let Ok(list) = std::env::var("LEAN_CTX_MINIMAL_CLIENTS") {
295                for needle in list.split(',').map(|s| s.trim().to_lowercase()) {
296                    if !needle.is_empty() && client_lower.contains(&needle) {
297                        return true;
298                    }
299                }
300            } else if client_lower.contains("hermes") || client_lower.contains("minimax") {
301                return true;
302            }
303        }
304
305        let model = std::env::var("LEAN_CTX_MODEL")
306            .or_else(|_| std::env::var("LCTX_MODEL"))
307            .unwrap_or_default();
308        let model = model.trim().to_lowercase();
309        if !model.is_empty() {
310            let m = model.replace(['_', ' '], "-");
311            if m.contains("minimax")
312                || m.contains("mini-max")
313                || m.contains("m2.7")
314                || m.contains("m2-7")
315            {
316                return true;
317            }
318        }
319
320        false
321    }
322
323    /// Returns `true` if shell hook injection is disabled via env var or config.
324    pub fn shell_hook_disabled_effective(&self) -> bool {
325        std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
326    }
327
328    /// Returns the effective shell activation mode (env var > config > default).
329    pub fn shell_activation_effective(&self) -> ShellActivation {
330        ShellActivation::effective(self)
331    }
332
333    /// Returns `true` if `ctx_shell` may accept shell file-write redirects.
334    /// `LEAN_CTX_SHELL_ALLOW_WRITES` (`1`/`true`/`yes`/`on`) overrides
335    /// `config.toml`. The real command gating still applies either way.
336    pub fn shell_allow_writes_effective(&self) -> bool {
337        match std::env::var("LEAN_CTX_SHELL_ALLOW_WRITES") {
338            Ok(raw) => matches!(
339                raw.trim().to_ascii_lowercase().as_str(),
340                "1" | "true" | "yes" | "on"
341            ),
342            Err(_) => self.shell_allow_writes,
343        }
344    }
345
346    /// Returns the effective paths where shell output capture may write.
347    /// Empty configuration intentionally falls back to OS temp directories.
348    pub fn shell_write_allow_paths_effective(&self) -> Vec<String> {
349        if self.write_allow_paths.is_empty() {
350            default_shell_write_allow_paths()
351        } else {
352            self.write_allow_paths.clone()
353        }
354    }
355
356    /// #814: returns `true` if `ctx_shell` may accept inline interpreter scripts
357    /// (`python3 -c "..."`, `node -e "..."`, etc.).
358    /// `LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS` (`1`/`true`/`yes`/`on`) overrides
359    /// `config.toml`. The real command gating (allowlist) still applies.
360    pub fn shell_allow_inline_scripts_effective(&self) -> bool {
361        match std::env::var("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS") {
362            Ok(raw) => matches!(
363                raw.trim().to_ascii_lowercase().as_str(),
364                "1" | "true" | "yes" | "on"
365            ),
366            Err(_) => self.shell_allow_inline_scripts,
367        }
368    }
369
370    /// Returns `true` if the daily update check is disabled via env var or config.
371    pub fn update_check_disabled_effective(&self) -> bool {
372        std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
373    }
374
375    pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
376        let mut policy = self.memory.clone();
377        policy.apply_env_overrides();
378
379        let budget = self.max_disk_mb_effective();
380        if budget > 0 {
381            let scale_factor = (budget as f64 / 500.0).clamp(0.5, 10.0);
382            let default_policy = MemoryPolicy::default();
383            if policy.knowledge.max_facts == default_policy.knowledge.max_facts {
384                policy.knowledge.max_facts = (200.0 * scale_factor) as usize;
385            }
386            if policy.knowledge.max_patterns == default_policy.knowledge.max_patterns {
387                policy.knowledge.max_patterns = (50.0 * scale_factor) as usize;
388            }
389            if policy.episodic.max_episodes == default_policy.episodic.max_episodes {
390                policy.episodic.max_episodes = (500.0 * scale_factor) as usize;
391            }
392            if policy.procedural.max_procedures == default_policy.procedural.max_procedures {
393                policy.procedural.max_procedures = (100.0 * scale_factor) as usize;
394            }
395        }
396
397        policy.validate()?;
398        Ok(policy)
399    }
400
401    /// Returns the effective set of default tool categories.
402    /// Priority: LCTX_DEFAULT_CATEGORIES env var > config.toml > hardcoded default.
403    pub fn default_tool_categories_effective(&self) -> Vec<String> {
404        if let Ok(val) = std::env::var("LCTX_DEFAULT_CATEGORIES") {
405            return val
406                .split(',')
407                .map(|s| s.trim().to_lowercase())
408                .filter(|s| !s.is_empty())
409                .collect();
410        }
411        if !self.default_tool_categories.is_empty() {
412            return self
413                .default_tool_categories
414                .iter()
415                .map(|s| s.to_lowercase())
416                .collect();
417        }
418        vec!["core".to_string()]
419    }
420
421    /// Returns the effective tool profile.
422    /// Priority: LEAN_CTX_TOOL_PROFILE env > config tool_profile > config
423    /// tools_enabled > active persona's tool surface > power.
424    ///
425    /// Explicit settings win (backward compatible); when none are set, the
426    /// active persona supplies the tool surface (the `coding` default resolves
427    /// to `power`, so existing installs are unaffected).
428    pub fn tool_profile_effective(&self) -> super::tool_profiles::ToolProfile {
429        super::persona::Persona::resolve(self).effective_tool_profile(self)
430    }
431
432    /// The `[sensitivity]` config with the active persona's floor folded in
433    /// (persona-spec-v1). Enforcement chokepoints use this instead of the raw
434    /// field so a persona like `lead-gen` (`sensitivity_floor = "confidential"`)
435    /// protects PII out of the box. The `coding` default (`public`) passes the
436    /// config through unchanged.
437    #[must_use]
438    pub fn sensitivity_effective(&self) -> crate::core::sensitivity::SensitivityConfig {
439        self.sensitivity
440            .clone()
441            .with_persona_floor(super::persona::Persona::resolve(self).sensitivity_floor)
442    }
443
444    /// Returns `true` if all automatic read-mode degradation is disabled.
445    /// Checks LCTX_NO_DEGRADE env var first, then config.toml field.
446    pub fn no_degrade_effective(&self) -> bool {
447        if let Ok(val) = std::env::var("LCTX_NO_DEGRADE") {
448            return val == "1" || val.eq_ignore_ascii_case("true");
449        }
450        self.no_degrade
451    }
452
453    /// Returns `true` if explicit `full`/`lines:N-M` re-reads of
454    /// cached-but-changed files should be served as deltas (`mode=diff`)
455    /// instead of re-emitting full content.
456    ///
457    /// Checks the `LCTX_DELTA_EXPLICIT` env var first, then the config.toml
458    /// field. Unlike a presence-only knob, an explicit `0`/`false` in the env
459    /// forces the feature OFF even when the config field is `true`, so the env
460    /// can fully override config in both directions.
461    pub fn delta_explicit_effective(&self) -> bool {
462        if let Ok(val) = std::env::var("LCTX_DELTA_EXPLICIT") {
463            return val == "1" || val.eq_ignore_ascii_case("true");
464        }
465        self.delta_explicit
466    }
467
468    /// Effective max_disk_mb from env or config.
469    pub fn max_disk_mb_effective(&self) -> u64 {
470        std::env::var("LEAN_CTX_MAX_DISK_MB")
471            .ok()
472            .and_then(|v| v.parse().ok())
473            .unwrap_or(self.max_disk_mb)
474    }
475
476    /// Effective max_staleness_days from env or config.
477    pub fn max_staleness_days_effective(&self) -> u32 {
478        std::env::var("LEAN_CTX_MAX_STALENESS_DAYS")
479            .ok()
480            .and_then(|v| v.parse().ok())
481            .unwrap_or(self.max_staleness_days)
482    }
483
484    /// Effective retention window for explicit session cleanup, independent of
485    /// the archive staleness policy.
486    pub fn session_retention_days_effective(&self) -> u32 {
487        std::env::var("LEAN_CTX_SESSION_RETENTION_DAYS")
488            .ok()
489            .and_then(|value| value.parse().ok())
490            .unwrap_or(self.session_retention_days)
491    }
492
493    /// Effective fixed-context budget (tokens) from env or config (#964). `0`
494    /// (env or config) disables the warning; otherwise the per-session footprint
495    /// is checked against this in `doctor overhead` and `gain`.
496    pub fn context_budget_tokens_effective(&self) -> usize {
497        std::env::var("LEAN_CTX_CONTEXT_BUDGET_TOKENS")
498            .ok()
499            .and_then(|v| v.parse().ok())
500            .unwrap_or(self.context.budget_tokens)
501    }
502
503    /// Whether later tool calls may receive matching CCR context.
504    pub fn proactive_expansion_effective(&self) -> bool {
505        self.context.proactive_expansion
506    }
507
508    /// Per-response token budget for proactive CCR expansion.
509    pub fn proactive_expansion_budget_tokens_effective(&self) -> usize {
510        self.context.proactive_expansion_budget_tokens
511    }
512
513    /// Normalized BM25 score threshold for proactive CCR expansion.
514    pub fn proactive_expansion_threshold_effective(&self) -> f64 {
515        self.context.proactive_expansion_threshold
516    }
517
518    /// Maximum archive age considered for proactive expansion.
519    pub fn proactive_expansion_max_age_secs_effective(&self) -> u64 {
520        self.context.proactive_expansion_max_age_secs
521    }
522
523    /// Archive max_disk_mb derived from simplified max_disk_mb if the detail
524    /// value is still at its default. Explicit overrides take priority.
525    pub fn archive_max_disk_mb_effective(&self) -> u64 {
526        let budget = self.max_disk_mb_effective();
527        if budget > 0 && self.archive.max_disk_mb == ArchiveConfig::default().max_disk_mb {
528            budget * 25 / 100
529        } else {
530            self.archive.max_disk_mb
531        }
532    }
533
534    /// Archive max_age_hours derived from max_staleness_days if the detail
535    /// value is still at its default. Explicit overrides take priority.
536    pub fn archive_max_age_hours_effective(&self) -> u64 {
537        let staleness = self.max_staleness_days_effective();
538        if staleness > 0 && self.archive.max_age_hours == ArchiveConfig::default().max_age_hours {
539            staleness as u64 * 24
540        } else {
541            self.archive.max_age_hours
542        }
543    }
544
545    /// Effective on-disk ceiling (MB) for the persisted BM25 index. Single source
546    /// of truth for `save`/`load`, `cache prune`, and the doctor health check.
547    ///
548    /// Priority: explicit `bm25_max_cache_mb` › `max_disk_mb` budget (10%) ›
549    /// generous default ([`DEFAULT_BM25_PERSIST_MB`]). The default is decoupled
550    /// from the RAM profile so large repos persist instead of rebuilding forever
551    /// (issue #249).
552    pub fn bm25_max_cache_mb_effective(&self) -> u64 {
553        if self.bm25_max_cache_mb != serde_defaults::default_bm25_max_cache_mb() {
554            return self.bm25_max_cache_mb;
555        }
556        let budget = self.max_disk_mb_effective();
557        if budget > 0 {
558            return budget * 10 / 100;
559        }
560        DEFAULT_BM25_PERSIST_MB
561    }
562}
563
564impl Config {
565    /// Safely mutate and persist the GLOBAL config. Reads the global file only
566    /// (no project-local merge), applies `f`, then writes minimally. Refuses
567    /// (returns `Err`) when the file exists but is unparseable, so a typo can
568    /// never clobber a customized config (#443). Returns the saved `Config`.
569    ///
570    /// This is the canonical persistence entry point: prefer it over
571    /// `Config::load()` followed by `save()`, which leaks project-local
572    /// overrides into the global file.
573    pub fn update_global<F>(f: F) -> std::result::Result<Self, super::error::LeanCtxError>
574    where
575        F: FnOnce(&mut Self),
576    {
577        let path = Self::path().ok_or_else(|| {
578            super::error::LeanCtxError::Config("cannot determine home directory".into())
579        })?;
580        Self::update_global_at(&path, f)
581    }
582
583    /// Path-parameterized core of [`Config::update_global`] (unit-testable).
584    pub(super) fn update_global_at<F>(
585        path: &Path,
586        f: F,
587    ) -> std::result::Result<Self, super::error::LeanCtxError>
588    where
589        F: FnOnce(&mut Self),
590    {
591        let mut cfg = match std::fs::read_to_string(path) {
592            Ok(raw) if !raw.trim().is_empty() => toml::from_str::<Self>(&raw).map_err(|e| {
593                super::error::LeanCtxError::Config(
594                    format!(
595                        "refusing to modify an unparseable config.toml ({e}); fix it \
596                     manually or run `lean-ctx doctor --fix`, then retry"
597                    )
598                    .into(),
599                )
600            })?,
601            _ => Self::default(),
602        };
603        f(&mut cfg);
604        cfg.save_to(path)?;
605        Ok(cfg)
606    }
607
608    /// Persists the current config to the global config file.
609    ///
610    /// Preserves user comments, formatting, and unknown keys, keeps the file
611    /// minimal (defaults that were never set on disk stay implicit), and writes
612    /// atomically with a `.bak` backup so customizations are always recoverable.
613    pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
614        let path = Self::path().ok_or_else(|| {
615            super::error::LeanCtxError::Config("cannot determine home directory".into())
616        })?;
617        self.save_to(&path)
618    }
619
620    /// Path-parameterized core of [`Config::save`] (unit-testable).
621    pub(super) fn save_to(
622        &self,
623        path: &Path,
624    ) -> std::result::Result<(), super::error::LeanCtxError> {
625        if let Some(parent) = path.parent() {
626            std::fs::create_dir_all(parent)?;
627        }
628        let content = toml::to_string_pretty(self)
629            .map_err(|e| super::error::LeanCtxError::Config(e.to_string().into()))?;
630        // Baseline = what loading an empty config yields. This honors serde's
631        // field-level `#[serde(default)]` (which can diverge from the struct's
632        // `Default` impl), so minimal mode skips exactly the keys that a fresh
633        // load would produce — no spurious lines on save.
634        let baseline = toml::from_str::<Self>("").unwrap_or_else(|_| Self::default());
635        let defaults = toml::to_string_pretty(&baseline)
636            .map_err(|e| super::error::LeanCtxError::Config(e.to_string().into()))?;
637        crate::config_io::write_toml_preserving_minimal(path, &content, &defaults)
638            .map_err(|e| super::error::LeanCtxError::Config(e.into()))?;
639        Ok(())
640    }
641
642    /// Formats the current config as a human-readable string with file paths.
643    pub fn show(&self) -> String {
644        let global_path = Self::path().map_or_else(
645            || "~/.lean-ctx/config.toml".to_string(),
646            |p| p.to_string_lossy().to_string(),
647        );
648        let content = toml::to_string_pretty(self).unwrap_or_default();
649        let mut out = format!("Global config: {global_path}\n\n{content}");
650
651        if let Some(root) = Self::find_project_root() {
652            let local = Self::local_path(&root);
653            if local.exists() {
654                out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
655            } else {
656                out.push_str(&format!(
657                    "\n\nLocal config: not found (create {} to override per-project)\n",
658                    local.display()
659                ));
660            }
661        }
662        out
663    }
664}
665
666/// Resolve the verbatim turn budget from the two configured limits (#1582).
667///
668/// Pure so the precedence rules are testable without touching process env:
669/// `0` means unlimited, and the verbatim budget is never smaller than the
670/// ordinary one.
671fn resolve_verbatim_limit(ordinary: usize, verbatim: usize) -> usize {
672    if verbatim == 0 {
673        return 0;
674    }
675    verbatim.max(ordinary)
676}
677
678#[cfg(test)]
679mod verbatim_budget_tests {
680    use super::resolve_verbatim_limit;
681
682    #[test]
683    fn verbatim_budget_is_larger_than_the_ordinary_backstop() {
684        assert_eq!(resolve_verbatim_limit(4096, 32_768), 32_768);
685    }
686
687    #[test]
688    fn zero_means_unlimited_verbatim_reads() {
689        assert_eq!(resolve_verbatim_limit(4096, 0), 0);
690    }
691
692    #[test]
693    fn a_raised_ordinary_budget_is_never_undercut() {
694        // Someone who sets turn_fresh_limit = 64k must not get *less* content
695        // back from an explicit raw read than from a compressed one.
696        assert_eq!(resolve_verbatim_limit(65_536, 32_768), 65_536);
697    }
698}