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