1use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex};
7
8use super::{CognitiveMode, Config, ConfigCacheSlot, default_shell_allowlist};
9
10const CONFIG_PROFILE_ENV: &str = "LEAN_CTX_CONFIG_PROFILE";
11
12pub(super) fn environment_config_profile() -> Option<String> {
13 std::env::var(CONFIG_PROFILE_ENV)
14 .ok()
15 .map(|name| name.trim().to_string())
16 .filter(|name| !name.is_empty())
17}
18
19pub(super) fn parse_config_with_profile(
22 raw: &str,
23 explicit_profile: Option<&str>,
24) -> Result<Config, String> {
25 let migrated = Config::migrate_v3_compression_document(raw)?;
26 let raw = migrated.as_deref().unwrap_or(raw);
27 let mut value: toml::Value = toml::from_str(raw).map_err(|error| error.to_string())?;
28 let configured_profile = value.get("config_profile").and_then(toml::Value::as_str);
29 let selected = explicit_profile
30 .map(str::trim)
31 .filter(|name| !name.is_empty())
32 .or(configured_profile);
33
34 if let Some(name) = selected {
35 let profiles = value
36 .get("profiles")
37 .and_then(toml::Value::as_table)
38 .ok_or_else(|| format!("config profile '{name}' selected but [profiles] is missing"))?;
39 let mut overlay = profiles
40 .get(name)
41 .and_then(toml::Value::as_table)
42 .cloned()
43 .ok_or_else(|| format!("config profile '{name}' is not defined"))?;
44 if overlay.remove("profiles").is_some() || overlay.remove("config_profile").is_some() {
45 return Err(format!(
46 "config profile '{name}' cannot override reserved profile keys"
47 ));
48 }
49 merge_toml_tables(
50 value
51 .as_table_mut()
52 .expect("a TOML document always has a root table"),
53 overlay,
54 );
55 }
56
57 value.try_into().map_err(|error| error.to_string())
58}
59
60fn merge_toml_tables(base: &mut toml::Table, overlay: toml::Table) {
61 for (key, overlay_value) in overlay {
62 match (base.get_mut(&key), overlay_value) {
63 (Some(toml::Value::Table(base_table)), toml::Value::Table(overlay_table)) => {
64 merge_toml_tables(base_table, overlay_table);
65 }
66 (_, replacement) => {
67 base.insert(key, replacement);
68 }
69 }
70 }
71}
72
73static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
79
80#[must_use]
83pub fn last_config_parse_error() -> Option<String> {
84 LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
85}
86
87fn record_parse_error(err: Option<String>) {
88 if let Ok(mut guard) = LAST_PARSE_ERROR.lock() {
89 *guard = err;
90 }
91}
92
93pub(crate) fn strip_sensitive_overrides(local: &mut Config) -> Vec<&'static str> {
106 let mut withheld: Vec<&'static str> = Vec::new();
107
108 if local.shell_allowlist != default_shell_allowlist() {
109 local.shell_allowlist = default_shell_allowlist();
110 withheld.push("shell_allowlist");
111 }
112 if !local.shell_allowlist_extra.is_empty() {
113 local.shell_allowlist_extra.clear();
114 withheld.push("shell_allowlist_extra");
115 }
116 if !local.allow_paths.is_empty() {
117 local.allow_paths.clear();
118 withheld.push("allow_paths");
119 }
120 if !local.extra_roots.is_empty() {
121 local.extra_roots.clear();
122 withheld.push("extra_roots");
123 }
124 if !local.allow_symlink_roots.is_empty() {
125 local.allow_symlink_roots.clear();
126 withheld.push("allow_symlink_roots");
127 }
128 if !local.custom_aliases.is_empty() {
129 local.custom_aliases.clear();
130 withheld.push("custom_aliases");
131 }
132 if !local.passthrough_urls.is_empty() {
133 local.passthrough_urls.clear();
134 withheld.push("passthrough_urls");
135 }
136 if local.proxy.anthropic_upstream.is_some()
137 || local.proxy.openai_upstream.is_some()
138 || local.proxy.chatgpt_upstream.is_some()
139 || local.proxy.gemini_upstream.is_some()
140 {
141 local.proxy.anthropic_upstream = None;
142 local.proxy.openai_upstream = None;
143 local.proxy.chatgpt_upstream = None;
144 local.proxy.gemini_upstream = None;
145 withheld.push("proxy.*_upstream");
146 }
147 if local.semantic_mode == super::SemanticMode::Eager {
150 local.semantic_mode = super::SemanticMode::default();
151 withheld.push("semantic_mode");
152 }
153 if local.rules_scope.is_some() {
154 local.rules_scope = None;
155 withheld.push("rules_scope");
156 }
157 if local.rules_injection.is_some() {
158 local.rules_injection = None;
159 withheld.push("rules_injection");
160 }
161 if local.permission_inheritance.is_some() {
162 local.permission_inheritance = None;
163 withheld.push("permission_inheritance");
164 }
165 if !local.disabled_tools.is_empty() {
166 local.disabled_tools.clear();
167 withheld.push("disabled_tools");
168 }
169 if local.tool_profile.is_some() {
170 local.tool_profile = None;
171 withheld.push("tool_profile");
172 }
173 if !local.tools_enabled.is_empty() {
174 local.tools_enabled.clear();
175 withheld.push("tools_enabled");
176 }
177 if !local.default_tool_categories.is_empty() {
178 local.default_tool_categories.clear();
179 withheld.push("default_tool_categories");
180 }
181 if !local.index.respect_gitignore {
182 local.index.respect_gitignore = true;
183 withheld.push("index.respect_gitignore");
184 }
185 if !local.shell_allowlist_subcommand_scoping {
186 local.shell_allowlist_subcommand_scoping = true;
187 withheld.push("shell_allowlist_subcommand_scoping");
188 }
189
190 withheld
191}
192
193#[must_use]
198pub fn local_sensitive_overrides(local_toml: &str) -> Vec<&'static str> {
199 let selected = environment_config_profile();
200 match parse_config_with_profile(local_toml, selected.as_deref()) {
201 Ok(mut parsed) => strip_sensitive_overrides(&mut parsed),
202 Err(_) => Vec::new(),
203 }
204}
205
206impl Config {
207 pub fn path() -> Option<PathBuf> {
212 crate::core::paths::config_dir_read_only()
213 .ok()
214 .map(|d| d.join("config.toml"))
215 }
216
217 #[must_use]
228 pub fn missing_config_path() -> Option<PathBuf> {
229 match Self::path() {
230 Some(p) if !p.exists() => Some(p),
231 _ => None,
232 }
233 }
234
235 pub fn local_path(project_root: &str) -> PathBuf {
237 PathBuf::from(project_root).join(".lean-ctx.toml")
238 }
239
240 pub(crate) fn find_project_root() -> Option<String> {
245 static ROOT_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
246 ROOT_CACHE
247 .get_or_init(Self::find_project_root_inner)
248 .clone()
249 }
250
251 fn find_project_root_inner() -> Option<String> {
252 if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
253 && !env_root.is_empty()
254 {
255 return Some(env_root);
256 }
257
258 let cwd = std::env::current_dir().ok();
259
260 if let Some(root) =
261 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
262 {
263 let root_path = std::path::Path::new(&root);
264 let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
265 let has_marker = crate::core::pathutil::has_project_marker(root_path);
270
271 if (cwd_is_under_root || has_marker) && crate::core::pathutil::may_probe_path(root_path)
272 {
273 return Some(root);
274 }
275 }
276
277 if let Some(ref cwd) = cwd {
278 let may_probe_cwd = crate::core::pathutil::may_probe_path(cwd);
282 let git_root = if may_probe_cwd {
283 std::process::Command::new("git")
284 .args(["rev-parse", "--show-toplevel"])
285 .current_dir(cwd)
286 .stdout(std::process::Stdio::piped())
287 .stderr(std::process::Stdio::null())
288 .output()
289 .ok()
290 .and_then(|o| {
291 if o.status.success() {
292 String::from_utf8(o.stdout)
293 .ok()
294 .map(|s| s.trim().to_string())
295 } else {
296 None
297 }
298 })
299 } else {
300 None
301 };
302 if let Some(root) = git_root {
303 return Some(root);
304 }
305 if may_probe_cwd && !crate::core::pathutil::is_broad_or_unsafe_root(cwd) {
306 return Some(cwd.to_string_lossy().to_string());
307 }
308 }
309 None
310 }
311
312 pub fn load() -> Self {
323 (*Self::load_arc()).clone()
324 }
325
326 pub fn load_arc() -> Arc<Self> {
333 static CACHE: Mutex<ConfigCacheSlot> = Mutex::new(None);
334
335 let Some(path) = Self::path() else {
336 return Arc::new(Self::default());
337 };
338
339 let project_root = Self::find_project_root();
340 let local_path = project_root.as_deref().map(Self::local_path);
341
342 let global_content = std::fs::read_to_string(&path).ok();
344 let local_content = local_path
349 .as_ref()
350 .filter(|p| crate::core::pathutil::may_probe_path(p.as_path()))
351 .and_then(|p| std::fs::read_to_string(p).ok());
352
353 let global_hash = global_content.as_deref().map(crate::core::hasher::hash_str);
354 let local_hash = local_content.as_deref().map(crate::core::hasher::hash_str);
355 let selected_profile = environment_config_profile();
356
357 if let Ok(guard) = CACHE.lock()
358 && let Some((ref cfg, ref cached_global, ref cached_local, ref cached_profile)) = *guard
359 && *cached_global == global_hash
360 && *cached_local == local_hash
361 && *cached_profile == selected_profile
362 {
363 return Arc::clone(cfg);
364 }
365
366 let mut cfg: Config = if let Some(ref content) = global_content {
367 match parse_config_with_profile(content, selected_profile.as_deref()) {
368 Ok(c) => {
369 record_parse_error(None);
370 c
371 }
372 Err(e) => {
373 record_parse_error(Some(e.clone()));
374 tracing::warn!("config parse error in {}: {e}", path.display());
375 eprintln!(
376 "\x1b[33m[lean-ctx] WARNING: config parse error in {}: {e}\n \
377 Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
378 path.display()
379 );
380 Self::default()
381 }
382 }
383 } else {
384 record_parse_error(None);
385 Self::default()
386 };
387
388 if let Some(ref local) = local_content {
389 let trusted = project_root.as_deref().is_some_and(|r| {
395 crate::core::workspace_trust::is_trusted_for(
396 std::path::Path::new(r),
397 local_hash.as_deref().unwrap_or_default(),
398 )
399 });
400 cfg.merge_local(local, trusted);
401 }
402
403 cfg.migrate_v4_config_on_disk();
404
405 let cfg = Arc::new(cfg);
406 if let Ok(mut guard) = CACHE.lock() {
407 *guard = Some((Arc::clone(&cfg), global_hash, local_hash, selected_profile));
408 }
409
410 cfg
411 }
412
413 pub fn load_for_project_root(project_root: &str) -> Self {
419 let selected_profile = environment_config_profile();
420 let mut cfg = Self::path()
421 .and_then(|p| std::fs::read_to_string(p).ok())
422 .and_then(|c| parse_config_with_profile(&c, selected_profile.as_deref()).ok())
423 .unwrap_or_default();
424 let local_path = Self::local_path(project_root);
425 if crate::core::pathutil::may_probe_path(local_path.as_path())
426 && let Ok(local) = std::fs::read_to_string(&local_path)
427 {
428 let trusted = crate::core::workspace_trust::is_trusted_for(
429 std::path::Path::new(project_root),
430 &crate::core::hasher::hash_str(&local),
431 );
432 cfg.merge_local(&local, trusted);
433 }
434 cfg
435 }
436
437 pub(crate) fn migrate_v4_config_on_disk(&mut self) {
442 let path = Self::path();
447 let writable = path
448 .as_deref()
449 .is_some_and(allows_automatic_config_migration);
450 let raw = path
451 .as_deref()
452 .filter(|_| writable)
453 .and_then(|path| std::fs::read_to_string(path).ok());
454 let reset_pending = crate::core::telemetry_consent::legacy_opt_out_reset_pending();
455 let reset = raw
456 .as_deref()
457 .filter(|_| reset_pending)
458 .and_then(reset_legacy_telemetry_opt_out);
459 if reset.is_some() && self.telemetry.preference == super::TelemetryPreference::DefaultOn {
460 self.telemetry.enabled = true;
461 }
462 let preserve_opt_out = self.telemetry.explicitly_disabled();
463 if self.cloud.contribute_enabled {
464 self.cloud.contribute_enabled = false;
465 if !preserve_opt_out {
466 self.telemetry.enabled = true;
467 self.telemetry.preference = super::TelemetryPreference::ExplicitlyEnabled;
468 }
469 }
470 if matches!(self.cognitive_mode, CognitiveMode::Basic) {
471 self.cognitive_mode = CognitiveMode::Full;
472 }
473 let Some(path) = path else {
474 return;
475 };
476 let Some(raw) = raw else {
477 if !writable {
478 tracing::debug!(
479 "config migration remains in memory: source or directory is read-only"
480 );
481 }
482 if reset_pending && !path.exists() {
484 crate::core::telemetry_consent::mark_legacy_opt_out_reset();
485 }
486 return;
487 };
488 let source = reset.as_deref().unwrap_or(&raw);
489 let migrated = match Self::migrate_v4_config_document(
490 source,
491 environment_config_profile().as_deref(),
492 preserve_opt_out,
493 ) {
494 Ok(Some(updated)) => Some(updated),
495 Ok(None) => (source != raw).then(|| source.to_string()),
496 Err(error) => {
497 tracing::warn!("config migration failed: {error}");
498 return;
499 }
500 };
501 let persisted = match migrated {
502 Some(updated) => crate::config_io::write_atomic_config_migration_checked(
503 &path,
504 &updated,
505 Some(raw.as_bytes()),
506 )
507 .map_err(|error| tracing::warn!("config migration could not be persisted: {error}"))
508 .is_ok(),
509 None => true,
510 };
511 if persisted && reset_pending {
512 crate::core::telemetry_consent::mark_legacy_opt_out_reset();
513 }
514 }
515
516 pub(super) fn migrate_v4_config_document(
517 raw: &str,
518 selected_profile: Option<&str>,
519 preserve_opt_out: bool,
520 ) -> Result<Option<String>, String> {
521 let document = raw
522 .parse::<toml_edit::DocumentMut>()
523 .map_err(|error| error.to_string())?;
524 let legacy_telemetry = document
525 .get("cloud")
526 .and_then(|table| table.get("contribute_enabled"))
527 .and_then(toml_edit::Item::as_bool)
528 == Some(true);
529 let persisted_opt_out = document
530 .get("telemetry")
531 .and_then(|table| table.get("enabled"))
532 .and_then(toml_edit::Item::as_bool)
533 == Some(false);
534 let mut updated = if legacy_telemetry {
535 migrate_legacy_contribute_document(raw, preserve_opt_out || persisted_opt_out)
536 .ok_or_else(|| "invalid legacy telemetry configuration".to_string())?
537 } else {
538 raw.to_string()
539 };
540 if let Some(next) = Self::validated_v3_compression_document(&updated, selected_profile)? {
541 updated = next;
542 }
543 let mut document = updated
544 .parse::<toml_edit::DocumentMut>()
545 .map_err(|error| error.to_string())?;
546 if document
547 .get("cognitive_mode")
548 .and_then(toml_edit::Item::as_str)
549 == Some("basic")
550 {
551 document["cognitive_mode"] = toml_edit::value("full");
552 updated = document.to_string();
553 }
554 parse_config_with_profile(&updated, selected_profile)?;
555 Ok((updated != raw).then_some(updated))
556 }
557
558 pub(crate) fn validated_v3_compression_document(
559 raw: &str,
560 selected_profile: Option<&str>,
561 ) -> Result<Option<String>, String> {
562 let migrated = Self::migrate_v3_compression_document(raw)?;
563 if let Some(ref updated) = migrated {
564 parse_config_with_profile(updated, selected_profile)?;
565 }
566 Ok(migrated)
567 }
568
569 pub(crate) fn migrate_v3_compression_document(raw: &str) -> Result<Option<String>, String> {
570 fn migrate_table(table: &mut toml_edit::Table) -> Result<bool, String> {
571 let has_legacy = ["terse_agent", "output_density", "ultra_compact"]
572 .iter()
573 .any(|key| table.get(key).is_some());
574 if !has_legacy {
575 return Ok(false);
576 }
577
578 let terse = match table.get("terse_agent") {
579 Some(item) => Some(
580 item.as_str()
581 .ok_or_else(|| "terse_agent must be a string".to_string())?,
582 ),
583 None => None,
584 };
585 if terse.is_some_and(|value| !matches!(value, "off" | "lite" | "full" | "ultra")) {
586 return Err("invalid terse_agent".to_string());
587 }
588 let density = match table.get("output_density") {
589 Some(item) => Some(
590 item.as_str()
591 .ok_or_else(|| "output_density must be a string".to_string())?,
592 ),
593 None => None,
594 };
595 if density.is_some_and(|value| !matches!(value, "normal" | "terse" | "ultra")) {
596 return Err("invalid output_density".to_string());
597 }
598 let ultra = match table.get("ultra_compact") {
599 Some(item) => Some(
600 item.as_bool()
601 .ok_or_else(|| "ultra_compact must be a boolean".to_string())?,
602 ),
603 None => None,
604 };
605
606 let level = if let Some(item) = table.get("compression_level") {
607 let value = item
608 .as_str()
609 .ok_or_else(|| "compression_level must be a string".to_string())?;
610 if !matches!(value, "off" | "lite" | "standard" | "max" | "raw") {
611 return Err(format!("invalid compression_level: {value}"));
612 }
613 value
614 } else if ultra == Some(true) || terse == Some("ultra") || density == Some("ultra") {
615 "max"
616 } else if terse == Some("full") {
617 "standard"
618 } else if terse == Some("lite") || density == Some("terse") {
619 "lite"
620 } else {
621 "off"
622 };
623
624 table["compression_level"] = toml_edit::value(level);
625 for key in ["terse_agent", "output_density", "ultra_compact"] {
626 table.remove(key);
627 }
628 Ok(true)
629 }
630
631 let mut document = raw
632 .parse::<toml_edit::DocumentMut>()
633 .map_err(|error| error.to_string())?;
634 let mut changed = migrate_table(document.as_table_mut())?;
635 if let Some(profiles) = document
636 .get_mut("profiles")
637 .and_then(toml_edit::Item::as_table_mut)
638 {
639 for (_, profile) in profiles.iter_mut() {
640 if let Some(table) = profile.as_table_mut() {
641 changed |= migrate_table(table)?;
642 }
643 }
644 }
645 Ok(changed.then(|| document.to_string()))
646 }
647
648 pub fn load_global() -> Self {
657 Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
658 }
659
660 pub fn try_load_global() -> Result<Self, super::error::LeanCtxError> {
665 let path = Self::path().ok_or_else(|| {
666 super::error::LeanCtxError::Config("cannot determine home directory".into())
667 })?;
668 Self::try_load_global_from(&path)
669 }
670
671 pub(super) fn try_load_global_from(path: &Path) -> Result<Self, super::error::LeanCtxError> {
672 match std::fs::read_to_string(path) {
673 Ok(raw) if !raw.trim().is_empty() => toml::from_str(&raw).map_err(|error| {
674 super::error::LeanCtxError::Config(
675 format!("refusing invalid global config.toml ({error})").into(),
676 )
677 }),
678 Ok(_) => Ok(Self::default()),
679 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
680 Err(error) => Err(error.into()),
681 }
682 }
683
684 pub(super) fn load_global_from(path: &Path) -> Self {
689 Self::try_load_global_from(path).unwrap_or_default()
690 }
691}
692
693fn allows_automatic_config_migration(path: &Path) -> bool {
696 path.parent().is_some_and(|parent| {
697 [path, parent].iter().all(|entry| {
698 std::fs::metadata(entry).is_ok_and(|metadata| !metadata.permissions().readonly())
699 })
700 })
701}
702
703pub(super) fn reset_legacy_telemetry_opt_out(raw: &str) -> Option<String> {
707 let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
708 let telemetry = document.get("telemetry")?;
709 let disabled = telemetry.get("enabled").and_then(toml_edit::Item::as_bool) == Some(false);
710 let implicit = matches!(
711 telemetry.get("preference").map(toml_edit::Item::as_str),
712 None | Some(Some("default_on"))
713 );
714 if !(disabled && implicit) {
715 return None;
716 }
717 document["telemetry"]["enabled"] = toml_edit::value(true);
718 Some(document.to_string())
719}
720
721fn migrate_legacy_contribute_document(raw: &str, preserve_opt_out: bool) -> Option<String> {
722 let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
723 document["cloud"]["contribute_enabled"] = toml_edit::value(false);
724 if !preserve_opt_out {
725 document["telemetry"]["enabled"] = toml_edit::value(true);
726 document["telemetry"]["preference"] = toml_edit::value("explicitly_enabled");
727 }
728 Some(document.to_string())
729}
730
731#[cfg(test)]
732mod telemetry_migration_tests {
733 use super::*;
734
735 #[test]
736 #[cfg(unix)]
737 fn automatic_migration_respects_readonly_file_and_directory() {
738 use std::os::unix::fs::PermissionsExt;
739 let directory = tempfile::tempdir().expect("migration directory");
740 let path = directory.path().join("config.toml");
741 std::fs::write(&path, "ultra_compact = true\n").expect("legacy config");
742 assert!(allows_automatic_config_migration(&path));
743 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap();
744 let readonly_file = allows_automatic_config_migration(&path);
745 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
746 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o500)).unwrap();
747 let readonly_directory = allows_automatic_config_migration(&path);
748 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
749 assert!(!readonly_file);
750 assert!(!readonly_directory);
751 assert!(!allows_automatic_config_migration(
752 &directory.path().join("missing.toml")
753 ));
754 }
755
756 #[test]
757 fn legacy_opt_in_becomes_explicit_and_send_eligible() {
758 let migrated = migrate_legacy_contribute_document(
759 "# keep me\n[cloud]\ncontribute_enabled = true\n",
760 false,
761 )
762 .expect("valid TOML");
763 assert!(migrated.contains("# keep me"));
764 let cfg: Config = toml::from_str(&migrated).expect("migrated config");
765 assert!(!cfg.cloud.contribute_enabled);
766 assert!(cfg.telemetry.enabled);
767 assert_eq!(
768 cfg.telemetry.preference,
769 super::super::TelemetryPreference::ExplicitlyEnabled
770 );
771 assert!(cfg.telemetry.send_eligible(None, None));
772 }
773
774 #[test]
775 fn legacy_contribute_never_overrides_explicit_opt_out() {
776 let migrated = migrate_legacy_contribute_document(
777 "[cloud]\ncontribute_enabled = true\n[telemetry]\nenabled = false\n",
778 true,
779 )
780 .expect("valid TOML");
781 let cfg: Config = toml::from_str(&migrated).expect("migrated config");
782 assert!(!cfg.cloud.contribute_enabled);
783 assert!(cfg.telemetry.explicitly_disabled());
784 }
785}