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
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 = "default_buddy_enabled")]
132    pub buddy_enabled: bool,
133    #[serde(default)]
134    pub redirect_exclude: Vec<String>,
135    /// Tools to exclude from the MCP tool list returned by list_tools.
136    /// Accepts exact tool names (e.g. `["ctx_graph", "ctx_agent"]`).
137    /// Empty by default — all tools listed, no behaviour change.
138    #[serde(default)]
139    pub disabled_tools: Vec<String>,
140    #[serde(default)]
141    pub loop_detection: LoopDetectionConfig,
142    /// Controls where lean-ctx installs agent rule files.
143    /// Values: "both" (default), "global" (home-dir only), "project" (repo-local only).
144    /// Override via LEAN_CTX_RULES_SCOPE env var.
145    #[serde(default)]
146    pub rules_scope: Option<String>,
147    /// Extra glob patterns to ignore in graph/overview/preload (repo-local).
148    /// Example: `["externals/**", "target/**", "temp/**"]`
149    #[serde(default)]
150    pub extra_ignore_patterns: Vec<String>,
151    /// Controls agent output verbosity via instructions injection.
152    /// Values: "off" (default), "lite", "full", "ultra".
153    /// Override via LEAN_CTX_TERSE_AGENT env var.
154    #[serde(default)]
155    pub terse_agent: TerseAgent,
156    /// Archive configuration for zero-loss compression.
157    #[serde(default)]
158    pub archive: ArchiveConfig,
159    /// Memory policy (knowledge/episodic/procedural/lifecycle budgets & thresholds).
160    #[serde(default)]
161    pub memory: MemoryPolicy,
162    /// Additional paths allowed by PathJail (absolute).
163    /// Useful for multi-project workspaces where the jail root is a parent directory.
164    /// Override via LEAN_CTX_ALLOW_PATH env var (path-list separator).
165    #[serde(default)]
166    pub allow_paths: Vec<String>,
167    /// Enable content-defined chunking (Rabin-Karp) for cache-optimal output ordering.
168    /// Stable chunks are emitted first to maximize prompt cache hits.
169    #[serde(default)]
170    pub content_defined_chunking: bool,
171    /// Skip session/knowledge/gotcha blocks in MCP instructions to minimize token overhead.
172    /// Override via LEAN_CTX_MINIMAL env var.
173    #[serde(default)]
174    pub minimal_overhead: bool,
175    /// Disable shell hook injection (the _lc() function that wraps CLI commands).
176    /// Override via LEAN_CTX_NO_HOOK env var.
177    #[serde(default)]
178    pub shell_hook_disabled: bool,
179    /// Disable the daily version check against leanctx.com/version.txt.
180    /// Override via LEAN_CTX_NO_UPDATE_CHECK env var.
181    #[serde(default)]
182    pub update_check_disabled: bool,
183}
184
185/// Settings for the zero-loss compression archive (large tool outputs saved to disk).
186#[derive(Debug, Clone, Serialize, Deserialize)]
187#[serde(default)]
188pub struct ArchiveConfig {
189    pub enabled: bool,
190    pub threshold_chars: usize,
191    pub max_age_hours: u64,
192    pub max_disk_mb: u64,
193}
194
195impl Default for ArchiveConfig {
196    fn default() -> Self {
197        Self {
198            enabled: true,
199            threshold_chars: 4096,
200            max_age_hours: 48,
201            max_disk_mb: 500,
202        }
203    }
204}
205
206fn default_buddy_enabled() -> bool {
207    true
208}
209
210fn deserialize_tee_mode<'de, D>(deserializer: D) -> Result<TeeMode, D::Error>
211where
212    D: serde::Deserializer<'de>,
213{
214    use serde::de::Error;
215    let v = serde_json::Value::deserialize(deserializer)?;
216    match &v {
217        serde_json::Value::Bool(true) => Ok(TeeMode::Failures),
218        serde_json::Value::Bool(false) => Ok(TeeMode::Never),
219        serde_json::Value::String(s) => match s.as_str() {
220            "never" => Ok(TeeMode::Never),
221            "failures" => Ok(TeeMode::Failures),
222            "always" => Ok(TeeMode::Always),
223            other => Err(D::Error::custom(format!("unknown tee_mode: {other}"))),
224        },
225        _ => Err(D::Error::custom("tee_mode must be string or bool")),
226    }
227}
228
229fn default_theme() -> String {
230    "default".to_string()
231}
232
233/// Controls autonomous background behaviors (preload, dedup, consolidation).
234#[derive(Debug, Clone, Serialize, Deserialize)]
235#[serde(default)]
236pub struct AutonomyConfig {
237    pub enabled: bool,
238    pub auto_preload: bool,
239    pub auto_dedup: bool,
240    pub auto_related: bool,
241    pub auto_consolidate: bool,
242    pub silent_preload: bool,
243    pub dedup_threshold: usize,
244    pub consolidate_every_calls: u32,
245    pub consolidate_cooldown_secs: u64,
246}
247
248impl Default for AutonomyConfig {
249    fn default() -> Self {
250        Self {
251            enabled: true,
252            auto_preload: true,
253            auto_dedup: true,
254            auto_related: true,
255            auto_consolidate: true,
256            silent_preload: true,
257            dedup_threshold: 8,
258            consolidate_every_calls: 25,
259            consolidate_cooldown_secs: 120,
260        }
261    }
262}
263
264impl AutonomyConfig {
265    /// Creates an autonomy config from env vars, falling back to defaults.
266    pub fn from_env() -> Self {
267        let mut cfg = Self::default();
268        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY") {
269            if v == "false" || v == "0" {
270                cfg.enabled = false;
271            }
272        }
273        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
274            cfg.auto_preload = v != "false" && v != "0";
275        }
276        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
277            cfg.auto_dedup = v != "false" && v != "0";
278        }
279        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
280            cfg.auto_related = v != "false" && v != "0";
281        }
282        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
283            cfg.auto_consolidate = v != "false" && v != "0";
284        }
285        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
286            cfg.silent_preload = v != "false" && v != "0";
287        }
288        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD") {
289            if let Ok(n) = v.parse() {
290                cfg.dedup_threshold = n;
291            }
292        }
293        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS") {
294            if let Ok(n) = v.parse() {
295                cfg.consolidate_every_calls = n;
296            }
297        }
298        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS") {
299            if let Ok(n) = v.parse() {
300                cfg.consolidate_cooldown_secs = n;
301            }
302        }
303        cfg
304    }
305
306    /// Loads autonomy config from disk, with env var overrides applied.
307    pub fn load() -> Self {
308        let file_cfg = Config::load().autonomy;
309        let mut cfg = file_cfg;
310        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY") {
311            if v == "false" || v == "0" {
312                cfg.enabled = false;
313            }
314        }
315        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
316            cfg.auto_preload = v != "false" && v != "0";
317        }
318        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
319            cfg.auto_dedup = v != "false" && v != "0";
320        }
321        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
322            cfg.auto_related = v != "false" && v != "0";
323        }
324        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
325            cfg.silent_preload = v != "false" && v != "0";
326        }
327        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD") {
328            if let Ok(n) = v.parse() {
329                cfg.dedup_threshold = n;
330            }
331        }
332        cfg
333    }
334}
335
336/// Cloud sync and contribution settings (pattern sharing, model pulls).
337#[derive(Debug, Clone, Serialize, Deserialize, Default)]
338#[serde(default)]
339pub struct CloudConfig {
340    pub contribute_enabled: bool,
341    pub last_contribute: Option<String>,
342    pub last_sync: Option<String>,
343    pub last_gain_sync: Option<String>,
344    pub last_model_pull: Option<String>,
345}
346
347/// A user-defined command alias mapping for shell compression patterns.
348#[derive(Debug, Clone, Serialize, Deserialize)]
349pub struct AliasEntry {
350    pub command: String,
351    pub alias: String,
352}
353
354/// Thresholds for detecting and throttling repetitive agent tool call loops.
355#[derive(Debug, Clone, Serialize, Deserialize)]
356#[serde(default)]
357pub struct LoopDetectionConfig {
358    pub normal_threshold: u32,
359    pub reduced_threshold: u32,
360    pub blocked_threshold: u32,
361    pub window_secs: u64,
362    pub search_group_limit: u32,
363}
364
365impl Default for LoopDetectionConfig {
366    fn default() -> Self {
367        Self {
368            normal_threshold: 2,
369            reduced_threshold: 4,
370            // 0 = blocking disabled (LeanCTX philosophy: always help, never block)
371            // Set to 6+ in config to enable blocking for strict governance
372            blocked_threshold: 0,
373            window_secs: 300,
374            search_group_limit: 10,
375        }
376    }
377}
378
379impl Default for Config {
380    fn default() -> Self {
381        Self {
382            ultra_compact: false,
383            tee_mode: TeeMode::default(),
384            output_density: OutputDensity::default(),
385            checkpoint_interval: 15,
386            excluded_commands: Vec::new(),
387            passthrough_urls: Vec::new(),
388            custom_aliases: Vec::new(),
389            slow_command_threshold_ms: 5000,
390            theme: default_theme(),
391            cloud: CloudConfig::default(),
392            autonomy: AutonomyConfig::default(),
393            buddy_enabled: default_buddy_enabled(),
394            redirect_exclude: Vec::new(),
395            disabled_tools: Vec::new(),
396            loop_detection: LoopDetectionConfig::default(),
397            rules_scope: None,
398            extra_ignore_patterns: Vec::new(),
399            terse_agent: TerseAgent::default(),
400            archive: ArchiveConfig::default(),
401            memory: MemoryPolicy::default(),
402            allow_paths: Vec::new(),
403            content_defined_chunking: false,
404            minimal_overhead: false,
405            shell_hook_disabled: false,
406            update_check_disabled: false,
407        }
408    }
409}
410
411/// Where agent rule files are installed: global home dir, project-local, or both.
412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
413pub enum RulesScope {
414    Both,
415    Global,
416    Project,
417}
418
419impl Config {
420    /// Returns the effective rules scope, preferring env var over config file.
421    pub fn rules_scope_effective(&self) -> RulesScope {
422        let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
423            .ok()
424            .or_else(|| self.rules_scope.clone())
425            .unwrap_or_default();
426        match raw.trim().to_lowercase().as_str() {
427            "global" => RulesScope::Global,
428            "project" => RulesScope::Project,
429            _ => RulesScope::Both,
430        }
431    }
432
433    fn parse_disabled_tools_env(val: &str) -> Vec<String> {
434        val.split(',')
435            .map(|s| s.trim().to_string())
436            .filter(|s| !s.is_empty())
437            .collect()
438    }
439
440    /// Returns the effective disabled tools list, preferring env var over config file.
441    pub fn disabled_tools_effective(&self) -> Vec<String> {
442        if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
443            Self::parse_disabled_tools_env(&val)
444        } else {
445            self.disabled_tools.clone()
446        }
447    }
448
449    /// Returns `true` if minimal overhead is enabled via env var or config.
450    pub fn minimal_overhead_effective(&self) -> bool {
451        std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
452    }
453
454    /// Returns `true` if shell hook injection is disabled via env var or config.
455    pub fn shell_hook_disabled_effective(&self) -> bool {
456        std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
457    }
458
459    /// Returns `true` if the daily update check is disabled via env var or config.
460    pub fn update_check_disabled_effective(&self) -> bool {
461        std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
462    }
463
464    pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
465        let mut policy = self.memory.clone();
466        policy.apply_env_overrides();
467        policy.validate()?;
468        Ok(policy)
469    }
470}
471
472#[cfg(test)]
473mod disabled_tools_tests {
474    use super::*;
475
476    #[test]
477    fn config_field_default_is_empty() {
478        let cfg = Config::default();
479        assert!(cfg.disabled_tools.is_empty());
480    }
481
482    #[test]
483    fn effective_returns_config_field_when_no_env_var() {
484        // Only meaningful when LEAN_CTX_DISABLED_TOOLS is unset; skip otherwise.
485        if std::env::var("LEAN_CTX_DISABLED_TOOLS").is_ok() {
486            return;
487        }
488        let cfg = Config {
489            disabled_tools: vec!["ctx_graph".to_string(), "ctx_agent".to_string()],
490            ..Default::default()
491        };
492        assert_eq!(
493            cfg.disabled_tools_effective(),
494            vec!["ctx_graph", "ctx_agent"]
495        );
496    }
497
498    #[test]
499    fn parse_env_basic() {
500        let result = Config::parse_disabled_tools_env("ctx_graph,ctx_agent");
501        assert_eq!(result, vec!["ctx_graph", "ctx_agent"]);
502    }
503
504    #[test]
505    fn parse_env_trims_whitespace_and_skips_empty() {
506        let result = Config::parse_disabled_tools_env(" ctx_graph , , ctx_agent ");
507        assert_eq!(result, vec!["ctx_graph", "ctx_agent"]);
508    }
509
510    #[test]
511    fn parse_env_single_entry() {
512        let result = Config::parse_disabled_tools_env("ctx_graph");
513        assert_eq!(result, vec!["ctx_graph"]);
514    }
515
516    #[test]
517    fn parse_env_empty_string_returns_empty() {
518        let result = Config::parse_disabled_tools_env("");
519        assert!(result.is_empty());
520    }
521
522    #[test]
523    fn disabled_tools_deserialization_defaults_to_empty() {
524        let cfg: Config = toml::from_str("").unwrap();
525        assert!(cfg.disabled_tools.is_empty());
526    }
527
528    #[test]
529    fn disabled_tools_deserialization_from_toml() {
530        let cfg: Config = toml::from_str(r#"disabled_tools = ["ctx_graph", "ctx_agent"]"#).unwrap();
531        assert_eq!(cfg.disabled_tools, vec!["ctx_graph", "ctx_agent"]);
532    }
533}
534
535#[cfg(test)]
536mod rules_scope_tests {
537    use super::*;
538
539    #[test]
540    fn default_is_both() {
541        let cfg = Config::default();
542        assert_eq!(cfg.rules_scope_effective(), RulesScope::Both);
543    }
544
545    #[test]
546    fn config_global() {
547        let cfg = Config {
548            rules_scope: Some("global".to_string()),
549            ..Default::default()
550        };
551        assert_eq!(cfg.rules_scope_effective(), RulesScope::Global);
552    }
553
554    #[test]
555    fn config_project() {
556        let cfg = Config {
557            rules_scope: Some("project".to_string()),
558            ..Default::default()
559        };
560        assert_eq!(cfg.rules_scope_effective(), RulesScope::Project);
561    }
562
563    #[test]
564    fn unknown_value_falls_back_to_both() {
565        let cfg = Config {
566            rules_scope: Some("nonsense".to_string()),
567            ..Default::default()
568        };
569        assert_eq!(cfg.rules_scope_effective(), RulesScope::Both);
570    }
571
572    #[test]
573    fn deserialization_none_by_default() {
574        let cfg: Config = toml::from_str("").unwrap();
575        assert!(cfg.rules_scope.is_none());
576        assert_eq!(cfg.rules_scope_effective(), RulesScope::Both);
577    }
578
579    #[test]
580    fn deserialization_from_toml() {
581        let cfg: Config = toml::from_str(r#"rules_scope = "project""#).unwrap();
582        assert_eq!(cfg.rules_scope.as_deref(), Some("project"));
583        assert_eq!(cfg.rules_scope_effective(), RulesScope::Project);
584    }
585}
586
587#[cfg(test)]
588mod loop_detection_config_tests {
589    use super::*;
590
591    #[test]
592    fn defaults_are_reasonable() {
593        let cfg = LoopDetectionConfig::default();
594        assert_eq!(cfg.normal_threshold, 2);
595        assert_eq!(cfg.reduced_threshold, 4);
596        // 0 = blocking disabled by default (LeanCTX philosophy: always help, never block)
597        assert_eq!(cfg.blocked_threshold, 0);
598        assert_eq!(cfg.window_secs, 300);
599        assert_eq!(cfg.search_group_limit, 10);
600    }
601
602    #[test]
603    fn deserialization_defaults_when_missing() {
604        let cfg: Config = toml::from_str("").unwrap();
605        // 0 = blocking disabled by default
606        assert_eq!(cfg.loop_detection.blocked_threshold, 0);
607        assert_eq!(cfg.loop_detection.search_group_limit, 10);
608    }
609
610    #[test]
611    fn deserialization_from_toml() {
612        let cfg: Config = toml::from_str(
613            r"
614            [loop_detection]
615            normal_threshold = 1
616            reduced_threshold = 3
617            blocked_threshold = 5
618            window_secs = 120
619            search_group_limit = 8
620            ",
621        )
622        .unwrap();
623        assert_eq!(cfg.loop_detection.normal_threshold, 1);
624        assert_eq!(cfg.loop_detection.reduced_threshold, 3);
625        assert_eq!(cfg.loop_detection.blocked_threshold, 5);
626        assert_eq!(cfg.loop_detection.window_secs, 120);
627        assert_eq!(cfg.loop_detection.search_group_limit, 8);
628    }
629
630    #[test]
631    fn partial_override_keeps_defaults() {
632        let cfg: Config = toml::from_str(
633            r"
634            [loop_detection]
635            blocked_threshold = 10
636            ",
637        )
638        .unwrap();
639        assert_eq!(cfg.loop_detection.blocked_threshold, 10);
640        assert_eq!(cfg.loop_detection.normal_threshold, 2);
641        assert_eq!(cfg.loop_detection.search_group_limit, 10);
642    }
643}
644
645impl Config {
646    /// Returns the path to the global config file (`~/.lean-ctx/config.toml`).
647    pub fn path() -> Option<PathBuf> {
648        crate::core::data_dir::lean_ctx_data_dir()
649            .ok()
650            .map(|d| d.join("config.toml"))
651    }
652
653    /// Returns the path to the project-local config override file.
654    pub fn local_path(project_root: &str) -> PathBuf {
655        PathBuf::from(project_root).join(".lean-ctx.toml")
656    }
657
658    fn find_project_root() -> Option<String> {
659        let cwd = std::env::current_dir().ok();
660
661        if let Some(root) =
662            crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
663        {
664            let root_path = std::path::Path::new(&root);
665            let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
666            let has_marker = root_path.join(".git").exists()
667                || root_path.join("Cargo.toml").exists()
668                || root_path.join("package.json").exists()
669                || root_path.join("go.mod").exists()
670                || root_path.join("pyproject.toml").exists()
671                || root_path.join(".lean-ctx.toml").exists();
672
673            if cwd_is_under_root || has_marker {
674                return Some(root);
675            }
676        }
677
678        if let Some(ref cwd) = cwd {
679            let git_root = std::process::Command::new("git")
680                .args(["rev-parse", "--show-toplevel"])
681                .current_dir(cwd)
682                .stdout(std::process::Stdio::piped())
683                .stderr(std::process::Stdio::null())
684                .output()
685                .ok()
686                .and_then(|o| {
687                    if o.status.success() {
688                        String::from_utf8(o.stdout)
689                            .ok()
690                            .map(|s| s.trim().to_string())
691                    } else {
692                        None
693                    }
694                });
695            if let Some(root) = git_root {
696                return Some(root);
697            }
698            return Some(cwd.to_string_lossy().to_string());
699        }
700        None
701    }
702
703    /// Loads config from disk with caching, merging global + project-local overrides.
704    pub fn load() -> Self {
705        static CACHE: Mutex<Option<(Config, SystemTime, Option<SystemTime>)>> = Mutex::new(None);
706
707        let Some(path) = Self::path() else {
708            return Self::default();
709        };
710
711        let local_path = Self::find_project_root().map(|r| Self::local_path(&r));
712
713        let mtime = std::fs::metadata(&path)
714            .and_then(|m| m.modified())
715            .unwrap_or(SystemTime::UNIX_EPOCH);
716
717        let local_mtime = local_path
718            .as_ref()
719            .and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok());
720
721        if let Ok(guard) = CACHE.lock() {
722            if let Some((ref cfg, ref cached_mtime, ref cached_local_mtime)) = *guard {
723                if *cached_mtime == mtime && *cached_local_mtime == local_mtime {
724                    return cfg.clone();
725                }
726            }
727        }
728
729        let mut cfg: Config = match std::fs::read_to_string(&path) {
730            Ok(content) => toml::from_str(&content).unwrap_or_default(),
731            Err(_) => Self::default(),
732        };
733
734        if let Some(ref lp) = local_path {
735            if let Ok(local_content) = std::fs::read_to_string(lp) {
736                cfg.merge_local(&local_content);
737            }
738        }
739
740        if let Ok(mut guard) = CACHE.lock() {
741            *guard = Some((cfg.clone(), mtime, local_mtime));
742        }
743
744        cfg
745    }
746
747    fn merge_local(&mut self, local_toml: &str) {
748        let local: Config = match toml::from_str(local_toml) {
749            Ok(c) => c,
750            Err(_) => return,
751        };
752        if local.ultra_compact {
753            self.ultra_compact = true;
754        }
755        if local.tee_mode != TeeMode::default() {
756            self.tee_mode = local.tee_mode;
757        }
758        if local.output_density != OutputDensity::default() {
759            self.output_density = local.output_density;
760        }
761        if local.checkpoint_interval != 15 {
762            self.checkpoint_interval = local.checkpoint_interval;
763        }
764        if !local.excluded_commands.is_empty() {
765            self.excluded_commands.extend(local.excluded_commands);
766        }
767        if !local.passthrough_urls.is_empty() {
768            self.passthrough_urls.extend(local.passthrough_urls);
769        }
770        if !local.custom_aliases.is_empty() {
771            self.custom_aliases.extend(local.custom_aliases);
772        }
773        if local.slow_command_threshold_ms != 5000 {
774            self.slow_command_threshold_ms = local.slow_command_threshold_ms;
775        }
776        if local.theme != "default" {
777            self.theme = local.theme;
778        }
779        if !local.buddy_enabled {
780            self.buddy_enabled = false;
781        }
782        if !local.redirect_exclude.is_empty() {
783            self.redirect_exclude.extend(local.redirect_exclude);
784        }
785        if !local.disabled_tools.is_empty() {
786            self.disabled_tools.extend(local.disabled_tools);
787        }
788        if !local.extra_ignore_patterns.is_empty() {
789            self.extra_ignore_patterns
790                .extend(local.extra_ignore_patterns);
791        }
792        if local.rules_scope.is_some() {
793            self.rules_scope = local.rules_scope;
794        }
795        if !local.autonomy.enabled {
796            self.autonomy.enabled = false;
797        }
798        if !local.autonomy.auto_preload {
799            self.autonomy.auto_preload = false;
800        }
801        if !local.autonomy.auto_dedup {
802            self.autonomy.auto_dedup = false;
803        }
804        if !local.autonomy.auto_related {
805            self.autonomy.auto_related = false;
806        }
807        if !local.autonomy.auto_consolidate {
808            self.autonomy.auto_consolidate = false;
809        }
810        if local.autonomy.silent_preload {
811            self.autonomy.silent_preload = true;
812        }
813        if !local.autonomy.silent_preload && self.autonomy.silent_preload {
814            self.autonomy.silent_preload = false;
815        }
816        if local.autonomy.dedup_threshold != AutonomyConfig::default().dedup_threshold {
817            self.autonomy.dedup_threshold = local.autonomy.dedup_threshold;
818        }
819        if local.autonomy.consolidate_every_calls
820            != AutonomyConfig::default().consolidate_every_calls
821        {
822            self.autonomy.consolidate_every_calls = local.autonomy.consolidate_every_calls;
823        }
824        if local.autonomy.consolidate_cooldown_secs
825            != AutonomyConfig::default().consolidate_cooldown_secs
826        {
827            self.autonomy.consolidate_cooldown_secs = local.autonomy.consolidate_cooldown_secs;
828        }
829        if local.terse_agent != TerseAgent::default() {
830            self.terse_agent = local.terse_agent;
831        }
832        if !local.archive.enabled {
833            self.archive.enabled = false;
834        }
835        if local.archive.threshold_chars != ArchiveConfig::default().threshold_chars {
836            self.archive.threshold_chars = local.archive.threshold_chars;
837        }
838        if local.archive.max_age_hours != ArchiveConfig::default().max_age_hours {
839            self.archive.max_age_hours = local.archive.max_age_hours;
840        }
841        if local.archive.max_disk_mb != ArchiveConfig::default().max_disk_mb {
842            self.archive.max_disk_mb = local.archive.max_disk_mb;
843        }
844        let mem_def = MemoryPolicy::default();
845        if local.memory.knowledge.max_facts != mem_def.knowledge.max_facts {
846            self.memory.knowledge.max_facts = local.memory.knowledge.max_facts;
847        }
848        if local.memory.knowledge.max_patterns != mem_def.knowledge.max_patterns {
849            self.memory.knowledge.max_patterns = local.memory.knowledge.max_patterns;
850        }
851        if local.memory.knowledge.max_history != mem_def.knowledge.max_history {
852            self.memory.knowledge.max_history = local.memory.knowledge.max_history;
853        }
854        if local.memory.knowledge.contradiction_threshold
855            != mem_def.knowledge.contradiction_threshold
856        {
857            self.memory.knowledge.contradiction_threshold =
858                local.memory.knowledge.contradiction_threshold;
859        }
860
861        if local.memory.episodic.max_episodes != mem_def.episodic.max_episodes {
862            self.memory.episodic.max_episodes = local.memory.episodic.max_episodes;
863        }
864        if local.memory.episodic.max_actions_per_episode != mem_def.episodic.max_actions_per_episode
865        {
866            self.memory.episodic.max_actions_per_episode =
867                local.memory.episodic.max_actions_per_episode;
868        }
869        if local.memory.episodic.summary_max_chars != mem_def.episodic.summary_max_chars {
870            self.memory.episodic.summary_max_chars = local.memory.episodic.summary_max_chars;
871        }
872
873        if local.memory.procedural.min_repetitions != mem_def.procedural.min_repetitions {
874            self.memory.procedural.min_repetitions = local.memory.procedural.min_repetitions;
875        }
876        if local.memory.procedural.min_sequence_len != mem_def.procedural.min_sequence_len {
877            self.memory.procedural.min_sequence_len = local.memory.procedural.min_sequence_len;
878        }
879        if local.memory.procedural.max_procedures != mem_def.procedural.max_procedures {
880            self.memory.procedural.max_procedures = local.memory.procedural.max_procedures;
881        }
882        if local.memory.procedural.max_window_size != mem_def.procedural.max_window_size {
883            self.memory.procedural.max_window_size = local.memory.procedural.max_window_size;
884        }
885
886        if local.memory.lifecycle.decay_rate != mem_def.lifecycle.decay_rate {
887            self.memory.lifecycle.decay_rate = local.memory.lifecycle.decay_rate;
888        }
889        if local.memory.lifecycle.low_confidence_threshold
890            != mem_def.lifecycle.low_confidence_threshold
891        {
892            self.memory.lifecycle.low_confidence_threshold =
893                local.memory.lifecycle.low_confidence_threshold;
894        }
895        if local.memory.lifecycle.stale_days != mem_def.lifecycle.stale_days {
896            self.memory.lifecycle.stale_days = local.memory.lifecycle.stale_days;
897        }
898        if local.memory.lifecycle.similarity_threshold != mem_def.lifecycle.similarity_threshold {
899            self.memory.lifecycle.similarity_threshold =
900                local.memory.lifecycle.similarity_threshold;
901        }
902
903        if local.memory.embeddings.max_facts != mem_def.embeddings.max_facts {
904            self.memory.embeddings.max_facts = local.memory.embeddings.max_facts;
905        }
906        if !local.allow_paths.is_empty() {
907            self.allow_paths.extend(local.allow_paths);
908        }
909        if local.minimal_overhead {
910            self.minimal_overhead = true;
911        }
912        if local.shell_hook_disabled {
913            self.shell_hook_disabled = true;
914        }
915    }
916
917    /// Persists the current config to the global config file.
918    pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
919        let path = Self::path().ok_or_else(|| {
920            super::error::LeanCtxError::Config("cannot determine home directory".into())
921        })?;
922        if let Some(parent) = path.parent() {
923            std::fs::create_dir_all(parent)?;
924        }
925        let content = toml::to_string_pretty(self)
926            .map_err(|e| super::error::LeanCtxError::Config(e.to_string()))?;
927        std::fs::write(&path, content)?;
928        Ok(())
929    }
930
931    /// Formats the current config as a human-readable string with file paths.
932    pub fn show(&self) -> String {
933        let global_path = Self::path().map_or_else(
934            || "~/.lean-ctx/config.toml".to_string(),
935            |p| p.to_string_lossy().to_string(),
936        );
937        let content = toml::to_string_pretty(self).unwrap_or_default();
938        let mut out = format!("Global config: {global_path}\n\n{content}");
939
940        if let Some(root) = Self::find_project_root() {
941            let local = Self::local_path(&root);
942            if local.exists() {
943                out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
944            } else {
945                out.push_str(&format!(
946                    "\n\nLocal config: not found (create {} to override per-project)\n",
947                    local.display()
948                ));
949            }
950        }
951        out
952    }
953}