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
12/// Advances each time [`Config::load_arc`] builds a new value: the global or
13/// project config, the profile or the project's trust changed (#2195).
14static CONFIG_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
15
16thread_local! {
17    /// Set while the shell-security policy is merged: no environment-selected
18    /// profile applies to it (`shell_policy`).
19    static IGNORE_ENV_PROFILE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20}
21
22/// Runs `f` with the environment's config profile ignored.
23pub(super) fn without_env_profile<T>(f: impl FnOnce() -> T) -> T {
24    let previous = IGNORE_ENV_PROFILE.with(|c| c.replace(true));
25    let out = f();
26    IGNORE_ENV_PROFILE.with(|c| c.set(previous));
27    out
28}
29
30pub(super) fn environment_config_profile() -> Option<String> {
31    if IGNORE_ENV_PROFILE.with(std::cell::Cell::get) {
32        return None;
33    }
34    std::env::var(CONFIG_PROFILE_ENV)
35        .ok()
36        .map(|name| name.trim().to_string())
37        .filter(|name| !name.is_empty())
38}
39
40/// Parses a config and recursively applies one named partial overlay. An
41/// explicit selector (normally the environment) wins over `config_profile`.
42pub(super) fn parse_config_with_profile(
43    raw: &str,
44    explicit_profile: Option<&str>,
45) -> Result<Config, String> {
46    resolve_config_table(raw, explicit_profile)?
47        .try_into()
48        .map_err(|error: toml::de::Error| error.to_string())
49}
50
51/// The TOML document `raw` describes once its selected profile overlay is
52/// applied (and legacy compression keys are migrated), before it becomes a
53/// [`Config`]: a merge can see which keys the document sets.
54pub(super) fn resolve_config_table(
55    raw: &str,
56    explicit_profile: Option<&str>,
57) -> Result<toml::Value, String> {
58    let migrated = Config::migrate_v3_compression_document(raw)?;
59    let raw = migrated.as_deref().unwrap_or(raw);
60    let mut value: toml::Value = toml::from_str(raw).map_err(|error| error.to_string())?;
61    super::renamed::apply(
62        value
63            .as_table_mut()
64            .expect("a TOML document always has a root table"),
65    );
66    let configured_profile = value.get("config_profile").and_then(toml::Value::as_str);
67    let selected = explicit_profile
68        .map(str::trim)
69        .filter(|name| !name.is_empty())
70        .or(configured_profile);
71
72    if let Some(name) = selected {
73        let profiles = value
74            .get("profiles")
75            .and_then(toml::Value::as_table)
76            .ok_or_else(|| format!("config profile '{name}' selected but [profiles] is missing"))?;
77        let mut overlay = profiles
78            .get(name)
79            .and_then(toml::Value::as_table)
80            .cloned()
81            .ok_or_else(|| format!("config profile '{name}' is not defined"))?;
82        if overlay.remove("profiles").is_some() || overlay.remove("config_profile").is_some() {
83            return Err(format!(
84                "config profile '{name}' cannot override reserved profile keys"
85            ));
86        }
87        super::renamed::apply(&mut overlay);
88        merge_toml_tables(
89            value
90                .as_table_mut()
91                .expect("a TOML document always has a root table"),
92            overlay,
93        );
94    }
95
96    Ok(value)
97}
98
99fn merge_toml_tables(base: &mut toml::Table, overlay: toml::Table) {
100    for (key, overlay_value) in overlay {
101        match (base.get_mut(&key), overlay_value) {
102            (Some(toml::Value::Table(base_table)), toml::Value::Table(overlay_table)) => {
103                merge_toml_tables(base_table, overlay_table);
104            }
105            (_, replacement) => {
106                base.insert(key, replacement);
107            }
108        }
109    }
110}
111
112/// Holds the most recent global `config.toml` parse error, if the file currently
113/// fails to parse. When that happens `Config::load()` silently falls back to the
114/// built-in defaults and only logs to stderr — which is invisible over an MCP/stdio
115/// transport. Recording it here lets callers (e.g. the shell-allowlist diagnostic
116/// and `lean-ctx doctor`) surface "you're on defaults because your config is broken".
117static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
118
119/// Returns the most recent global config parse error, or `None` if the current
120/// `config.toml` parsed successfully (or no config file exists).
121#[must_use]
122pub fn last_config_parse_error() -> Option<String> {
123    LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
124}
125
126/// Parses a global `config.toml` document exactly as [`Config::load`] does
127/// (legacy-key migration, renamed keys, selected profile overlay) and reports
128/// the error that would make the loader fall back to defaults. `config
129/// validate` uses it so it never accepts a value the loader cannot read
130/// (gh-2283).
131pub fn check_config_document(raw: &str) -> Result<(), String> {
132    parse_config_with_profile(raw, environment_config_profile().as_deref()).map(|_| ())
133}
134
135fn record_parse_error(err: Option<String>) {
136    if let Ok(mut guard) = LAST_PARSE_ERROR.lock() {
137        *guard = err;
138    }
139}
140
141/// Why a loaded [`Config`] holds built-in defaults although a global
142/// `config.toml` is present. Carried on the snapshot itself
143/// ([`Config::load_failure`]), so a decision that depends on "were the
144/// operator's settings applied?" reads it from the very value it uses.
145/// [`last_config_parse_error`] is a diagnostic for humans and must not be used
146/// for that: it is process-global and a later load overwrites it.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum ConfigLoadFailure {
149    /// The file exists but could not be read as text: permission denied,
150    /// invalid UTF-8, a directory in its place, or another I/O error. A file
151    /// that is simply absent (clean install) is not a failure.
152    Unreadable,
153    /// The file was read but is not a valid configuration: TOML syntax, a
154    /// field of the wrong type, or a selected profile that is not defined.
155    Invalid,
156}
157
158impl ConfigLoadFailure {
159    /// Stable reason code for refusals and diagnostics.
160    #[must_use]
161    pub fn code(self) -> &'static str {
162        match self {
163            Self::Unreadable => "config.global_unreadable",
164            Self::Invalid => "config.global_invalid",
165        }
166    }
167}
168
169/// Reset every SECURITY-sensitive field of a parsed project-local `Config` back
170/// to its default, returning the names of the ones that actually carried an
171/// override. Used by [`Config::merge_local`] for untrusted workspaces: clearing a
172/// field to its default makes the downstream "== default ⇒ no override" merge
173/// guards skip it automatically, so a single list here gates every sensitive key
174/// without touching the per-field merge arms (security audit #4).
175///
176/// Sensitive = anything that can widen lean-ctx's own boundaries or steer the
177/// agent: the shell allowlist, path-jail roots, proxy upstreams, command
178/// aliases, network passthrough, rules scope/injection, tool surface control
179/// (profile/enabled-list/categories, disabling) and permission inheritance.
180/// Comfort/perf knobs are intentionally NOT listed.
181pub(crate) fn strip_sensitive_overrides(local: &mut Config) -> Vec<&'static str> {
182    let mut withheld: Vec<&'static str> = Vec::new();
183
184    if local.shell_allowlist != default_shell_allowlist() {
185        local.shell_allowlist = default_shell_allowlist();
186        withheld.push("shell_allowlist");
187    }
188    if !local.shell_allowlist_extra.is_empty() {
189        local.shell_allowlist_extra.clear();
190        withheld.push("shell_allowlist_extra");
191    }
192    if !local.allow_paths.is_empty() {
193        local.allow_paths.clear();
194        withheld.push("allow_paths");
195    }
196    if !local.extra_roots.is_empty() {
197        local.extra_roots.clear();
198        withheld.push("extra_roots");
199    }
200    // Shell-redirect write targets widen what lean-ctx may write.
201    if !local.write_allow_paths.is_empty() {
202        local.write_allow_paths.clear();
203        withheld.push("write_allow_paths");
204    }
205    // Read-only roots also resolve reads like extra roots (#475).
206    if !local.read_only_roots.is_empty() {
207        local.read_only_roots.clear();
208        withheld.push("read_only_roots");
209    }
210    // `off` skips the native-read redirect and the redaction it applies.
211    if local.read_redirect == super::ReadRedirect::Off {
212        local.read_redirect = super::ReadRedirect::default();
213        withheld.push("read_redirect");
214    }
215    if !local.allow_symlink_roots.is_empty() {
216        local.allow_symlink_roots.clear();
217        withheld.push("allow_symlink_roots");
218    }
219    // Destinations ctx_shell redirects and downloads may write to.
220    if !local.write_allow_paths.is_empty() {
221        local.write_allow_paths.clear();
222        withheld.push("write_allow_paths");
223    }
224    if !local.custom_aliases.is_empty() {
225        local.custom_aliases.clear();
226        withheld.push("custom_aliases");
227    }
228    if !local.passthrough_urls.is_empty() {
229        local.passthrough_urls.clear();
230        withheld.push("passthrough_urls");
231    }
232    // Paths in `redirect_exclude` skip the native-read redirect, and with it
233    // the redaction that path applies; a cloned repo must not opt itself out.
234    if !local.redirect_exclude.is_empty() {
235        local.redirect_exclude.clear();
236        withheld.push("redirect_exclude");
237    }
238    if local.proxy.anthropic_upstream.is_some()
239        || local.proxy.openai_upstream.is_some()
240        || local.proxy.chatgpt_upstream.is_some()
241        || local.proxy.gemini_upstream.is_some()
242    {
243        local.proxy.anthropic_upstream = None;
244        local.proxy.openai_upstream = None;
245        local.proxy.chatgpt_upstream = None;
246        local.proxy.gemini_upstream = None;
247        withheld.push("proxy.*_upstream");
248    }
249    // `eager` lets background work start language servers, which execute
250    // project code (build scripts, proc macros). Lowering to off/auto is safe.
251    if local.semantic_mode == super::SemanticMode::Eager {
252        local.semantic_mode = super::SemanticMode::default();
253        withheld.push("semantic_mode");
254    }
255    if local.rules_scope.is_some() {
256        local.rules_scope = None;
257        withheld.push("rules_scope");
258    }
259    if local.rules_injection.is_some() {
260        local.rules_injection = None;
261        withheld.push("rules_injection");
262    }
263    if local.permission_inheritance.is_some() {
264        local.permission_inheritance = None;
265        withheld.push("permission_inheritance");
266    }
267    if !local.disabled_tools.is_empty() {
268        local.disabled_tools.clear();
269        withheld.push("disabled_tools");
270    }
271    if local.tool_profile.is_some() {
272        local.tool_profile = None;
273        withheld.push("tool_profile");
274    }
275    if !local.tools_enabled.is_empty() {
276        local.tools_enabled.clear();
277        withheld.push("tools_enabled");
278    }
279    if !local.default_tool_categories.is_empty() {
280        local.default_tool_categories.clear();
281        withheld.push("default_tool_categories");
282    }
283    if !local.index.respect_gitignore {
284        local.index.respect_gitignore = true;
285        withheld.push("index.respect_gitignore");
286    }
287    if !local.shell_allowlist_subcommand_scoping {
288        local.shell_allowlist_subcommand_scoping = true;
289        withheld.push("shell_allowlist_subcommand_scoping");
290    }
291
292    withheld
293}
294
295/// Tell the gateway evidence store the ceiling this configuration gives.
296/// The store's writers run deep inside calls and must not load a
297/// configuration themselves (`receipt_store::capacity`, G09).
298fn note_gateway_store_ceiling(cfg: &Config) {
299    crate::core::context_admission::receipt_store::capacity::note_configured_ceiling(
300        cfg.gateway_store_configured_mb(),
301    );
302}
303
304/// Names of the SECURITY-sensitive overrides a project-local `.lean-ctx.toml`
305/// carries — the keys `strip_sensitive_overrides` would withhold for an
306/// untrusted workspace. Read-only (parses a throwaway `Config`); used by
307/// `lean-ctx trust` to tell the user exactly what trusting will enable.
308#[must_use]
309pub fn local_sensitive_overrides(local_toml: &str) -> Vec<&'static str> {
310    let selected = environment_config_profile();
311    match parse_config_with_profile(local_toml, selected.as_deref()) {
312        Ok(mut parsed) => strip_sensitive_overrides(&mut parsed),
313        Err(_) => Vec::new(),
314    }
315}
316
317/// A string-array key from the raw GLOBAL config table — never the merged
318/// runtime view, so project-local or default values are never persisted
319/// globally.
320pub fn global_string_list(key: &str) -> Vec<String> {
321    let Some(path) = Config::path() else {
322        return Vec::new();
323    };
324    let Ok(raw) = std::fs::read_to_string(&path) else {
325        return Vec::new();
326    };
327    let Ok(table) = raw.parse::<toml::Table>() else {
328        return Vec::new();
329    };
330    table
331        .get(key)
332        .and_then(toml::Value::as_array)
333        .map(|arr| {
334            arr.iter()
335                .filter_map(|v| v.as_str().map(str::to_string))
336                .collect()
337        })
338        .unwrap_or_default()
339}
340
341impl Config {
342    /// Returns the path to the global config file (`$XDG_CONFIG_HOME/lean-ctx/config.toml`).
343    ///
344    /// Resolves the canonical config category without creating directories or
345    /// repairing permissions; existing single-dir installations retain their path.
346    pub fn path() -> Option<PathBuf> {
347        crate::core::paths::config_dir_read_only()
348            .ok()
349            .map(|d| d.join("config.toml"))
350    }
351
352    /// `Some(path)` when the global config the runtime *resolves* does not exist,
353    /// so lean-ctx is silently on built-in defaults. `None` when a config file is
354    /// present (or HOME is unresolvable).
355    ///
356    /// The directory is layout-dependent (XDG `~/.config/lean-ctx` vs legacy
357    /// `~/.lean-ctx` vs `$LEAN_CTX_DATA_DIR`) and an MCP client may launch the
358    /// server in a sandbox/container with a different `$HOME`. An edit made to a
359    /// *different* `config.toml` than this one is silently ignored; the block
360    /// messages use this to say so out loud over MCP, where the stderr path is
361    /// invisible (#540).
362    #[must_use]
363    pub fn missing_config_path() -> Option<PathBuf> {
364        match Self::path() {
365            Some(p) if !p.exists() => Some(p),
366            _ => None,
367        }
368    }
369
370    /// Returns the path to the project-local config override file.
371    pub fn local_path(project_root: &str) -> PathBuf {
372        PathBuf::from(project_root).join(".lean-ctx.toml")
373    }
374
375    /// Resolves the active project root (env override → session → git toplevel →
376    /// cwd), cached for the process. Exposed crate-wide so workspace-trust and the
377    /// CLI agree with config loading on *which* directory a `.lean-ctx.toml`
378    /// belongs to (GH security audit, finding 4).
379    ///
380    /// Inside a request the request's bound project is the root, uncached: a
381    /// server serving several projects must apply each one's own
382    /// `.lean-ctx.toml` and trust, never the first one it happened to resolve
383    /// (AP04-G3).
384    pub fn find_project_root() -> Option<String> {
385        static ROOT_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
386        if let Ok(project) =
387            crate::core::policy::runtime::REQUEST_PROJECT.try_with(|slot| slot.borrow().clone())
388        {
389            return project.map(|root| root.to_string_lossy().into_owned());
390        }
391        ROOT_CACHE
392            .get_or_init(Self::find_project_root_inner)
393            .clone()
394    }
395
396    fn find_project_root_inner() -> Option<String> {
397        if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
398            && !env_root.is_empty()
399        {
400            return Some(env_root);
401        }
402
403        let cwd = std::env::current_dir().ok();
404
405        if let Some(root) =
406            crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
407        {
408            let root_path = std::path::Path::new(&root);
409            let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
410            // Route the marker probe through the TCC-guarded helper and never
411            // adopt a ~/Documents project root from a launchd-standalone process
412            // (#356): doing so would later stat its `.lean-ctx.toml`/markers and
413            // pop the macOS privacy prompt in lean-ctx's own name.
414            let has_marker = crate::core::pathutil::has_project_marker(root_path);
415
416            if (cwd_is_under_root || has_marker) && crate::core::pathutil::may_probe_path(root_path)
417            {
418                return Some(root);
419            }
420        }
421
422        if let Some(ref cwd) = cwd {
423            // A launchd-standalone process must not shell out to `git` (which
424            // stats the working tree) or adopt cwd as the project root when cwd
425            // is under a TCC-protected dir (#356).
426            let may_probe_cwd = crate::core::pathutil::may_probe_path(cwd);
427            let git_root = if may_probe_cwd {
428                std::process::Command::new("git")
429                    .args(["rev-parse", "--show-toplevel"])
430                    .current_dir(cwd)
431                    .stdout(std::process::Stdio::piped())
432                    .stderr(std::process::Stdio::null())
433                    .output()
434                    .ok()
435                    .and_then(|o| {
436                        if o.status.success() {
437                            String::from_utf8(o.stdout)
438                                .ok()
439                                .map(|s| s.trim().to_string())
440                        } else {
441                            None
442                        }
443                    })
444            } else {
445                None
446            };
447            if let Some(root) = git_root {
448                return Some(root);
449            }
450            if may_probe_cwd && !crate::core::pathutil::is_broad_or_unsafe_root(cwd) {
451                return Some(cwd.to_string_lossy().to_string());
452            }
453        }
454        None
455    }
456
457    /// Loads config from disk with caching, merging global + project-local overrides.
458    ///
459    /// The cache is keyed on a **content hash** of the global + project-local
460    /// files, not their mtime. mtime-only invalidation silently served a stale
461    /// `Config` whenever a content edit preserved the mtime (coarse filesystem
462    /// mtime resolution, `cp -p`, atomic save-then-rename, two edits within the
463    /// same second). A long-lived MCP server then kept the old value (e.g.
464    /// `path_jail`) while a fresh `lean-ctx doctor` process — with an empty
465    /// cache — saw the new one (#406). Config files are tiny, so reading +
466    /// hashing them on every load is negligible and guarantees liveness.
467    pub fn load() -> Self {
468        (*Self::load_arc()).clone()
469    }
470
471    /// Shared-ownership variant of [`load`](Self::load): returns the cached
472    /// `Arc<Config>` so the per-dispatch hot path bumps a refcount instead of
473    /// deep-cloning the whole struct. Liveness is identical to `load` — the
474    /// global and project-local files are still read and content-hashed on
475    /// every call (#406); only the cache payload became an `Arc`, so a cache
476    /// hit is a cheap `Arc::clone`.
477    /// The config generation: it advances whenever a load sees a changed
478    /// config (content, project, profile or trust), so a cache derived from
479    /// the config can key on it instead of re-reading the config (#2195).
480    pub fn generation() -> u64 {
481        CONFIG_GENERATION.load(std::sync::atomic::Ordering::Acquire)
482    }
483
484    pub fn load_arc() -> Arc<Self> {
485        static CACHE: Mutex<ConfigCacheSlot> = Mutex::new(None);
486        Self::load_arc_with(Self::find_project_root().as_deref(), &CACHE)
487    }
488
489    pub(super) fn load_arc_with(
490        project_root: Option<&str>,
491        cache: &Mutex<ConfigCacheSlot>,
492    ) -> Arc<Self> {
493        let Some(path) = Self::path() else {
494            return Arc::new(Self::default());
495        };
496
497        let local_path = project_root.map(Self::local_path);
498
499        // Read raw content up front so the cache key is a content hash. Only a
500        // file that is absent counts as "no config"; any other read error
501        // means settings exist that could not be applied.
502        let (global_content, unreadable) = match std::fs::read_to_string(&path) {
503            Ok(content) => (Some(content), None),
504            Err(error) if error.kind() == std::io::ErrorKind::NotFound => (None, None),
505            Err(error) => (None, Some(error.kind())),
506        };
507        // TCC (#356): never read a project-local `.lean-ctx.toml` under
508        // ~/Documents from a launchd-standalone process — the read pops the
509        // macOS privacy prompt. `find_project_root` already avoids returning
510        // such roots; this also guards the explicit `LEAN_CTX_PROJECT_ROOT` path.
511        let local_content = local_path
512            .as_ref()
513            .filter(|p| crate::core::pathutil::may_probe_path(p.as_path()))
514            .and_then(|p| std::fs::read_to_string(p).ok());
515
516        // An unreadable file gets its own cache key, distinct from "absent".
517        let global_hash = global_content
518            .as_deref()
519            .map(crate::core::hasher::hash_str)
520            .or_else(|| unreadable.map(|kind| format!("unreadable:{kind:?}")));
521        let local_hash = local_content.as_deref().map(crate::core::hasher::hash_str);
522        // Trust is per project: equal local files of two projects are not one
523        // cache entry.
524        let local_key = local_hash
525            .as_deref()
526            .map(|hash| format!("{}\0{hash}", project_root.unwrap_or_default()));
527        let selected_profile = environment_config_profile();
528
529        // Finding 4: a project-local `.lean-ctx.toml`'s SECURITY-sensitive
530        // overrides (shell allowlist, path-jail widening, proxy upstream, …)
531        // are honoured only for a workspace the user has explicitly trusted.
532        // `local_hash` is exactly the content hash workspace-trust pins, so
533        // editing the file after trust re-gates it (see `workspace_trust`).
534        // Decided before the cache lookup and part of the key, so `trust` /
535        // `untrust` reach a running server without a file change (#2144).
536        let trusted = local_content.is_some()
537            && project_root.is_some_and(|r| {
538                crate::core::workspace_trust::is_trusted_for(
539                    std::path::Path::new(r),
540                    local_hash.as_deref().unwrap_or_default(),
541                )
542            });
543
544        // The machine's managed configuration overlays `[cloud]` (below).
545        let managed = crate::core::config::managed::current();
546        let managed_key = crate::core::config::managed::cache_key();
547
548        if let Ok(guard) = cache.lock()
549            && let Some((
550                ref cfg,
551                ref cached_global,
552                ref cached_local,
553                ref cached_profile,
554                cached_trusted,
555                ref cached_managed,
556            )) = *guard
557            && *cached_global == global_hash
558            && *cached_local == local_key
559            && *cached_profile == selected_profile
560            && cached_trusted == trusted
561            && *cached_managed == managed_key
562        {
563            note_gateway_store_ceiling(cfg);
564            return Arc::clone(cfg);
565        }
566
567        let mut failure = unreadable.map(|_| ConfigLoadFailure::Unreadable);
568        let mut cfg: Config = if let Some(ref content) = global_content {
569            match parse_config_with_profile(content, selected_profile.as_deref()) {
570                Ok(c) => {
571                    record_parse_error(None);
572                    c
573                }
574                Err(e) => {
575                    failure = Some(ConfigLoadFailure::Invalid);
576                    record_parse_error(Some(e.clone()));
577                    tracing::warn!("config parse error in {}: {e}", path.display());
578                    eprintln!(
579                        "\x1b[33m[lean-ctx] WARNING: config parse error in {}: {e}\n  \
580                         Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
581                        path.display()
582                    );
583                    Self::default()
584                }
585            }
586        } else if let Some(kind) = unreadable {
587            let message = format!("cannot read config: {kind}");
588            record_parse_error(Some(message.clone()));
589            tracing::warn!("{message} ({})", path.display());
590            eprintln!(
591                "\x1b[33m[lean-ctx] WARNING: {message} ({})\n  \
592                 Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
593                path.display()
594            );
595            Self::default()
596        } else {
597            record_parse_error(None);
598            Self::default()
599        };
600
601        if let Some(ref local) = local_content {
602            cfg.merge_local(local, trusted);
603        }
604
605        // A snapshot of defaults standing in for an unusable file must not be
606        // migrated back to disk.
607        if failure.is_none() {
608            cfg.migrate_v4_config_on_disk();
609        }
610        // Managed > Cloud floor > user config > defaults. After the on-disk
611        // migration, so the overlay never reaches the user's file.
612        if let Some(managed) = &managed {
613            managed.apply_to_cloud(&mut cfg.cloud);
614        }
615        // Last, so no merge step can drop it: the marker belongs to this value.
616        cfg.load_failure = failure;
617
618        let cfg = Arc::new(cfg);
619        if let Ok(mut guard) = cache.lock() {
620            *guard = Some((
621                Arc::clone(&cfg),
622                global_hash,
623                local_key,
624                selected_profile,
625                trusted,
626                managed_key,
627            ));
628        }
629        CONFIG_GENERATION.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
630
631        note_gateway_store_ceiling(&cfg);
632        cfg
633    }
634
635    /// Global config merged with the `.lean-ctx.toml` of `project_root` — not
636    /// of the process's own project. A daemon serving several repositories
637    /// must evaluate per-project settings (and their workspace trust) against
638    /// the project being processed. Uncached; same merge + trust rules as
639    /// [`load_arc`](Self::load_arc).
640    pub fn load_for_project_root(project_root: &str) -> Self {
641        let selected_profile = environment_config_profile();
642        let mut cfg = Self::path()
643            .and_then(|p| std::fs::read_to_string(p).ok())
644            .and_then(|c| parse_config_with_profile(&c, selected_profile.as_deref()).ok())
645            .unwrap_or_default();
646        let local_path = Self::local_path(project_root);
647        if crate::core::pathutil::may_probe_path(local_path.as_path())
648            && let Ok(local) = std::fs::read_to_string(&local_path)
649        {
650            let trusted = crate::core::workspace_trust::is_trusted_for(
651                std::path::Path::new(project_root),
652                &crate::core::hasher::hash_str(&local),
653            );
654            cfg.merge_local(&local, trusted);
655        }
656        cfg
657    }
658
659    // `merge_local` is in `merge.rs` (extracted for #660 LOC gate).
660
661    /// Consolidate legacy changes into one recoverable config transaction.
662    /// Preserve explicit telemetry opt-outs and the integrated preference model.
663    pub(crate) fn migrate_v4_config_on_disk(&mut self) {
664        // Telemetry was opt-in before v2, so a persisted `enabled = false`
665        // without an explicit preference is not a choice against v2. Re-enable
666        // it once, in a writable config only: a read-only (declaratively
667        // managed) file keeps exactly what its owner wrote.
668        let path = Self::path();
669        let writable = path
670            .as_deref()
671            .is_some_and(allows_automatic_config_migration);
672        let raw = path
673            .as_deref()
674            .filter(|_| writable)
675            .and_then(|path| std::fs::read_to_string(path).ok());
676        let reset_pending = crate::core::telemetry_consent::legacy_opt_out_reset_pending();
677        let reset = raw
678            .as_deref()
679            .filter(|_| reset_pending)
680            .and_then(reset_legacy_telemetry_opt_out);
681        let reenables =
682            reset.is_some() && self.telemetry.preference == super::TelemetryPreference::DefaultOn;
683        // The opt-out the migrated document will carry: with the reset applied
684        // only an explicit preference keeps telemetry off.
685        let preserve_opt_out = if reenables {
686            self.telemetry.preference == super::TelemetryPreference::ExplicitlyDisabled
687        } else {
688            self.telemetry.explicitly_disabled()
689        };
690        // The reset flips consent, so it takes effect in memory only once it is
691        // on disk. While it cannot be persisted (#2175: a refused journal), the
692        // user's saved `enabled = false` stays authoritative and the reset
693        // stays pending.
694        let persisted = self.persist_v4_migration(
695            path.as_deref(),
696            writable,
697            raw.as_deref(),
698            reset.as_deref(),
699            reset_pending,
700            preserve_opt_out,
701        );
702        if reenables && persisted {
703            self.telemetry.enabled = true;
704        }
705        let preserve_opt_out = self.telemetry.explicitly_disabled();
706        if self.cloud.contribute_enabled {
707            self.cloud.contribute_enabled = false;
708            if !preserve_opt_out {
709                self.telemetry.enabled = true;
710                self.telemetry.preference = super::TelemetryPreference::ExplicitlyEnabled;
711            }
712        }
713    }
714
715    /// Writes the migrated document through the config migration journal.
716    /// Returns whether the on-disk config now carries the migration (also
717    /// `true` when nothing had to change).
718    fn persist_v4_migration(
719        &self,
720        path: Option<&Path>,
721        writable: bool,
722        raw: Option<&str>,
723        reset: Option<&str>,
724        reset_pending: bool,
725        preserve_opt_out: bool,
726    ) -> bool {
727        let Some(path) = path else {
728            return false;
729        };
730        let Some(raw) = raw else {
731            if !writable {
732                tracing::debug!(
733                    "config migration remains in memory: source or directory is read-only"
734                );
735            }
736            // No config yet: there is no legacy opt-out to reset, now or later.
737            if reset_pending && !path.exists() {
738                crate::core::telemetry_consent::mark_legacy_opt_out_reset();
739            }
740            return false;
741        };
742        let source = reset.unwrap_or(raw);
743        let migrated = match Self::migrate_v4_config_document(
744            source,
745            environment_config_profile().as_deref(),
746            preserve_opt_out,
747        ) {
748            Ok(Some(updated)) => Some(updated),
749            Ok(None) => (source != raw).then(|| source.to_string()),
750            Err(error) => {
751                tracing::warn!("config migration failed: {error}");
752                return false;
753            }
754        };
755        let persisted = match migrated {
756            Some(updated) => {
757                match crate::config_io::write_atomic_config_migration_checked(
758                    path,
759                    &updated,
760                    Some(raw.as_bytes()),
761                ) {
762                    Ok(()) => true,
763                    Err(error) => {
764                        warn_config_migration_paused_once(path, raw, &updated, &error);
765                        false
766                    }
767                }
768            }
769            None => true,
770        };
771        if persisted {
772            clear_config_migration_pause_marker(path);
773        }
774        if persisted && reset_pending {
775            crate::core::telemetry_consent::mark_legacy_opt_out_reset();
776        }
777        persisted
778    }
779
780    pub(super) fn migrate_v4_config_document(
781        raw: &str,
782        selected_profile: Option<&str>,
783        preserve_opt_out: bool,
784    ) -> Result<Option<String>, String> {
785        let document = raw
786            .parse::<toml_edit::DocumentMut>()
787            .map_err(|error| error.to_string())?;
788        let legacy_telemetry = document
789            .get("cloud")
790            .and_then(|table| table.get("contribute_enabled"))
791            .and_then(toml_edit::Item::as_bool)
792            == Some(true);
793        let persisted_opt_out = document
794            .get("telemetry")
795            .and_then(|table| table.get("enabled"))
796            .and_then(toml_edit::Item::as_bool)
797            == Some(false);
798        let mut updated = if legacy_telemetry {
799            migrate_legacy_contribute_document(raw, preserve_opt_out || persisted_opt_out)
800                .ok_or_else(|| "invalid legacy telemetry configuration".to_string())?
801        } else {
802            raw.to_string()
803        };
804        if let Some(next) = Self::validated_v3_compression_document(&updated, selected_profile)? {
805            updated = next;
806        }
807        if let Some(next) = super::retired::migrate_retired_document(&updated)? {
808            updated = next;
809        }
810        parse_config_with_profile(&updated, selected_profile)?;
811        Ok((updated != raw).then_some(updated))
812    }
813
814    pub(crate) fn validated_v3_compression_document(
815        raw: &str,
816        selected_profile: Option<&str>,
817    ) -> Result<Option<String>, String> {
818        let migrated = Self::migrate_v3_compression_document(raw)?;
819        if let Some(ref updated) = migrated {
820            parse_config_with_profile(updated, selected_profile)?;
821        }
822        Ok(migrated)
823    }
824
825    pub(crate) fn migrate_v3_compression_document(raw: &str) -> Result<Option<String>, String> {
826        fn migrate_table(table: &mut toml_edit::Table) -> Result<bool, String> {
827            let has_legacy = ["terse_agent", "output_density", "ultra_compact"]
828                .iter()
829                .any(|key| table.get(key).is_some());
830            if !has_legacy {
831                return Ok(false);
832            }
833
834            let terse = match table.get("terse_agent") {
835                Some(item) => Some(
836                    item.as_str()
837                        .ok_or_else(|| "terse_agent must be a string".to_string())?,
838                ),
839                None => None,
840            };
841            if terse.is_some_and(|value| !matches!(value, "off" | "lite" | "full" | "ultra")) {
842                return Err("invalid terse_agent".to_string());
843            }
844            let density = match table.get("output_density") {
845                Some(item) => Some(
846                    item.as_str()
847                        .ok_or_else(|| "output_density must be a string".to_string())?,
848                ),
849                None => None,
850            };
851            if density.is_some_and(|value| !matches!(value, "normal" | "terse" | "ultra")) {
852                return Err("invalid output_density".to_string());
853            }
854            let ultra = match table.get("ultra_compact") {
855                Some(item) => Some(
856                    item.as_bool()
857                        .ok_or_else(|| "ultra_compact must be a boolean".to_string())?,
858                ),
859                None => None,
860            };
861
862            let level = if let Some(item) = table.get("compression_level") {
863                let value = item
864                    .as_str()
865                    .ok_or_else(|| "compression_level must be a string".to_string())?;
866                if !matches!(value, "off" | "lite" | "standard" | "max" | "raw") {
867                    return Err(format!("invalid compression_level: {value}"));
868                }
869                value
870            } else if ultra == Some(true) || terse == Some("ultra") || density == Some("ultra") {
871                "max"
872            } else if terse == Some("full") {
873                "standard"
874            } else if terse == Some("lite") || density == Some("terse") {
875                "lite"
876            } else {
877                "off"
878            };
879
880            table["compression_level"] = toml_edit::value(level);
881            for key in ["terse_agent", "output_density", "ultra_compact"] {
882                table.remove(key);
883            }
884            Ok(true)
885        }
886
887        let mut document = raw
888            .parse::<toml_edit::DocumentMut>()
889            .map_err(|error| error.to_string())?;
890        let mut changed = migrate_table(document.as_table_mut())?;
891        if let Some(profiles) = document
892            .get_mut("profiles")
893            .and_then(toml_edit::Item::as_table_mut)
894        {
895            for (_, profile) in profiles.iter_mut() {
896                if let Some(table) = profile.as_table_mut() {
897                    changed |= migrate_table(table)?;
898                }
899            }
900        }
901        Ok(changed.then(|| document.to_string()))
902    }
903
904    /// Loads ONLY the global config file — never merging project-local
905    /// `.lean-ctx.toml` overrides, and bypassing the in-memory cache. Every
906    /// PERSIST path must use this (or [`Config::update_global`]): [`Config::load`]
907    /// folds per-project overrides into the struct, and [`Config::save`] writes
908    /// the whole struct back to the GLOBAL file — so a `load → mutate → save`
909    /// round-trip silently leaks per-project values (and, historically, reset
910    /// customized keys) into the global config (#443). Reading global-only makes
911    /// the save leak-free by construction.
912    pub fn load_global() -> Self {
913        Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
914    }
915
916    /// Strict variant of [`Config::load_global`]: an unreadable or unparseable
917    /// global config is an error instead of silently becoming the defaults.
918    /// Consent-gated paths (telemetry send) must use this so a corrupt file
919    /// never turns into default-on behaviour.
920    pub fn try_load_global() -> Result<Self, super::error::LeanCtxError> {
921        let path = Self::path().ok_or_else(|| {
922            super::error::LeanCtxError::Config("cannot determine home directory".into())
923        })?;
924        Self::try_load_global_from(&path)
925    }
926
927    pub(super) fn try_load_global_from(path: &Path) -> Result<Self, super::error::LeanCtxError> {
928        match std::fs::read_to_string(path) {
929            Ok(raw) if !raw.trim().is_empty() => toml::from_str(&raw).map_err(|error| {
930                super::error::LeanCtxError::Config(
931                    format!("refusing invalid global config.toml ({error})").into(),
932                )
933            }),
934            Ok(_) => Ok(Self::default()),
935            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
936            Err(error) => Err(error.into()),
937        }
938    }
939
940    /// Path-parameterized core of [`Config::load_global`] (unit-testable without
941    /// the real config dir). Missing, empty, or unparseable files yield
942    /// defaults; persisting callers that must not clobber a corrupt file use
943    /// [`Config::update_global`], which refuses instead.
944    pub(super) fn load_global_from(path: &Path) -> Self {
945        Self::try_load_global_from(path).unwrap_or_default()
946    }
947}
948
949/// Prefix of the per-config markers in the state dir that hold the
950/// fingerprint of the last reported paused migration. Every command loads the
951/// config, so without them one refused journal warns on every invocation
952/// (#2175).
953const CONFIG_MIGRATION_PAUSE_MARKER: &str = "config_migration_paused";
954
955/// Marker for one config file: keyed by the blake3 of its canonical write
956/// target, so two config paths (profiles, overrides) never share or clear
957/// each other's state. Content-addressed name, no time or counter.
958pub(super) fn config_migration_pause_marker(path: &Path) -> Option<std::path::PathBuf> {
959    let target =
960        crate::config_io::config_migration_target(path).unwrap_or_else(|| path.to_path_buf());
961    let key = blake3::hash(target.to_string_lossy().as_bytes()).to_hex();
962    crate::core::paths::state_dir()
963        .ok()
964        .map(|dir| dir.join(format!("{CONFIG_MIGRATION_PAUSE_MARKER}.{}", &key[..16])))
965}
966
967/// Why a config migration is paused and what the user can do about it.
968/// Every field is a deterministic function of the config path and the
969/// journal state on disk.
970#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct ConfigMigrationPause {
972    /// Stable class, e.g. `write-refused` or `backup-mismatch`.
973    pub label: &'static str,
974    pub config: std::path::PathBuf,
975    pub backup: std::path::PathBuf,
976    pub receipt: std::path::PathBuf,
977    /// What is wrong, in one sentence.
978    pub reason: String,
979    /// The action that works in this state.
980    pub action: String,
981    /// Archive that keeps the config from before the first recorded migration.
982    pub original: Option<std::path::PathBuf>,
983}
984
985/// Describes the paused migration of `path` from the journal state on disk.
986/// A journal that verifies (or none) means the writer itself was refused.
987pub(super) fn describe_config_migration_pause(path: &Path) -> ConfigMigrationPause {
988    use crate::config_io::{ConfigMigrationJournalRefusal as Refusal, ConfigMigrationJournalState};
989    let config =
990        crate::config_io::config_migration_target(path).unwrap_or_else(|| path.to_path_buf());
991    let (backup, receipt) =
992        crate::config_io::config_migration_journal_files(path).unwrap_or_else(|| {
993            (
994                config.with_file_name("config.toml.v4-migration.bak"),
995                config.with_file_name("config.toml.v4-migration.json"),
996            )
997        });
998    let next = crate::config_io::config_migration_next_receipt_file(path)
999        .unwrap_or_else(|| config.with_file_name("config.toml.v4-migration.next.json"));
1000    let dir = config
1001        .parent()
1002        .map_or_else(|| ".".to_string(), |dir| dir.display().to_string());
1003    let (b, r, n, c) = (
1004        backup.display(),
1005        receipt.display(),
1006        next.display(),
1007        config.display(),
1008    );
1009    let fresh = "; the migration starts a fresh journal on the next command.";
1010    let state = crate::config_io::config_migration_journal_state(path);
1011    let (label, reason, action) = if let ConfigMigrationJournalState::Refused(refusal) = state {
1012        let (reason, action) = match refusal {
1013            Refusal::Symlink => (
1014                "a migration journal file is a symbolic link, which lean-ctx does not follow."
1015                    .to_string(),
1016                format!(
1017                    "Replace {b}, {r} and {n} with regular files or move them out of {dir}{fresh}"
1018                ),
1019            ),
1020            Refusal::Unreadable => (
1021                "a migration journal file cannot be read.".to_string(),
1022                format!(
1023                    "Make {b} and {r} readable for lean-ctx; the migration retries on the next command."
1024                ),
1025            ),
1026            Refusal::ReceiptUnverifiable => (
1027                format!(
1028                    "the journal receipt {r} cannot be verified, so neither the migration nor \
1029                         `lean-ctx migrate config --rollback` can use it."
1030                ),
1031                format!(
1032                    "Check {b} (the config before the recorded migration) and {r}, then move \
1033                         both out of {dir}{fresh}"
1034                ),
1035            ),
1036            Refusal::BackupMismatch => (
1037                format!(
1038                    "the journal backup {b} does not match its receipt {r}, so neither the \
1039                         migration nor `lean-ctx migrate config --rollback` can use it."
1040                ),
1041                format!("Check {b} and {r}, then move both out of {dir}{fresh}"),
1042            ),
1043            Refusal::OrphanBackup => (
1044                format!(
1045                    "{b} has no receipt and matches neither the config nor an archived journal."
1046                ),
1047                format!("Check {b}, then move it out of {dir}{fresh}"),
1048            ),
1049            Refusal::OrphanReceipt => (
1050                format!("{r} has no backup and the config is not the source it records."),
1051                format!("Check {r}, then move it out of {dir}{fresh}"),
1052            ),
1053            Refusal::NextReceiptUnverifiable => (
1054                format!(
1055                    "the unfinished journal update {n} cannot be verified and the config \
1056                         matches neither recorded state."
1057                ),
1058                format!(
1059                    "Check {n}, then move it out of {dir}; the migration retries on the next \
1060                         command."
1061                ),
1062            ),
1063        };
1064        (refusal.label(), reason, action)
1065    } else {
1066        let mut action = format!(
1067            "Make {dir} and {c} writable for lean-ctx; the migration retries on the next command."
1068        );
1069        if state.rollback_available() {
1070            action.push_str(&format!(
1071                " `lean-ctx migrate config --rollback` restores the config recorded in {b}."
1072            ));
1073        }
1074        (
1075            "write-refused",
1076            "lean-ctx could not write the migrated config or its migration journal.".to_string(),
1077            action,
1078        )
1079    };
1080    ConfigMigrationPause {
1081        label,
1082        original: crate::config_io::original_config_migration_backup(path),
1083        config,
1084        backup,
1085        receipt,
1086        reason,
1087        action,
1088    }
1089}
1090
1091impl ConfigMigrationPause {
1092    /// The one-time warning text; stable for a given state.
1093    pub fn message(&self) -> String {
1094        let original = self
1095            .original
1096            .as_deref()
1097            .map(crate::config_io::original_config_sentence)
1098            .unwrap_or_default();
1099        format!(
1100            "config migration paused for {} ({}): {} {}{original} Reported once until the config \
1101             or the journal changes.",
1102            self.config.display(),
1103            self.label,
1104            self.reason,
1105            self.action
1106        )
1107    }
1108}
1109
1110/// The paused migration of `path`, if the last load had to pause it (for
1111/// `lean-ctx doctor`, which reports it on every run, independent of the
1112/// once-per-state warning).
1113pub fn config_migration_pause_status(path: &Path) -> Option<ConfigMigrationPause> {
1114    config_migration_pause_marker(path)
1115        .is_some_and(|marker| marker.is_file())
1116        .then(|| describe_config_migration_pause(path))
1117}
1118
1119/// Deterministic identity of one paused-migration state: the stable class,
1120/// the config path and bytes, the proposed output and every journal file.
1121/// Never the error text, which can carry random temporary file names.
1122pub(super) fn config_migration_pause_fingerprint(
1123    path: &Path,
1124    raw: &str,
1125    updated: &str,
1126    label: &str,
1127) -> String {
1128    let mut hasher = blake3::Hasher::new();
1129    let target =
1130        crate::config_io::config_migration_target(path).unwrap_or_else(|| path.to_path_buf());
1131    let target = target.to_string_lossy();
1132    for part in [
1133        label.as_bytes(),
1134        target.as_bytes(),
1135        raw.as_bytes(),
1136        updated.as_bytes(),
1137    ] {
1138        hasher.update(&(part.len() as u64).to_le_bytes());
1139        hasher.update(part);
1140    }
1141    let journal = crate::config_io::config_migration_journal_files(path)
1142        .map(|(backup, receipt)| vec![backup, receipt])
1143        .unwrap_or_default();
1144    let next = crate::config_io::config_migration_next_receipt_file(path);
1145    for file in journal.into_iter().chain(next) {
1146        let bytes = std::fs::read(file).unwrap_or_default();
1147        hasher.update(&(bytes.len() as u64).to_le_bytes());
1148        hasher.update(&bytes);
1149    }
1150    hasher.finalize().to_hex().to_string()
1151}
1152
1153/// Warns about a refused config migration once per distinct state; repeats
1154/// of the same state go to debug level only. Returns whether it warned.
1155pub(super) fn warn_config_migration_paused_once(
1156    path: &Path,
1157    raw: &str,
1158    updated: &str,
1159    error: &str,
1160) -> bool {
1161    let pause = describe_config_migration_pause(path);
1162    let fingerprint = config_migration_pause_fingerprint(path, raw, updated, pause.label);
1163    let marker = config_migration_pause_marker(path);
1164    let reported = marker
1165        .as_deref()
1166        .and_then(|marker| std::fs::read_to_string(marker).ok())
1167        .is_some_and(|seen| seen.lines().next() == Some(fingerprint.as_str()));
1168    // The raw error can name random temporary files: debug only.
1169    tracing::debug!("config migration paused ({}): {error}", pause.label);
1170    if reported {
1171        return false;
1172    }
1173    tracing::warn!("{}", pause.message());
1174    if let Some(marker) = marker {
1175        if let Some(parent) = marker.parent() {
1176            let _ = std::fs::create_dir_all(parent);
1177        }
1178        let _ = std::fs::write(marker, format!("{fingerprint}\n{}\n", pause.label));
1179    }
1180    true
1181}
1182
1183fn clear_config_migration_pause_marker(path: &Path) {
1184    if let Some(marker) = config_migration_pause_marker(path)
1185        && marker.exists()
1186    {
1187        let _ = std::fs::remove_file(marker);
1188    }
1189}
1190
1191// Respect declared read-only permissions even when a privileged process could
1192// bypass them. Other access restrictions still fail at the transactional writer.
1193fn allows_automatic_config_migration(path: &Path) -> bool {
1194    path.parent().is_some_and(|parent| {
1195        [path, parent].iter().all(|entry| {
1196            std::fs::metadata(entry).is_ok_and(|metadata| !metadata.permissions().readonly())
1197        })
1198    })
1199}
1200
1201/// Re-enables a pre-v2 `telemetry.enabled = false` that carries no explicit
1202/// preference. Returns `None` when there is nothing to reset, including every
1203/// explicit choice (`explicitly_disabled` stays off).
1204pub(super) fn reset_legacy_telemetry_opt_out(raw: &str) -> Option<String> {
1205    let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
1206    let telemetry = document.get("telemetry")?;
1207    let disabled = telemetry.get("enabled").and_then(toml_edit::Item::as_bool) == Some(false);
1208    let implicit = matches!(
1209        telemetry.get("preference").map(toml_edit::Item::as_str),
1210        None | Some(Some("default_on"))
1211    );
1212    if !(disabled && implicit) {
1213        return None;
1214    }
1215    document["telemetry"]["enabled"] = toml_edit::value(true);
1216    Some(document.to_string())
1217}
1218
1219fn migrate_legacy_contribute_document(raw: &str, preserve_opt_out: bool) -> Option<String> {
1220    let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
1221    document["cloud"]["contribute_enabled"] = toml_edit::value(false);
1222    if !preserve_opt_out {
1223        document["telemetry"]["enabled"] = toml_edit::value(true);
1224        document["telemetry"]["preference"] = toml_edit::value("explicitly_enabled");
1225    }
1226    Some(document.to_string())
1227}
1228
1229#[cfg(test)]
1230mod telemetry_migration_tests {
1231    use super::*;
1232
1233    #[test]
1234    #[cfg(unix)]
1235    fn automatic_migration_respects_readonly_file_and_directory() {
1236        use std::os::unix::fs::PermissionsExt;
1237        let directory = tempfile::tempdir().expect("migration directory");
1238        let path = directory.path().join("config.toml");
1239        std::fs::write(&path, "ultra_compact = true\n").expect("legacy config");
1240        assert!(allows_automatic_config_migration(&path));
1241        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap();
1242        let readonly_file = allows_automatic_config_migration(&path);
1243        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
1244        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o500)).unwrap();
1245        let readonly_directory = allows_automatic_config_migration(&path);
1246        std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
1247        assert!(!readonly_file);
1248        assert!(!readonly_directory);
1249        assert!(!allows_automatic_config_migration(
1250            &directory.path().join("missing.toml")
1251        ));
1252    }
1253
1254    #[test]
1255    fn legacy_opt_in_becomes_explicit_and_send_eligible() {
1256        let migrated = migrate_legacy_contribute_document(
1257            "# keep me\n[cloud]\ncontribute_enabled = true\n",
1258            false,
1259        )
1260        .expect("valid TOML");
1261        assert!(migrated.contains("# keep me"));
1262        let cfg: Config = toml::from_str(&migrated).expect("migrated config");
1263        assert!(!cfg.cloud.contribute_enabled);
1264        assert!(cfg.telemetry.enabled);
1265        assert_eq!(
1266            cfg.telemetry.preference,
1267            super::super::TelemetryPreference::ExplicitlyEnabled
1268        );
1269        assert!(cfg.telemetry.send_eligible(None, None));
1270    }
1271
1272    #[test]
1273    fn legacy_contribute_never_overrides_explicit_opt_out() {
1274        let migrated = migrate_legacy_contribute_document(
1275            "[cloud]\ncontribute_enabled = true\n[telemetry]\nenabled = false\n",
1276            true,
1277        )
1278        .expect("valid TOML");
1279        let cfg: Config = toml::from_str(&migrated).expect("migrated config");
1280        assert!(!cfg.cloud.contribute_enabled);
1281        assert!(cfg.telemetry.explicitly_disabled());
1282    }
1283}