Skip to main content

lean_ctx/core/
config.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3use std::sync::Mutex;
4use std::time::SystemTime;
5
6use super::memory_policy::MemoryPolicy;
7
8/// Controls when shell output is tee'd to disk for later retrieval.
9#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
10#[serde(rename_all = "lowercase")]
11pub enum TeeMode {
12    Never,
13    #[default]
14    Failures,
15    Always,
16}
17
18/// Controls agent output verbosity level injected into MCP instructions.
19#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
20#[serde(rename_all = "lowercase")]
21pub enum TerseAgent {
22    #[default]
23    Off,
24    Lite,
25    Full,
26    Ultra,
27}
28
29impl TerseAgent {
30    /// Reads the terse-agent level from the `LEAN_CTX_TERSE_AGENT` env var.
31    pub fn from_env() -> Self {
32        match std::env::var("LEAN_CTX_TERSE_AGENT")
33            .unwrap_or_default()
34            .to_lowercase()
35            .as_str()
36        {
37            "lite" => Self::Lite,
38            "full" => Self::Full,
39            "ultra" => Self::Ultra,
40            _ => Self::Off,
41        }
42    }
43
44    /// Returns the effective terse level, preferring env var over config value.
45    pub fn effective(config_val: &TerseAgent) -> Self {
46        match std::env::var("LEAN_CTX_TERSE_AGENT") {
47            Ok(val) if !val.is_empty() => match val.to_lowercase().as_str() {
48                "lite" => Self::Lite,
49                "full" => Self::Full,
50                "ultra" => Self::Ultra,
51                _ => Self::Off,
52            },
53            _ => config_val.clone(),
54        }
55    }
56
57    /// Returns `true` if any terse level is enabled (not `Off`).
58    pub fn is_active(&self) -> bool {
59        !matches!(self, Self::Off)
60    }
61}
62
63/// Controls how dense/compact MCP tool output is formatted.
64#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
65#[serde(rename_all = "lowercase")]
66pub enum OutputDensity {
67    #[default]
68    Normal,
69    Terse,
70    Ultra,
71}
72
73impl OutputDensity {
74    /// Reads the output density from the `LEAN_CTX_OUTPUT_DENSITY` env var.
75    pub fn from_env() -> Self {
76        match std::env::var("LEAN_CTX_OUTPUT_DENSITY")
77            .unwrap_or_default()
78            .to_lowercase()
79            .as_str()
80        {
81            "terse" => Self::Terse,
82            "ultra" => Self::Ultra,
83            _ => Self::Normal,
84        }
85    }
86
87    /// Returns the effective density, preferring env var over config value.
88    pub fn effective(config_val: &OutputDensity) -> Self {
89        let env_val = Self::from_env();
90        if env_val != Self::Normal {
91            return env_val;
92        }
93        let profile_val = crate::core::profiles::active_profile()
94            .compression
95            .output_density_effective()
96            .to_lowercase();
97        let profile_density = match profile_val.as_str() {
98            "terse" => Self::Terse,
99            "ultra" => Self::Ultra,
100            _ => Self::Normal,
101        };
102        if profile_density != Self::Normal {
103            return profile_density;
104        }
105        config_val.clone()
106    }
107}
108
109/// Global lean-ctx configuration loaded from `config.toml`, merged with project-local overrides.
110#[derive(Debug, Clone, Serialize, Deserialize)]
111#[serde(default)]
112pub struct Config {
113    pub ultra_compact: bool,
114    #[serde(default, deserialize_with = "deserialize_tee_mode")]
115    pub tee_mode: TeeMode,
116    #[serde(default)]
117    pub output_density: OutputDensity,
118    pub checkpoint_interval: u32,
119    pub excluded_commands: Vec<String>,
120    pub passthrough_urls: Vec<String>,
121    pub custom_aliases: Vec<AliasEntry>,
122    /// Commands taking longer than this threshold (ms) are recorded in the slow log.
123    /// Set to 0 to disable slow logging.
124    pub slow_command_threshold_ms: u64,
125    #[serde(default = "default_theme")]
126    pub theme: String,
127    #[serde(default)]
128    pub cloud: CloudConfig,
129    #[serde(default)]
130    pub autonomy: AutonomyConfig,
131    #[serde(default)]
132    pub proxy: ProxyConfig,
133    #[serde(default = "default_buddy_enabled")]
134    pub buddy_enabled: bool,
135    #[serde(default)]
136    pub redirect_exclude: Vec<String>,
137    /// Tools to exclude from the MCP tool list returned by list_tools.
138    /// Accepts exact tool names (e.g. `["ctx_graph", "ctx_agent"]`).
139    /// Empty by default — all tools listed, no behaviour change.
140    #[serde(default)]
141    pub disabled_tools: Vec<String>,
142    #[serde(default)]
143    pub loop_detection: LoopDetectionConfig,
144    /// Controls where lean-ctx installs agent rule files.
145    /// Values: "both" (default), "global" (home-dir only), "project" (repo-local only).
146    /// Override via LEAN_CTX_RULES_SCOPE env var.
147    #[serde(default)]
148    pub rules_scope: Option<String>,
149    /// Extra glob patterns to ignore in graph/overview/preload (repo-local).
150    /// Example: `["externals/**", "target/**", "temp/**"]`
151    #[serde(default)]
152    pub extra_ignore_patterns: Vec<String>,
153    /// Controls agent output verbosity via instructions injection.
154    /// Values: "off" (default), "lite", "full", "ultra".
155    /// Override via LEAN_CTX_TERSE_AGENT env var.
156    #[serde(default)]
157    pub terse_agent: TerseAgent,
158    /// Archive configuration for zero-loss compression.
159    #[serde(default)]
160    pub archive: ArchiveConfig,
161    /// Memory policy (knowledge/episodic/procedural/lifecycle budgets & thresholds).
162    #[serde(default)]
163    pub memory: MemoryPolicy,
164    /// Additional paths allowed by PathJail (absolute).
165    /// Useful for multi-project workspaces where the jail root is a parent directory.
166    /// Override via LEAN_CTX_ALLOW_PATH env var (path-list separator).
167    #[serde(default)]
168    pub allow_paths: Vec<String>,
169    /// Enable content-defined chunking (Rabin-Karp) for cache-optimal output ordering.
170    /// Stable chunks are emitted first to maximize prompt cache hits.
171    #[serde(default)]
172    pub content_defined_chunking: bool,
173    /// Skip session/knowledge/gotcha blocks in MCP instructions to minimize token overhead.
174    /// Override via LEAN_CTX_MINIMAL env var.
175    #[serde(default)]
176    pub minimal_overhead: bool,
177    /// Disable shell hook injection (the _lc() function that wraps CLI commands).
178    /// Override via LEAN_CTX_NO_HOOK env var.
179    #[serde(default)]
180    pub shell_hook_disabled: bool,
181    /// Disable the daily version check against leanctx.com/version.txt.
182    /// Override via LEAN_CTX_NO_UPDATE_CHECK env var.
183    #[serde(default)]
184    pub update_check_disabled: bool,
185}
186
187/// Settings for the zero-loss compression archive (large tool outputs saved to disk).
188#[derive(Debug, Clone, Serialize, Deserialize)]
189#[serde(default)]
190pub struct ArchiveConfig {
191    pub enabled: bool,
192    pub threshold_chars: usize,
193    pub max_age_hours: u64,
194    pub max_disk_mb: u64,
195}
196
197impl Default for ArchiveConfig {
198    fn default() -> Self {
199        Self {
200            enabled: true,
201            threshold_chars: 4096,
202            max_age_hours: 48,
203            max_disk_mb: 500,
204        }
205    }
206}
207
208/// API proxy upstream overrides. `None` = use provider default.
209#[derive(Debug, Clone, Default, Serialize, Deserialize)]
210#[serde(default)]
211pub struct ProxyConfig {
212    pub anthropic_upstream: Option<String>,
213    pub openai_upstream: Option<String>,
214    pub gemini_upstream: Option<String>,
215}
216
217impl ProxyConfig {
218    pub fn resolve_upstream(&self, provider: ProxyProvider) -> String {
219        let (env_var, config_val, default) = match provider {
220            ProxyProvider::Anthropic => (
221                "LEAN_CTX_ANTHROPIC_UPSTREAM",
222                self.anthropic_upstream.as_deref(),
223                "https://api.anthropic.com",
224            ),
225            ProxyProvider::OpenAi => (
226                "LEAN_CTX_OPENAI_UPSTREAM",
227                self.openai_upstream.as_deref(),
228                "https://api.openai.com",
229            ),
230            ProxyProvider::Gemini => (
231                "LEAN_CTX_GEMINI_UPSTREAM",
232                self.gemini_upstream.as_deref(),
233                "https://generativelanguage.googleapis.com",
234            ),
235        };
236        std::env::var(env_var)
237            .ok()
238            .and_then(|v| normalize_url_opt(&v))
239            .or_else(|| config_val.and_then(normalize_url_opt))
240            .unwrap_or_else(|| normalize_url(default))
241    }
242}
243
244#[derive(Debug, Clone, Copy)]
245pub enum ProxyProvider {
246    Anthropic,
247    OpenAi,
248    Gemini,
249}
250
251pub fn normalize_url(value: &str) -> String {
252    value.trim().trim_end_matches('/').to_string()
253}
254
255pub fn normalize_url_opt(value: &str) -> Option<String> {
256    let trimmed = normalize_url(value);
257    if trimmed.is_empty() {
258        None
259    } else {
260        Some(trimmed)
261    }
262}
263
264pub fn is_local_proxy_url(value: &str) -> bool {
265    let n = normalize_url(value);
266    n.starts_with("http://127.0.0.1:")
267        || n.starts_with("http://localhost:")
268        || n.starts_with("http://[::1]:")
269}
270
271fn default_buddy_enabled() -> bool {
272    true
273}
274
275fn deserialize_tee_mode<'de, D>(deserializer: D) -> Result<TeeMode, D::Error>
276where
277    D: serde::Deserializer<'de>,
278{
279    use serde::de::Error;
280    let v = serde_json::Value::deserialize(deserializer)?;
281    match &v {
282        serde_json::Value::Bool(true) => Ok(TeeMode::Failures),
283        serde_json::Value::Bool(false) => Ok(TeeMode::Never),
284        serde_json::Value::String(s) => match s.as_str() {
285            "never" => Ok(TeeMode::Never),
286            "failures" => Ok(TeeMode::Failures),
287            "always" => Ok(TeeMode::Always),
288            other => Err(D::Error::custom(format!("unknown tee_mode: {other}"))),
289        },
290        _ => Err(D::Error::custom("tee_mode must be string or bool")),
291    }
292}
293
294fn default_theme() -> String {
295    "default".to_string()
296}
297
298/// Controls autonomous background behaviors (preload, dedup, consolidation).
299#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(default)]
301pub struct AutonomyConfig {
302    pub enabled: bool,
303    pub auto_preload: bool,
304    pub auto_dedup: bool,
305    pub auto_related: bool,
306    pub auto_consolidate: bool,
307    pub silent_preload: bool,
308    pub dedup_threshold: usize,
309    pub consolidate_every_calls: u32,
310    pub consolidate_cooldown_secs: u64,
311}
312
313impl Default for AutonomyConfig {
314    fn default() -> Self {
315        Self {
316            enabled: true,
317            auto_preload: true,
318            auto_dedup: true,
319            auto_related: true,
320            auto_consolidate: true,
321            silent_preload: true,
322            dedup_threshold: 8,
323            consolidate_every_calls: 25,
324            consolidate_cooldown_secs: 120,
325        }
326    }
327}
328
329impl AutonomyConfig {
330    /// Creates an autonomy config from env vars, falling back to defaults.
331    pub fn from_env() -> Self {
332        let mut cfg = Self::default();
333        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY") {
334            if v == "false" || v == "0" {
335                cfg.enabled = false;
336            }
337        }
338        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
339            cfg.auto_preload = v != "false" && v != "0";
340        }
341        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
342            cfg.auto_dedup = v != "false" && v != "0";
343        }
344        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
345            cfg.auto_related = v != "false" && v != "0";
346        }
347        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
348            cfg.auto_consolidate = v != "false" && v != "0";
349        }
350        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
351            cfg.silent_preload = v != "false" && v != "0";
352        }
353        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD") {
354            if let Ok(n) = v.parse() {
355                cfg.dedup_threshold = n;
356            }
357        }
358        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS") {
359            if let Ok(n) = v.parse() {
360                cfg.consolidate_every_calls = n;
361            }
362        }
363        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS") {
364            if let Ok(n) = v.parse() {
365                cfg.consolidate_cooldown_secs = n;
366            }
367        }
368        cfg
369    }
370
371    /// Loads autonomy config from disk, with env var overrides applied.
372    pub fn load() -> Self {
373        let file_cfg = Config::load().autonomy;
374        let mut cfg = file_cfg;
375        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY") {
376            if v == "false" || v == "0" {
377                cfg.enabled = false;
378            }
379        }
380        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
381            cfg.auto_preload = v != "false" && v != "0";
382        }
383        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
384            cfg.auto_dedup = v != "false" && v != "0";
385        }
386        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
387            cfg.auto_related = v != "false" && v != "0";
388        }
389        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
390            cfg.silent_preload = v != "false" && v != "0";
391        }
392        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD") {
393            if let Ok(n) = v.parse() {
394                cfg.dedup_threshold = n;
395            }
396        }
397        cfg
398    }
399}
400
401/// Cloud sync and contribution settings (pattern sharing, model pulls).
402#[derive(Debug, Clone, Serialize, Deserialize, Default)]
403#[serde(default)]
404pub struct CloudConfig {
405    pub contribute_enabled: bool,
406    pub last_contribute: Option<String>,
407    pub last_sync: Option<String>,
408    pub last_gain_sync: Option<String>,
409    pub last_model_pull: Option<String>,
410}
411
412/// A user-defined command alias mapping for shell compression patterns.
413#[derive(Debug, Clone, Serialize, Deserialize)]
414pub struct AliasEntry {
415    pub command: String,
416    pub alias: String,
417}
418
419/// Thresholds for detecting and throttling repetitive agent tool call loops.
420#[derive(Debug, Clone, Serialize, Deserialize)]
421#[serde(default)]
422pub struct LoopDetectionConfig {
423    pub normal_threshold: u32,
424    pub reduced_threshold: u32,
425    pub blocked_threshold: u32,
426    pub window_secs: u64,
427    pub search_group_limit: u32,
428}
429
430impl Default for LoopDetectionConfig {
431    fn default() -> Self {
432        Self {
433            normal_threshold: 2,
434            reduced_threshold: 4,
435            // 0 = blocking disabled (LeanCTX philosophy: always help, never block)
436            // Set to 6+ in config to enable blocking for strict governance
437            blocked_threshold: 0,
438            window_secs: 300,
439            search_group_limit: 10,
440        }
441    }
442}
443
444impl Default for Config {
445    fn default() -> Self {
446        Self {
447            ultra_compact: false,
448            tee_mode: TeeMode::default(),
449            output_density: OutputDensity::default(),
450            checkpoint_interval: 15,
451            excluded_commands: Vec::new(),
452            passthrough_urls: Vec::new(),
453            custom_aliases: Vec::new(),
454            slow_command_threshold_ms: 5000,
455            theme: default_theme(),
456            cloud: CloudConfig::default(),
457            autonomy: AutonomyConfig::default(),
458            proxy: ProxyConfig::default(),
459            buddy_enabled: default_buddy_enabled(),
460            redirect_exclude: Vec::new(),
461            disabled_tools: Vec::new(),
462            loop_detection: LoopDetectionConfig::default(),
463            rules_scope: None,
464            extra_ignore_patterns: Vec::new(),
465            terse_agent: TerseAgent::default(),
466            archive: ArchiveConfig::default(),
467            memory: MemoryPolicy::default(),
468            allow_paths: Vec::new(),
469            content_defined_chunking: false,
470            minimal_overhead: false,
471            shell_hook_disabled: false,
472            update_check_disabled: false,
473        }
474    }
475}
476
477/// Where agent rule files are installed: global home dir, project-local, or both.
478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
479pub enum RulesScope {
480    Both,
481    Global,
482    Project,
483}
484
485impl Config {
486    /// Returns the effective rules scope, preferring env var over config file.
487    pub fn rules_scope_effective(&self) -> RulesScope {
488        let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
489            .ok()
490            .or_else(|| self.rules_scope.clone())
491            .unwrap_or_default();
492        match raw.trim().to_lowercase().as_str() {
493            "global" => RulesScope::Global,
494            "project" => RulesScope::Project,
495            _ => RulesScope::Both,
496        }
497    }
498
499    fn parse_disabled_tools_env(val: &str) -> Vec<String> {
500        val.split(',')
501            .map(|s| s.trim().to_string())
502            .filter(|s| !s.is_empty())
503            .collect()
504    }
505
506    /// Returns the effective disabled tools list, preferring env var over config file.
507    pub fn disabled_tools_effective(&self) -> Vec<String> {
508        if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
509            Self::parse_disabled_tools_env(&val)
510        } else {
511            self.disabled_tools.clone()
512        }
513    }
514
515    /// Returns `true` if minimal overhead is enabled via env var or config.
516    pub fn minimal_overhead_effective(&self) -> bool {
517        std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
518    }
519
520    /// Returns `true` if minimal overhead should be enabled for this MCP client.
521    ///
522    /// This is a superset of `minimal_overhead_effective()`:
523    /// - `LEAN_CTX_OVERHEAD_MODE=minimal` forces minimal overhead
524    /// - `LEAN_CTX_OVERHEAD_MODE=full` disables client/model heuristics (still honors LEAN_CTX_MINIMAL / config)
525    /// - In auto mode (default), certain low-context clients/models are treated as minimal to prevent
526    ///   large metadata blocks from destabilizing smaller context windows (e.g. Hermes + MiniMax).
527    pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool {
528        if let Ok(raw) = std::env::var("LEAN_CTX_OVERHEAD_MODE") {
529            match raw.trim().to_lowercase().as_str() {
530                "minimal" => return true,
531                "full" => return self.minimal_overhead_effective(),
532                _ => {}
533            }
534        }
535
536        if self.minimal_overhead_effective() {
537            return true;
538        }
539
540        let client_lower = client_name.trim().to_lowercase();
541        if !client_lower.is_empty() {
542            if let Ok(list) = std::env::var("LEAN_CTX_MINIMAL_CLIENTS") {
543                for needle in list.split(',').map(|s| s.trim().to_lowercase()) {
544                    if !needle.is_empty() && client_lower.contains(&needle) {
545                        return true;
546                    }
547                }
548            } else if client_lower.contains("hermes") || client_lower.contains("minimax") {
549                return true;
550            }
551        }
552
553        let model = std::env::var("LEAN_CTX_MODEL")
554            .or_else(|_| std::env::var("LCTX_MODEL"))
555            .unwrap_or_default();
556        let model = model.trim().to_lowercase();
557        if !model.is_empty() {
558            let m = model.replace(['_', ' '], "-");
559            if m.contains("minimax")
560                || m.contains("mini-max")
561                || m.contains("m2.7")
562                || m.contains("m2-7")
563            {
564                return true;
565            }
566        }
567
568        false
569    }
570
571    /// Returns `true` if shell hook injection is disabled via env var or config.
572    pub fn shell_hook_disabled_effective(&self) -> bool {
573        std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
574    }
575
576    /// Returns `true` if the daily update check is disabled via env var or config.
577    pub fn update_check_disabled_effective(&self) -> bool {
578        std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
579    }
580
581    pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
582        let mut policy = self.memory.clone();
583        policy.apply_env_overrides();
584        policy.validate()?;
585        Ok(policy)
586    }
587}
588
589#[cfg(test)]
590mod disabled_tools_tests {
591    use super::*;
592
593    #[test]
594    fn config_field_default_is_empty() {
595        let cfg = Config::default();
596        assert!(cfg.disabled_tools.is_empty());
597    }
598
599    #[test]
600    fn effective_returns_config_field_when_no_env_var() {
601        // Only meaningful when LEAN_CTX_DISABLED_TOOLS is unset; skip otherwise.
602        if std::env::var("LEAN_CTX_DISABLED_TOOLS").is_ok() {
603            return;
604        }
605        let cfg = Config {
606            disabled_tools: vec!["ctx_graph".to_string(), "ctx_agent".to_string()],
607            ..Default::default()
608        };
609        assert_eq!(
610            cfg.disabled_tools_effective(),
611            vec!["ctx_graph", "ctx_agent"]
612        );
613    }
614
615    #[test]
616    fn parse_env_basic() {
617        let result = Config::parse_disabled_tools_env("ctx_graph,ctx_agent");
618        assert_eq!(result, vec!["ctx_graph", "ctx_agent"]);
619    }
620
621    #[test]
622    fn parse_env_trims_whitespace_and_skips_empty() {
623        let result = Config::parse_disabled_tools_env(" ctx_graph , , ctx_agent ");
624        assert_eq!(result, vec!["ctx_graph", "ctx_agent"]);
625    }
626
627    #[test]
628    fn parse_env_single_entry() {
629        let result = Config::parse_disabled_tools_env("ctx_graph");
630        assert_eq!(result, vec!["ctx_graph"]);
631    }
632
633    #[test]
634    fn parse_env_empty_string_returns_empty() {
635        let result = Config::parse_disabled_tools_env("");
636        assert!(result.is_empty());
637    }
638
639    #[test]
640    fn disabled_tools_deserialization_defaults_to_empty() {
641        let cfg: Config = toml::from_str("").unwrap();
642        assert!(cfg.disabled_tools.is_empty());
643    }
644
645    #[test]
646    fn disabled_tools_deserialization_from_toml() {
647        let cfg: Config = toml::from_str(r#"disabled_tools = ["ctx_graph", "ctx_agent"]"#).unwrap();
648        assert_eq!(cfg.disabled_tools, vec!["ctx_graph", "ctx_agent"]);
649    }
650}
651
652#[cfg(test)]
653mod rules_scope_tests {
654    use super::*;
655
656    #[test]
657    fn default_is_both() {
658        let cfg = Config::default();
659        assert_eq!(cfg.rules_scope_effective(), RulesScope::Both);
660    }
661
662    #[test]
663    fn config_global() {
664        let cfg = Config {
665            rules_scope: Some("global".to_string()),
666            ..Default::default()
667        };
668        assert_eq!(cfg.rules_scope_effective(), RulesScope::Global);
669    }
670
671    #[test]
672    fn config_project() {
673        let cfg = Config {
674            rules_scope: Some("project".to_string()),
675            ..Default::default()
676        };
677        assert_eq!(cfg.rules_scope_effective(), RulesScope::Project);
678    }
679
680    #[test]
681    fn unknown_value_falls_back_to_both() {
682        let cfg = Config {
683            rules_scope: Some("nonsense".to_string()),
684            ..Default::default()
685        };
686        assert_eq!(cfg.rules_scope_effective(), RulesScope::Both);
687    }
688
689    #[test]
690    fn deserialization_none_by_default() {
691        let cfg: Config = toml::from_str("").unwrap();
692        assert!(cfg.rules_scope.is_none());
693        assert_eq!(cfg.rules_scope_effective(), RulesScope::Both);
694    }
695
696    #[test]
697    fn deserialization_from_toml() {
698        let cfg: Config = toml::from_str(r#"rules_scope = "project""#).unwrap();
699        assert_eq!(cfg.rules_scope.as_deref(), Some("project"));
700        assert_eq!(cfg.rules_scope_effective(), RulesScope::Project);
701    }
702}
703
704#[cfg(test)]
705mod loop_detection_config_tests {
706    use super::*;
707
708    #[test]
709    fn defaults_are_reasonable() {
710        let cfg = LoopDetectionConfig::default();
711        assert_eq!(cfg.normal_threshold, 2);
712        assert_eq!(cfg.reduced_threshold, 4);
713        // 0 = blocking disabled by default (LeanCTX philosophy: always help, never block)
714        assert_eq!(cfg.blocked_threshold, 0);
715        assert_eq!(cfg.window_secs, 300);
716        assert_eq!(cfg.search_group_limit, 10);
717    }
718
719    #[test]
720    fn deserialization_defaults_when_missing() {
721        let cfg: Config = toml::from_str("").unwrap();
722        // 0 = blocking disabled by default
723        assert_eq!(cfg.loop_detection.blocked_threshold, 0);
724        assert_eq!(cfg.loop_detection.search_group_limit, 10);
725    }
726
727    #[test]
728    fn deserialization_from_toml() {
729        let cfg: Config = toml::from_str(
730            r"
731            [loop_detection]
732            normal_threshold = 1
733            reduced_threshold = 3
734            blocked_threshold = 5
735            window_secs = 120
736            search_group_limit = 8
737            ",
738        )
739        .unwrap();
740        assert_eq!(cfg.loop_detection.normal_threshold, 1);
741        assert_eq!(cfg.loop_detection.reduced_threshold, 3);
742        assert_eq!(cfg.loop_detection.blocked_threshold, 5);
743        assert_eq!(cfg.loop_detection.window_secs, 120);
744        assert_eq!(cfg.loop_detection.search_group_limit, 8);
745    }
746
747    #[test]
748    fn partial_override_keeps_defaults() {
749        let cfg: Config = toml::from_str(
750            r"
751            [loop_detection]
752            blocked_threshold = 10
753            ",
754        )
755        .unwrap();
756        assert_eq!(cfg.loop_detection.blocked_threshold, 10);
757        assert_eq!(cfg.loop_detection.normal_threshold, 2);
758        assert_eq!(cfg.loop_detection.search_group_limit, 10);
759    }
760}
761
762impl Config {
763    /// Returns the path to the global config file (`~/.lean-ctx/config.toml`).
764    pub fn path() -> Option<PathBuf> {
765        crate::core::data_dir::lean_ctx_data_dir()
766            .ok()
767            .map(|d| d.join("config.toml"))
768    }
769
770    /// Returns the path to the project-local config override file.
771    pub fn local_path(project_root: &str) -> PathBuf {
772        PathBuf::from(project_root).join(".lean-ctx.toml")
773    }
774
775    fn find_project_root() -> Option<String> {
776        let cwd = std::env::current_dir().ok();
777
778        if let Some(root) =
779            crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
780        {
781            let root_path = std::path::Path::new(&root);
782            let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
783            let has_marker = root_path.join(".git").exists()
784                || root_path.join("Cargo.toml").exists()
785                || root_path.join("package.json").exists()
786                || root_path.join("go.mod").exists()
787                || root_path.join("pyproject.toml").exists()
788                || root_path.join(".lean-ctx.toml").exists();
789
790            if cwd_is_under_root || has_marker {
791                return Some(root);
792            }
793        }
794
795        if let Some(ref cwd) = cwd {
796            let git_root = std::process::Command::new("git")
797                .args(["rev-parse", "--show-toplevel"])
798                .current_dir(cwd)
799                .stdout(std::process::Stdio::piped())
800                .stderr(std::process::Stdio::null())
801                .output()
802                .ok()
803                .and_then(|o| {
804                    if o.status.success() {
805                        String::from_utf8(o.stdout)
806                            .ok()
807                            .map(|s| s.trim().to_string())
808                    } else {
809                        None
810                    }
811                });
812            if let Some(root) = git_root {
813                return Some(root);
814            }
815            return Some(cwd.to_string_lossy().to_string());
816        }
817        None
818    }
819
820    /// Loads config from disk with caching, merging global + project-local overrides.
821    pub fn load() -> Self {
822        static CACHE: Mutex<Option<(Config, SystemTime, Option<SystemTime>)>> = Mutex::new(None);
823
824        let Some(path) = Self::path() else {
825            return Self::default();
826        };
827
828        let local_path = Self::find_project_root().map(|r| Self::local_path(&r));
829
830        let mtime = std::fs::metadata(&path)
831            .and_then(|m| m.modified())
832            .unwrap_or(SystemTime::UNIX_EPOCH);
833
834        let local_mtime = local_path
835            .as_ref()
836            .and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok());
837
838        if let Ok(guard) = CACHE.lock() {
839            if let Some((ref cfg, ref cached_mtime, ref cached_local_mtime)) = *guard {
840                if *cached_mtime == mtime && *cached_local_mtime == local_mtime {
841                    return cfg.clone();
842                }
843            }
844        }
845
846        let mut cfg: Config = match std::fs::read_to_string(&path) {
847            Ok(content) => toml::from_str(&content).unwrap_or_default(),
848            Err(_) => Self::default(),
849        };
850
851        if let Some(ref lp) = local_path {
852            if let Ok(local_content) = std::fs::read_to_string(lp) {
853                cfg.merge_local(&local_content);
854            }
855        }
856
857        if let Ok(mut guard) = CACHE.lock() {
858            *guard = Some((cfg.clone(), mtime, local_mtime));
859        }
860
861        cfg
862    }
863
864    fn merge_local(&mut self, local_toml: &str) {
865        let local: Config = match toml::from_str(local_toml) {
866            Ok(c) => c,
867            Err(_) => return,
868        };
869        if local.ultra_compact {
870            self.ultra_compact = true;
871        }
872        if local.tee_mode != TeeMode::default() {
873            self.tee_mode = local.tee_mode;
874        }
875        if local.output_density != OutputDensity::default() {
876            self.output_density = local.output_density;
877        }
878        if local.checkpoint_interval != 15 {
879            self.checkpoint_interval = local.checkpoint_interval;
880        }
881        if !local.excluded_commands.is_empty() {
882            self.excluded_commands.extend(local.excluded_commands);
883        }
884        if !local.passthrough_urls.is_empty() {
885            self.passthrough_urls.extend(local.passthrough_urls);
886        }
887        if !local.custom_aliases.is_empty() {
888            self.custom_aliases.extend(local.custom_aliases);
889        }
890        if local.slow_command_threshold_ms != 5000 {
891            self.slow_command_threshold_ms = local.slow_command_threshold_ms;
892        }
893        if local.theme != "default" {
894            self.theme = local.theme;
895        }
896        if !local.buddy_enabled {
897            self.buddy_enabled = false;
898        }
899        if !local.redirect_exclude.is_empty() {
900            self.redirect_exclude.extend(local.redirect_exclude);
901        }
902        if !local.disabled_tools.is_empty() {
903            self.disabled_tools.extend(local.disabled_tools);
904        }
905        if !local.extra_ignore_patterns.is_empty() {
906            self.extra_ignore_patterns
907                .extend(local.extra_ignore_patterns);
908        }
909        if local.rules_scope.is_some() {
910            self.rules_scope = local.rules_scope;
911        }
912        if local.proxy.anthropic_upstream.is_some() {
913            self.proxy.anthropic_upstream = local.proxy.anthropic_upstream;
914        }
915        if local.proxy.openai_upstream.is_some() {
916            self.proxy.openai_upstream = local.proxy.openai_upstream;
917        }
918        if local.proxy.gemini_upstream.is_some() {
919            self.proxy.gemini_upstream = local.proxy.gemini_upstream;
920        }
921        if !local.autonomy.enabled {
922            self.autonomy.enabled = false;
923        }
924        if !local.autonomy.auto_preload {
925            self.autonomy.auto_preload = false;
926        }
927        if !local.autonomy.auto_dedup {
928            self.autonomy.auto_dedup = false;
929        }
930        if !local.autonomy.auto_related {
931            self.autonomy.auto_related = false;
932        }
933        if !local.autonomy.auto_consolidate {
934            self.autonomy.auto_consolidate = false;
935        }
936        if local.autonomy.silent_preload {
937            self.autonomy.silent_preload = true;
938        }
939        if !local.autonomy.silent_preload && self.autonomy.silent_preload {
940            self.autonomy.silent_preload = false;
941        }
942        if local.autonomy.dedup_threshold != AutonomyConfig::default().dedup_threshold {
943            self.autonomy.dedup_threshold = local.autonomy.dedup_threshold;
944        }
945        if local.autonomy.consolidate_every_calls
946            != AutonomyConfig::default().consolidate_every_calls
947        {
948            self.autonomy.consolidate_every_calls = local.autonomy.consolidate_every_calls;
949        }
950        if local.autonomy.consolidate_cooldown_secs
951            != AutonomyConfig::default().consolidate_cooldown_secs
952        {
953            self.autonomy.consolidate_cooldown_secs = local.autonomy.consolidate_cooldown_secs;
954        }
955        if local.terse_agent != TerseAgent::default() {
956            self.terse_agent = local.terse_agent;
957        }
958        if !local.archive.enabled {
959            self.archive.enabled = false;
960        }
961        if local.archive.threshold_chars != ArchiveConfig::default().threshold_chars {
962            self.archive.threshold_chars = local.archive.threshold_chars;
963        }
964        if local.archive.max_age_hours != ArchiveConfig::default().max_age_hours {
965            self.archive.max_age_hours = local.archive.max_age_hours;
966        }
967        if local.archive.max_disk_mb != ArchiveConfig::default().max_disk_mb {
968            self.archive.max_disk_mb = local.archive.max_disk_mb;
969        }
970        let mem_def = MemoryPolicy::default();
971        if local.memory.knowledge.max_facts != mem_def.knowledge.max_facts {
972            self.memory.knowledge.max_facts = local.memory.knowledge.max_facts;
973        }
974        if local.memory.knowledge.max_patterns != mem_def.knowledge.max_patterns {
975            self.memory.knowledge.max_patterns = local.memory.knowledge.max_patterns;
976        }
977        if local.memory.knowledge.max_history != mem_def.knowledge.max_history {
978            self.memory.knowledge.max_history = local.memory.knowledge.max_history;
979        }
980        if local.memory.knowledge.contradiction_threshold
981            != mem_def.knowledge.contradiction_threshold
982        {
983            self.memory.knowledge.contradiction_threshold =
984                local.memory.knowledge.contradiction_threshold;
985        }
986
987        if local.memory.episodic.max_episodes != mem_def.episodic.max_episodes {
988            self.memory.episodic.max_episodes = local.memory.episodic.max_episodes;
989        }
990        if local.memory.episodic.max_actions_per_episode != mem_def.episodic.max_actions_per_episode
991        {
992            self.memory.episodic.max_actions_per_episode =
993                local.memory.episodic.max_actions_per_episode;
994        }
995        if local.memory.episodic.summary_max_chars != mem_def.episodic.summary_max_chars {
996            self.memory.episodic.summary_max_chars = local.memory.episodic.summary_max_chars;
997        }
998
999        if local.memory.procedural.min_repetitions != mem_def.procedural.min_repetitions {
1000            self.memory.procedural.min_repetitions = local.memory.procedural.min_repetitions;
1001        }
1002        if local.memory.procedural.min_sequence_len != mem_def.procedural.min_sequence_len {
1003            self.memory.procedural.min_sequence_len = local.memory.procedural.min_sequence_len;
1004        }
1005        if local.memory.procedural.max_procedures != mem_def.procedural.max_procedures {
1006            self.memory.procedural.max_procedures = local.memory.procedural.max_procedures;
1007        }
1008        if local.memory.procedural.max_window_size != mem_def.procedural.max_window_size {
1009            self.memory.procedural.max_window_size = local.memory.procedural.max_window_size;
1010        }
1011
1012        if local.memory.lifecycle.decay_rate != mem_def.lifecycle.decay_rate {
1013            self.memory.lifecycle.decay_rate = local.memory.lifecycle.decay_rate;
1014        }
1015        if local.memory.lifecycle.low_confidence_threshold
1016            != mem_def.lifecycle.low_confidence_threshold
1017        {
1018            self.memory.lifecycle.low_confidence_threshold =
1019                local.memory.lifecycle.low_confidence_threshold;
1020        }
1021        if local.memory.lifecycle.stale_days != mem_def.lifecycle.stale_days {
1022            self.memory.lifecycle.stale_days = local.memory.lifecycle.stale_days;
1023        }
1024        if local.memory.lifecycle.similarity_threshold != mem_def.lifecycle.similarity_threshold {
1025            self.memory.lifecycle.similarity_threshold =
1026                local.memory.lifecycle.similarity_threshold;
1027        }
1028
1029        if local.memory.embeddings.max_facts != mem_def.embeddings.max_facts {
1030            self.memory.embeddings.max_facts = local.memory.embeddings.max_facts;
1031        }
1032        if !local.allow_paths.is_empty() {
1033            self.allow_paths.extend(local.allow_paths);
1034        }
1035        if local.minimal_overhead {
1036            self.minimal_overhead = true;
1037        }
1038        if local.shell_hook_disabled {
1039            self.shell_hook_disabled = true;
1040        }
1041    }
1042
1043    /// Persists the current config to the global config file.
1044    pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
1045        let path = Self::path().ok_or_else(|| {
1046            super::error::LeanCtxError::Config("cannot determine home directory".into())
1047        })?;
1048        if let Some(parent) = path.parent() {
1049            std::fs::create_dir_all(parent)?;
1050        }
1051        let content = toml::to_string_pretty(self)
1052            .map_err(|e| super::error::LeanCtxError::Config(e.to_string()))?;
1053        std::fs::write(&path, content)?;
1054        Ok(())
1055    }
1056
1057    /// Formats the current config as a human-readable string with file paths.
1058    pub fn show(&self) -> String {
1059        let global_path = Self::path().map_or_else(
1060            || "~/.lean-ctx/config.toml".to_string(),
1061            |p| p.to_string_lossy().to_string(),
1062        );
1063        let content = toml::to_string_pretty(self).unwrap_or_default();
1064        let mut out = format!("Global config: {global_path}\n\n{content}");
1065
1066        if let Some(root) = Self::find_project_root() {
1067            let local = Self::local_path(&root);
1068            if local.exists() {
1069                out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
1070            } else {
1071                out.push_str(&format!(
1072                    "\n\nLocal config: not found (create {} to override per-project)\n",
1073                    local.display()
1074                ));
1075            }
1076        }
1077        out
1078    }
1079}