Skip to main content

lean_ctx/core/config/
loader.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Config path resolution and disk loading.
4
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7
8use super::{CognitiveMode, Config, ConfigCacheSlot, default_shell_allowlist};
9
10const CONFIG_PROFILE_ENV: &str = "LEAN_CTX_CONFIG_PROFILE";
11
12pub(super) fn environment_config_profile() -> Option<String> {
13    std::env::var(CONFIG_PROFILE_ENV)
14        .ok()
15        .map(|name| name.trim().to_string())
16        .filter(|name| !name.is_empty())
17}
18
19/// Parses a config and recursively applies one named partial overlay. An
20/// explicit selector (normally the environment) wins over `config_profile`.
21pub(super) fn parse_config_with_profile(
22    raw: &str,
23    explicit_profile: Option<&str>,
24) -> Result<Config, String> {
25    let migrated = Config::migrate_v3_compression_document(raw)?;
26    let raw = migrated.as_deref().unwrap_or(raw);
27    let mut value: toml::Value = toml::from_str(raw).map_err(|error| error.to_string())?;
28    let configured_profile = value.get("config_profile").and_then(toml::Value::as_str);
29    let selected = explicit_profile
30        .map(str::trim)
31        .filter(|name| !name.is_empty())
32        .or(configured_profile);
33
34    if let Some(name) = selected {
35        let profiles = value
36            .get("profiles")
37            .and_then(toml::Value::as_table)
38            .ok_or_else(|| format!("config profile '{name}' selected but [profiles] is missing"))?;
39        let mut overlay = profiles
40            .get(name)
41            .and_then(toml::Value::as_table)
42            .cloned()
43            .ok_or_else(|| format!("config profile '{name}' is not defined"))?;
44        if overlay.remove("profiles").is_some() || overlay.remove("config_profile").is_some() {
45            return Err(format!(
46                "config profile '{name}' cannot override reserved profile keys"
47            ));
48        }
49        merge_toml_tables(
50            value
51                .as_table_mut()
52                .expect("a TOML document always has a root table"),
53            overlay,
54        );
55    }
56
57    value.try_into().map_err(|error| error.to_string())
58}
59
60fn merge_toml_tables(base: &mut toml::Table, overlay: toml::Table) {
61    for (key, overlay_value) in overlay {
62        match (base.get_mut(&key), overlay_value) {
63            (Some(toml::Value::Table(base_table)), toml::Value::Table(overlay_table)) => {
64                merge_toml_tables(base_table, overlay_table);
65            }
66            (_, replacement) => {
67                base.insert(key, replacement);
68            }
69        }
70    }
71}
72
73/// Holds the most recent global `config.toml` parse error, if the file currently
74/// fails to parse. When that happens `Config::load()` silently falls back to the
75/// built-in defaults and only logs to stderr — which is invisible over an MCP/stdio
76/// transport. Recording it here lets callers (e.g. the shell-allowlist diagnostic
77/// and `lean-ctx doctor`) surface "you're on defaults because your config is broken".
78static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
79
80/// Returns the most recent global config parse error, or `None` if the current
81/// `config.toml` parsed successfully (or no config file exists).
82#[must_use]
83pub fn last_config_parse_error() -> Option<String> {
84    LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
85}
86
87fn record_parse_error(err: Option<String>) {
88    if let Ok(mut guard) = LAST_PARSE_ERROR.lock() {
89        *guard = err;
90    }
91}
92
93/// Reset every SECURITY-sensitive field of a parsed project-local `Config` back
94/// to its default, returning the names of the ones that actually carried an
95/// override. Used by [`Config::merge_local`] for untrusted workspaces: clearing a
96/// field to its default makes the downstream "== default ⇒ no override" merge
97/// guards skip it automatically, so a single list here gates every sensitive key
98/// without touching the per-field merge arms (security audit #4).
99///
100/// Sensitive = anything that can widen lean-ctx's own boundaries or steer the
101/// agent: the shell allowlist, path-jail roots, proxy upstreams, command
102/// aliases, network passthrough, rules scope/injection, tool surface control
103/// (profile/enabled-list/categories, disabling) and permission inheritance.
104/// Comfort/perf knobs are intentionally NOT listed.
105pub(crate) fn strip_sensitive_overrides(local: &mut Config) -> Vec<&'static str> {
106    let mut withheld: Vec<&'static str> = Vec::new();
107
108    if local.shell_allowlist != default_shell_allowlist() {
109        local.shell_allowlist = default_shell_allowlist();
110        withheld.push("shell_allowlist");
111    }
112    if !local.shell_allowlist_extra.is_empty() {
113        local.shell_allowlist_extra.clear();
114        withheld.push("shell_allowlist_extra");
115    }
116    if !local.allow_paths.is_empty() {
117        local.allow_paths.clear();
118        withheld.push("allow_paths");
119    }
120    if !local.extra_roots.is_empty() {
121        local.extra_roots.clear();
122        withheld.push("extra_roots");
123    }
124    if !local.allow_symlink_roots.is_empty() {
125        local.allow_symlink_roots.clear();
126        withheld.push("allow_symlink_roots");
127    }
128    if !local.custom_aliases.is_empty() {
129        local.custom_aliases.clear();
130        withheld.push("custom_aliases");
131    }
132    if !local.passthrough_urls.is_empty() {
133        local.passthrough_urls.clear();
134        withheld.push("passthrough_urls");
135    }
136    // Paths in `redirect_exclude` skip the native-read redirect, and with it
137    // the redaction that path applies; a cloned repo must not opt itself out.
138    if !local.redirect_exclude.is_empty() {
139        local.redirect_exclude.clear();
140        withheld.push("redirect_exclude");
141    }
142    if local.proxy.anthropic_upstream.is_some()
143        || local.proxy.openai_upstream.is_some()
144        || local.proxy.chatgpt_upstream.is_some()
145        || local.proxy.gemini_upstream.is_some()
146    {
147        local.proxy.anthropic_upstream = None;
148        local.proxy.openai_upstream = None;
149        local.proxy.chatgpt_upstream = None;
150        local.proxy.gemini_upstream = None;
151        withheld.push("proxy.*_upstream");
152    }
153    // `eager` lets background work start language servers, which execute
154    // project code (build scripts, proc macros). Lowering to off/auto is safe.
155    if local.semantic_mode == super::SemanticMode::Eager {
156        local.semantic_mode = super::SemanticMode::default();
157        withheld.push("semantic_mode");
158    }
159    if local.rules_scope.is_some() {
160        local.rules_scope = None;
161        withheld.push("rules_scope");
162    }
163    if local.rules_injection.is_some() {
164        local.rules_injection = None;
165        withheld.push("rules_injection");
166    }
167    if local.permission_inheritance.is_some() {
168        local.permission_inheritance = None;
169        withheld.push("permission_inheritance");
170    }
171    if !local.disabled_tools.is_empty() {
172        local.disabled_tools.clear();
173        withheld.push("disabled_tools");
174    }
175    if local.tool_profile.is_some() {
176        local.tool_profile = None;
177        withheld.push("tool_profile");
178    }
179    if !local.tools_enabled.is_empty() {
180        local.tools_enabled.clear();
181        withheld.push("tools_enabled");
182    }
183    if !local.default_tool_categories.is_empty() {
184        local.default_tool_categories.clear();
185        withheld.push("default_tool_categories");
186    }
187    if !local.index.respect_gitignore {
188        local.index.respect_gitignore = true;
189        withheld.push("index.respect_gitignore");
190    }
191    if !local.shell_allowlist_subcommand_scoping {
192        local.shell_allowlist_subcommand_scoping = true;
193        withheld.push("shell_allowlist_subcommand_scoping");
194    }
195
196    withheld
197}
198
199/// Names of the SECURITY-sensitive overrides a project-local `.lean-ctx.toml`
200/// carries — the keys `strip_sensitive_overrides` would withhold for an
201/// untrusted workspace. Read-only (parses a throwaway `Config`); used by
202/// `lean-ctx trust` to tell the user exactly what trusting will enable.
203#[must_use]
204pub fn local_sensitive_overrides(local_toml: &str) -> Vec<&'static str> {
205    let selected = environment_config_profile();
206    match parse_config_with_profile(local_toml, selected.as_deref()) {
207        Ok(mut parsed) => strip_sensitive_overrides(&mut parsed),
208        Err(_) => Vec::new(),
209    }
210}
211
212impl Config {
213    /// Returns the path to the global config file (`$XDG_CONFIG_HOME/lean-ctx/config.toml`).
214    ///
215    /// Resolves the canonical config category without creating directories or
216    /// repairing permissions; existing single-dir installations retain their path.
217    pub fn path() -> Option<PathBuf> {
218        crate::core::paths::config_dir_read_only()
219            .ok()
220            .map(|d| d.join("config.toml"))
221    }
222
223    /// `Some(path)` when the global config the runtime *resolves* does not exist,
224    /// so lean-ctx is silently on built-in defaults. `None` when a config file is
225    /// present (or HOME is unresolvable).
226    ///
227    /// The directory is layout-dependent (XDG `~/.config/lean-ctx` vs legacy
228    /// `~/.lean-ctx` vs `$LEAN_CTX_DATA_DIR`) and an MCP client may launch the
229    /// server in a sandbox/container with a different `$HOME`. An edit made to a
230    /// *different* `config.toml` than this one is silently ignored; the block
231    /// messages use this to say so out loud over MCP, where the stderr path is
232    /// invisible (#540).
233    #[must_use]
234    pub fn missing_config_path() -> Option<PathBuf> {
235        match Self::path() {
236            Some(p) if !p.exists() => Some(p),
237            _ => None,
238        }
239    }
240
241    /// Returns the path to the project-local config override file.
242    pub fn local_path(project_root: &str) -> PathBuf {
243        PathBuf::from(project_root).join(".lean-ctx.toml")
244    }
245
246    /// Resolves the active project root (env override → session → git toplevel →
247    /// cwd), cached for the process. Exposed crate-wide so workspace-trust and the
248    /// CLI agree with config loading on *which* directory a `.lean-ctx.toml`
249    /// belongs to (GH security audit, finding 4).
250    pub(crate) fn find_project_root() -> Option<String> {
251        static ROOT_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
252        ROOT_CACHE
253            .get_or_init(Self::find_project_root_inner)
254            .clone()
255    }
256
257    fn find_project_root_inner() -> Option<String> {
258        if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
259            && !env_root.is_empty()
260        {
261            return Some(env_root);
262        }
263
264        let cwd = std::env::current_dir().ok();
265
266        if let Some(root) =
267            crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
268        {
269            let root_path = std::path::Path::new(&root);
270            let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
271            // Route the marker probe through the TCC-guarded helper and never
272            // adopt a ~/Documents project root from a launchd-standalone process
273            // (#356): doing so would later stat its `.lean-ctx.toml`/markers and
274            // pop the macOS privacy prompt in lean-ctx's own name.
275            let has_marker = crate::core::pathutil::has_project_marker(root_path);
276
277            if (cwd_is_under_root || has_marker) && crate::core::pathutil::may_probe_path(root_path)
278            {
279                return Some(root);
280            }
281        }
282
283        if let Some(ref cwd) = cwd {
284            // A launchd-standalone process must not shell out to `git` (which
285            // stats the working tree) or adopt cwd as the project root when cwd
286            // is under a TCC-protected dir (#356).
287            let may_probe_cwd = crate::core::pathutil::may_probe_path(cwd);
288            let git_root = if may_probe_cwd {
289                std::process::Command::new("git")
290                    .args(["rev-parse", "--show-toplevel"])
291                    .current_dir(cwd)
292                    .stdout(std::process::Stdio::piped())
293                    .stderr(std::process::Stdio::null())
294                    .output()
295                    .ok()
296                    .and_then(|o| {
297                        if o.status.success() {
298                            String::from_utf8(o.stdout)
299                                .ok()
300                                .map(|s| s.trim().to_string())
301                        } else {
302                            None
303                        }
304                    })
305            } else {
306                None
307            };
308            if let Some(root) = git_root {
309                return Some(root);
310            }
311            if may_probe_cwd && !crate::core::pathutil::is_broad_or_unsafe_root(cwd) {
312                return Some(cwd.to_string_lossy().to_string());
313            }
314        }
315        None
316    }
317
318    /// Loads config from disk with caching, merging global + project-local overrides.
319    ///
320    /// The cache is keyed on a **content hash** of the global + project-local
321    /// files, not their mtime. mtime-only invalidation silently served a stale
322    /// `Config` whenever a content edit preserved the mtime (coarse filesystem
323    /// mtime resolution, `cp -p`, atomic save-then-rename, two edits within the
324    /// same second). A long-lived MCP server then kept the old value (e.g.
325    /// `path_jail`) while a fresh `lean-ctx doctor` process — with an empty
326    /// cache — saw the new one (#406). Config files are tiny, so reading +
327    /// hashing them on every load is negligible and guarantees liveness.
328    pub fn load() -> Self {
329        (*Self::load_arc()).clone()
330    }
331
332    /// Shared-ownership variant of [`load`](Self::load): returns the cached
333    /// `Arc<Config>` so the per-dispatch hot path bumps a refcount instead of
334    /// deep-cloning the whole struct. Liveness is identical to `load` — the
335    /// global and project-local files are still read and content-hashed on
336    /// every call (#406); only the cache payload became an `Arc`, so a cache
337    /// hit is a cheap `Arc::clone`.
338    pub fn load_arc() -> Arc<Self> {
339        static CACHE: Mutex<ConfigCacheSlot> = Mutex::new(None);
340
341        let Some(path) = Self::path() else {
342            return Arc::new(Self::default());
343        };
344
345        let project_root = Self::find_project_root();
346        let local_path = project_root.as_deref().map(Self::local_path);
347
348        // Read raw content up front so the cache key is a content hash.
349        let global_content = std::fs::read_to_string(&path).ok();
350        // TCC (#356): never read a project-local `.lean-ctx.toml` under
351        // ~/Documents from a launchd-standalone process — the read pops the
352        // macOS privacy prompt. `find_project_root` already avoids returning
353        // such roots; this also guards the explicit `LEAN_CTX_PROJECT_ROOT` path.
354        let local_content = local_path
355            .as_ref()
356            .filter(|p| crate::core::pathutil::may_probe_path(p.as_path()))
357            .and_then(|p| std::fs::read_to_string(p).ok());
358
359        let global_hash = global_content.as_deref().map(crate::core::hasher::hash_str);
360        let local_hash = local_content.as_deref().map(crate::core::hasher::hash_str);
361        let selected_profile = environment_config_profile();
362
363        if let Ok(guard) = CACHE.lock()
364            && let Some((ref cfg, ref cached_global, ref cached_local, ref cached_profile)) = *guard
365            && *cached_global == global_hash
366            && *cached_local == local_hash
367            && *cached_profile == selected_profile
368        {
369            return Arc::clone(cfg);
370        }
371
372        let mut cfg: Config = if let Some(ref content) = global_content {
373            match parse_config_with_profile(content, selected_profile.as_deref()) {
374                Ok(c) => {
375                    record_parse_error(None);
376                    c
377                }
378                Err(e) => {
379                    record_parse_error(Some(e.clone()));
380                    tracing::warn!("config parse error in {}: {e}", path.display());
381                    eprintln!(
382                        "\x1b[33m[lean-ctx] WARNING: config parse error in {}: {e}\n  \
383                         Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
384                        path.display()
385                    );
386                    Self::default()
387                }
388            }
389        } else {
390            record_parse_error(None);
391            Self::default()
392        };
393
394        if let Some(ref local) = local_content {
395            // Finding 4: a project-local `.lean-ctx.toml`'s SECURITY-sensitive
396            // overrides (shell allowlist, path-jail widening, proxy upstream, …)
397            // are honoured only for a workspace the user has explicitly trusted.
398            // `local_hash` is exactly the content hash workspace-trust pins, so
399            // editing the file after trust re-gates it (see `workspace_trust`).
400            let trusted = project_root.as_deref().is_some_and(|r| {
401                crate::core::workspace_trust::is_trusted_for(
402                    std::path::Path::new(r),
403                    local_hash.as_deref().unwrap_or_default(),
404                )
405            });
406            cfg.merge_local(local, trusted);
407        }
408
409        cfg.migrate_v4_config_on_disk();
410
411        let cfg = Arc::new(cfg);
412        if let Ok(mut guard) = CACHE.lock() {
413            *guard = Some((Arc::clone(&cfg), global_hash, local_hash, selected_profile));
414        }
415
416        cfg
417    }
418
419    /// Global config merged with the `.lean-ctx.toml` of `project_root` — not
420    /// of the process's own project. A daemon serving several repositories
421    /// must evaluate per-project settings (and their workspace trust) against
422    /// the project being processed. Uncached; same merge + trust rules as
423    /// [`load_arc`](Self::load_arc).
424    pub fn load_for_project_root(project_root: &str) -> Self {
425        let selected_profile = environment_config_profile();
426        let mut cfg = Self::path()
427            .and_then(|p| std::fs::read_to_string(p).ok())
428            .and_then(|c| parse_config_with_profile(&c, selected_profile.as_deref()).ok())
429            .unwrap_or_default();
430        let local_path = Self::local_path(project_root);
431        if crate::core::pathutil::may_probe_path(local_path.as_path())
432            && let Ok(local) = std::fs::read_to_string(&local_path)
433        {
434            let trusted = crate::core::workspace_trust::is_trusted_for(
435                std::path::Path::new(project_root),
436                &crate::core::hasher::hash_str(&local),
437            );
438            cfg.merge_local(&local, trusted);
439        }
440        cfg
441    }
442
443    // `merge_local` is in `merge.rs` (extracted for #660 LOC gate).
444
445    /// Consolidate legacy changes into one recoverable config transaction.
446    /// Preserve explicit telemetry opt-outs and the integrated preference model.
447    pub(crate) fn migrate_v4_config_on_disk(&mut self) {
448        // Telemetry was opt-in before v2, so a persisted `enabled = false`
449        // without an explicit preference is not a choice against v2. Re-enable
450        // it once, in a writable config only: a read-only (declaratively
451        // managed) file keeps exactly what its owner wrote.
452        let path = Self::path();
453        let writable = path
454            .as_deref()
455            .is_some_and(allows_automatic_config_migration);
456        let raw = path
457            .as_deref()
458            .filter(|_| writable)
459            .and_then(|path| std::fs::read_to_string(path).ok());
460        let reset_pending = crate::core::telemetry_consent::legacy_opt_out_reset_pending();
461        let reset = raw
462            .as_deref()
463            .filter(|_| reset_pending)
464            .and_then(reset_legacy_telemetry_opt_out);
465        if reset.is_some() && self.telemetry.preference == super::TelemetryPreference::DefaultOn {
466            self.telemetry.enabled = true;
467        }
468        let preserve_opt_out = self.telemetry.explicitly_disabled();
469        if self.cloud.contribute_enabled {
470            self.cloud.contribute_enabled = false;
471            if !preserve_opt_out {
472                self.telemetry.enabled = true;
473                self.telemetry.preference = super::TelemetryPreference::ExplicitlyEnabled;
474            }
475        }
476        if matches!(self.cognitive_mode, CognitiveMode::Basic) {
477            self.cognitive_mode = CognitiveMode::Full;
478        }
479        let Some(path) = path else {
480            return;
481        };
482        let Some(raw) = raw else {
483            if !writable {
484                tracing::debug!(
485                    "config migration remains in memory: source or directory is read-only"
486                );
487            }
488            // No config yet: there is no legacy opt-out to reset, now or later.
489            if reset_pending && !path.exists() {
490                crate::core::telemetry_consent::mark_legacy_opt_out_reset();
491            }
492            return;
493        };
494        let source = reset.as_deref().unwrap_or(&raw);
495        let migrated = match Self::migrate_v4_config_document(
496            source,
497            environment_config_profile().as_deref(),
498            preserve_opt_out,
499        ) {
500            Ok(Some(updated)) => Some(updated),
501            Ok(None) => (source != raw).then(|| source.to_string()),
502            Err(error) => {
503                tracing::warn!("config migration failed: {error}");
504                return;
505            }
506        };
507        let persisted = match migrated {
508            Some(updated) => crate::config_io::write_atomic_config_migration_checked(
509                &path,
510                &updated,
511                Some(raw.as_bytes()),
512            )
513            .map_err(|error| tracing::warn!("config migration could not be persisted: {error}"))
514            .is_ok(),
515            None => true,
516        };
517        if persisted && reset_pending {
518            crate::core::telemetry_consent::mark_legacy_opt_out_reset();
519        }
520    }
521
522    pub(super) fn migrate_v4_config_document(
523        raw: &str,
524        selected_profile: Option<&str>,
525        preserve_opt_out: bool,
526    ) -> Result<Option<String>, String> {
527        let document = raw
528            .parse::<toml_edit::DocumentMut>()
529            .map_err(|error| error.to_string())?;
530        let legacy_telemetry = document
531            .get("cloud")
532            .and_then(|table| table.get("contribute_enabled"))
533            .and_then(toml_edit::Item::as_bool)
534            == Some(true);
535        let persisted_opt_out = document
536            .get("telemetry")
537            .and_then(|table| table.get("enabled"))
538            .and_then(toml_edit::Item::as_bool)
539            == Some(false);
540        let mut updated = if legacy_telemetry {
541            migrate_legacy_contribute_document(raw, preserve_opt_out || persisted_opt_out)
542                .ok_or_else(|| "invalid legacy telemetry configuration".to_string())?
543        } else {
544            raw.to_string()
545        };
546        if let Some(next) = Self::validated_v3_compression_document(&updated, selected_profile)? {
547            updated = next;
548        }
549        let mut document = updated
550            .parse::<toml_edit::DocumentMut>()
551            .map_err(|error| error.to_string())?;
552        if document
553            .get("cognitive_mode")
554            .and_then(toml_edit::Item::as_str)
555            == Some("basic")
556        {
557            document["cognitive_mode"] = toml_edit::value("full");
558            updated = document.to_string();
559        }
560        parse_config_with_profile(&updated, selected_profile)?;
561        Ok((updated != raw).then_some(updated))
562    }
563
564    pub(crate) fn validated_v3_compression_document(
565        raw: &str,
566        selected_profile: Option<&str>,
567    ) -> Result<Option<String>, String> {
568        let migrated = Self::migrate_v3_compression_document(raw)?;
569        if let Some(ref updated) = migrated {
570            parse_config_with_profile(updated, selected_profile)?;
571        }
572        Ok(migrated)
573    }
574
575    pub(crate) fn migrate_v3_compression_document(raw: &str) -> Result<Option<String>, String> {
576        fn migrate_table(table: &mut toml_edit::Table) -> Result<bool, String> {
577            let has_legacy = ["terse_agent", "output_density", "ultra_compact"]
578                .iter()
579                .any(|key| table.get(key).is_some());
580            if !has_legacy {
581                return Ok(false);
582            }
583
584            let terse = match table.get("terse_agent") {
585                Some(item) => Some(
586                    item.as_str()
587                        .ok_or_else(|| "terse_agent must be a string".to_string())?,
588                ),
589                None => None,
590            };
591            if terse.is_some_and(|value| !matches!(value, "off" | "lite" | "full" | "ultra")) {
592                return Err("invalid terse_agent".to_string());
593            }
594            let density = match table.get("output_density") {
595                Some(item) => Some(
596                    item.as_str()
597                        .ok_or_else(|| "output_density must be a string".to_string())?,
598                ),
599                None => None,
600            };
601            if density.is_some_and(|value| !matches!(value, "normal" | "terse" | "ultra")) {
602                return Err("invalid output_density".to_string());
603            }
604            let ultra = match table.get("ultra_compact") {
605                Some(item) => Some(
606                    item.as_bool()
607                        .ok_or_else(|| "ultra_compact must be a boolean".to_string())?,
608                ),
609                None => None,
610            };
611
612            let level = if let Some(item) = table.get("compression_level") {
613                let value = item
614                    .as_str()
615                    .ok_or_else(|| "compression_level must be a string".to_string())?;
616                if !matches!(value, "off" | "lite" | "standard" | "max" | "raw") {
617                    return Err(format!("invalid compression_level: {value}"));
618                }
619                value
620            } else if ultra == Some(true) || terse == Some("ultra") || density == Some("ultra") {
621                "max"
622            } else if terse == Some("full") {
623                "standard"
624            } else if terse == Some("lite") || density == Some("terse") {
625                "lite"
626            } else {
627                "off"
628            };
629
630            table["compression_level"] = toml_edit::value(level);
631            for key in ["terse_agent", "output_density", "ultra_compact"] {
632                table.remove(key);
633            }
634            Ok(true)
635        }
636
637        let mut document = raw
638            .parse::<toml_edit::DocumentMut>()
639            .map_err(|error| error.to_string())?;
640        let mut changed = migrate_table(document.as_table_mut())?;
641        if let Some(profiles) = document
642            .get_mut("profiles")
643            .and_then(toml_edit::Item::as_table_mut)
644        {
645            for (_, profile) in profiles.iter_mut() {
646                if let Some(table) = profile.as_table_mut() {
647                    changed |= migrate_table(table)?;
648                }
649            }
650        }
651        Ok(changed.then(|| document.to_string()))
652    }
653
654    /// Loads ONLY the global config file — never merging project-local
655    /// `.lean-ctx.toml` overrides, and bypassing the in-memory cache. Every
656    /// PERSIST path must use this (or [`Config::update_global`]): [`Config::load`]
657    /// folds per-project overrides into the struct, and [`Config::save`] writes
658    /// the whole struct back to the GLOBAL file — so a `load → mutate → save`
659    /// round-trip silently leaks per-project values (and, historically, reset
660    /// customized keys) into the global config (#443). Reading global-only makes
661    /// the save leak-free by construction.
662    pub fn load_global() -> Self {
663        Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
664    }
665
666    /// Strict variant of [`Config::load_global`]: an unreadable or unparseable
667    /// global config is an error instead of silently becoming the defaults.
668    /// Consent-gated paths (telemetry send) must use this so a corrupt file
669    /// never turns into default-on behaviour.
670    pub fn try_load_global() -> Result<Self, super::error::LeanCtxError> {
671        let path = Self::path().ok_or_else(|| {
672            super::error::LeanCtxError::Config("cannot determine home directory".into())
673        })?;
674        Self::try_load_global_from(&path)
675    }
676
677    pub(super) fn try_load_global_from(path: &Path) -> Result<Self, super::error::LeanCtxError> {
678        match std::fs::read_to_string(path) {
679            Ok(raw) if !raw.trim().is_empty() => toml::from_str(&raw).map_err(|error| {
680                super::error::LeanCtxError::Config(
681                    format!("refusing invalid global config.toml ({error})").into(),
682                )
683            }),
684            Ok(_) => Ok(Self::default()),
685            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
686            Err(error) => Err(error.into()),
687        }
688    }
689
690    /// Path-parameterized core of [`Config::load_global`] (unit-testable without
691    /// the real config dir). Missing, empty, or unparseable files yield
692    /// defaults; persisting callers that must not clobber a corrupt file use
693    /// [`Config::update_global`], which refuses instead.
694    pub(super) fn load_global_from(path: &Path) -> Self {
695        Self::try_load_global_from(path).unwrap_or_default()
696    }
697}
698
699// Respect declared read-only permissions even when a privileged process could
700// bypass them. Other access restrictions still fail at the transactional writer.
701fn allows_automatic_config_migration(path: &Path) -> bool {
702    path.parent().is_some_and(|parent| {
703        [path, parent].iter().all(|entry| {
704            std::fs::metadata(entry).is_ok_and(|metadata| !metadata.permissions().readonly())
705        })
706    })
707}
708
709/// Re-enables a pre-v2 `telemetry.enabled = false` that carries no explicit
710/// preference. Returns `None` when there is nothing to reset, including every
711/// explicit choice (`explicitly_disabled` stays off).
712pub(super) fn reset_legacy_telemetry_opt_out(raw: &str) -> Option<String> {
713    let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
714    let telemetry = document.get("telemetry")?;
715    let disabled = telemetry.get("enabled").and_then(toml_edit::Item::as_bool) == Some(false);
716    let implicit = matches!(
717        telemetry.get("preference").map(toml_edit::Item::as_str),
718        None | Some(Some("default_on"))
719    );
720    if !(disabled && implicit) {
721        return None;
722    }
723    document["telemetry"]["enabled"] = toml_edit::value(true);
724    Some(document.to_string())
725}
726
727fn migrate_legacy_contribute_document(raw: &str, preserve_opt_out: bool) -> Option<String> {
728    let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
729    document["cloud"]["contribute_enabled"] = toml_edit::value(false);
730    if !preserve_opt_out {
731        document["telemetry"]["enabled"] = toml_edit::value(true);
732        document["telemetry"]["preference"] = toml_edit::value("explicitly_enabled");
733    }
734    Some(document.to_string())
735}
736
737#[cfg(test)]
738mod telemetry_migration_tests {
739    use super::*;
740
741    #[test]
742    #[cfg(unix)]
743    fn automatic_migration_respects_readonly_file_and_directory() {
744        use std::os::unix::fs::PermissionsExt;
745        let directory = tempfile::tempdir().expect("migration directory");
746        let path = directory.path().join("config.toml");
747        std::fs::write(&path, "ultra_compact = true\n").expect("legacy config");
748        assert!(allows_automatic_config_migration(&path));
749        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap();
750        let readonly_file = allows_automatic_config_migration(&path);
751        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
752        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o500)).unwrap();
753        let readonly_directory = allows_automatic_config_migration(&path);
754        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
755        assert!(!readonly_file);
756        assert!(!readonly_directory);
757        assert!(!allows_automatic_config_migration(
758            &directory.path().join("missing.toml")
759        ));
760    }
761
762    #[test]
763    fn legacy_opt_in_becomes_explicit_and_send_eligible() {
764        let migrated = migrate_legacy_contribute_document(
765            "# keep me\n[cloud]\ncontribute_enabled = true\n",
766            false,
767        )
768        .expect("valid TOML");
769        assert!(migrated.contains("# keep me"));
770        let cfg: Config = toml::from_str(&migrated).expect("migrated config");
771        assert!(!cfg.cloud.contribute_enabled);
772        assert!(cfg.telemetry.enabled);
773        assert_eq!(
774            cfg.telemetry.preference,
775            super::super::TelemetryPreference::ExplicitlyEnabled
776        );
777        assert!(cfg.telemetry.send_eligible(None, None));
778    }
779
780    #[test]
781    fn legacy_contribute_never_overrides_explicit_opt_out() {
782        let migrated = migrate_legacy_contribute_document(
783            "[cloud]\ncontribute_enabled = true\n[telemetry]\nenabled = false\n",
784            true,
785        )
786        .expect("valid TOML");
787        let cfg: Config = toml::from_str(&migrated).expect("migrated config");
788        assert!(!cfg.cloud.contribute_enabled);
789        assert!(cfg.telemetry.explicitly_disabled());
790    }
791}