1use 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
12static CONFIG_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
15
16thread_local! {
17 static IGNORE_ENV_PROFILE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20}
21
22pub(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
40pub(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
51pub(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
112static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
118
119#[must_use]
122pub fn last_config_parse_error() -> Option<String> {
123 LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
124}
125
126pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum ConfigLoadFailure {
149 Unreadable,
153 Invalid,
156}
157
158impl ConfigLoadFailure {
159 #[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
169pub(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 if !local.write_allow_paths.is_empty() {
202 local.write_allow_paths.clear();
203 withheld.push("write_allow_paths");
204 }
205 if !local.read_only_roots.is_empty() {
207 local.read_only_roots.clear();
208 withheld.push("read_only_roots");
209 }
210 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 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 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 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
295fn 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#[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
317pub 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 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 #[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 pub fn local_path(project_root: &str) -> PathBuf {
372 PathBuf::from(project_root).join(".lean-ctx.toml")
373 }
374
375 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 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 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 pub fn load() -> Self {
468 (*Self::load_arc()).clone()
469 }
470
471 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 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 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 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 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 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 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 if failure.is_none() {
608 cfg.migrate_v4_config_on_disk();
609 }
610 if let Some(managed) = &managed {
613 managed.apply_to_cloud(&mut cfg.cloud);
614 }
615 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 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 pub(crate) fn migrate_v4_config_on_disk(&mut self) {
664 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 let preserve_opt_out = if reenables {
686 self.telemetry.preference == super::TelemetryPreference::ExplicitlyDisabled
687 } else {
688 self.telemetry.explicitly_disabled()
689 };
690 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 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 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 pub fn load_global() -> Self {
913 Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
914 }
915
916 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 pub(super) fn load_global_from(path: &Path) -> Self {
945 Self::try_load_global_from(path).unwrap_or_default()
946 }
947}
948
949const CONFIG_MIGRATION_PAUSE_MARKER: &str = "config_migration_paused";
954
955pub(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#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct ConfigMigrationPause {
972 pub label: &'static str,
974 pub config: std::path::PathBuf,
975 pub backup: std::path::PathBuf,
976 pub receipt: std::path::PathBuf,
977 pub reason: String,
979 pub action: String,
981 pub original: Option<std::path::PathBuf>,
983}
984
985pub(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 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
1110pub 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
1119pub(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
1153pub(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 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
1191fn 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
1201pub(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}