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
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
19pub(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
30pub(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
91static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
97
98#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum ConfigLoadFailure {
119 Unreadable,
123 Invalid,
126}
127
128impl ConfigLoadFailure {
129 #[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
139pub(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 if !local.write_allow_paths.is_empty() {
172 local.write_allow_paths.clear();
173 withheld.push("write_allow_paths");
174 }
175 if !local.read_only_roots.is_empty() {
177 local.read_only_roots.clear();
178 withheld.push("read_only_roots");
179 }
180 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 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 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 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
265fn 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#[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 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 #[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 pub fn local_path(project_root: &str) -> PathBuf {
318 PathBuf::from(project_root).join(".lean-ctx.toml")
319 }
320
321 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 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 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 pub fn load() -> Self {
414 (*Self::load_arc()).clone()
415 }
416
417 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 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 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 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 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 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 if failure.is_none() {
541 cfg.migrate_v4_config_on_disk();
542 }
543 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 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 pub(crate) fn migrate_v4_config_on_disk(&mut self) {
590 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 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 pub fn load_global() -> Self {
794 Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
795 }
796
797 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 pub(super) fn load_global_from(path: &Path) -> Self {
826 Self::try_load_global_from(path).unwrap_or_default()
827 }
828}
829
830fn 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
840pub(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}