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