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 preserve_opt_out = self.telemetry.explicitly_disabled();
443 if self.cloud.contribute_enabled {
444 self.cloud.contribute_enabled = false;
445 if !preserve_opt_out {
446 self.telemetry.enabled = true;
447 self.telemetry.preference = super::TelemetryPreference::ExplicitlyEnabled;
448 }
449 }
450 if matches!(self.cognitive_mode, CognitiveMode::Basic) {
451 self.cognitive_mode = CognitiveMode::Full;
452 }
453 let Some(path) = Self::path() else {
454 return;
455 };
456 if !allows_automatic_config_migration(&path) {
457 tracing::debug!("config migration remains in memory: source or directory is read-only");
458 return;
459 }
460 let Ok(raw) = std::fs::read_to_string(&path) else {
461 return;
462 };
463 match Self::migrate_v4_config_document(
464 &raw,
465 environment_config_profile().as_deref(),
466 preserve_opt_out,
467 ) {
468 Ok(Some(updated)) => {
469 if let Err(error) = crate::config_io::write_atomic_config_migration_checked(
470 &path,
471 &updated,
472 Some(raw.as_bytes()),
473 ) {
474 tracing::warn!("config migration could not be persisted: {error}");
475 }
476 }
477 Ok(None) => {}
478 Err(error) => tracing::warn!("config migration failed: {error}"),
479 }
480 }
481
482 pub(super) fn migrate_v4_config_document(
483 raw: &str,
484 selected_profile: Option<&str>,
485 preserve_opt_out: bool,
486 ) -> Result<Option<String>, String> {
487 let document = raw
488 .parse::<toml_edit::DocumentMut>()
489 .map_err(|error| error.to_string())?;
490 let legacy_telemetry = document
491 .get("cloud")
492 .and_then(|table| table.get("contribute_enabled"))
493 .and_then(toml_edit::Item::as_bool)
494 == Some(true);
495 let persisted_opt_out = document
496 .get("telemetry")
497 .and_then(|table| table.get("enabled"))
498 .and_then(toml_edit::Item::as_bool)
499 == Some(false);
500 let mut updated = if legacy_telemetry {
501 migrate_legacy_contribute_document(raw, preserve_opt_out || persisted_opt_out)
502 .ok_or_else(|| "invalid legacy telemetry configuration".to_string())?
503 } else {
504 raw.to_string()
505 };
506 if let Some(next) = Self::validated_v3_compression_document(&updated, selected_profile)? {
507 updated = next;
508 }
509 let mut document = updated
510 .parse::<toml_edit::DocumentMut>()
511 .map_err(|error| error.to_string())?;
512 if document
513 .get("cognitive_mode")
514 .and_then(toml_edit::Item::as_str)
515 == Some("basic")
516 {
517 document["cognitive_mode"] = toml_edit::value("full");
518 updated = document.to_string();
519 }
520 parse_config_with_profile(&updated, selected_profile)?;
521 Ok((updated != raw).then_some(updated))
522 }
523
524 pub(crate) fn validated_v3_compression_document(
525 raw: &str,
526 selected_profile: Option<&str>,
527 ) -> Result<Option<String>, String> {
528 let migrated = Self::migrate_v3_compression_document(raw)?;
529 if let Some(ref updated) = migrated {
530 parse_config_with_profile(updated, selected_profile)?;
531 }
532 Ok(migrated)
533 }
534
535 pub(crate) fn migrate_v3_compression_document(raw: &str) -> Result<Option<String>, String> {
536 fn migrate_table(table: &mut toml_edit::Table) -> Result<bool, String> {
537 let has_legacy = ["terse_agent", "output_density", "ultra_compact"]
538 .iter()
539 .any(|key| table.get(key).is_some());
540 if !has_legacy {
541 return Ok(false);
542 }
543
544 let terse = match table.get("terse_agent") {
545 Some(item) => Some(
546 item.as_str()
547 .ok_or_else(|| "terse_agent must be a string".to_string())?,
548 ),
549 None => None,
550 };
551 if terse.is_some_and(|value| !matches!(value, "off" | "lite" | "full" | "ultra")) {
552 return Err("invalid terse_agent".to_string());
553 }
554 let density = match table.get("output_density") {
555 Some(item) => Some(
556 item.as_str()
557 .ok_or_else(|| "output_density must be a string".to_string())?,
558 ),
559 None => None,
560 };
561 if density.is_some_and(|value| !matches!(value, "normal" | "terse" | "ultra")) {
562 return Err("invalid output_density".to_string());
563 }
564 let ultra = match table.get("ultra_compact") {
565 Some(item) => Some(
566 item.as_bool()
567 .ok_or_else(|| "ultra_compact must be a boolean".to_string())?,
568 ),
569 None => None,
570 };
571
572 let level = if let Some(item) = table.get("compression_level") {
573 let value = item
574 .as_str()
575 .ok_or_else(|| "compression_level must be a string".to_string())?;
576 if !matches!(value, "off" | "lite" | "standard" | "max" | "raw") {
577 return Err(format!("invalid compression_level: {value}"));
578 }
579 value
580 } else if ultra == Some(true) || terse == Some("ultra") || density == Some("ultra") {
581 "max"
582 } else if terse == Some("full") {
583 "standard"
584 } else if terse == Some("lite") || density == Some("terse") {
585 "lite"
586 } else {
587 "off"
588 };
589
590 table["compression_level"] = toml_edit::value(level);
591 for key in ["terse_agent", "output_density", "ultra_compact"] {
592 table.remove(key);
593 }
594 Ok(true)
595 }
596
597 let mut document = raw
598 .parse::<toml_edit::DocumentMut>()
599 .map_err(|error| error.to_string())?;
600 let mut changed = migrate_table(document.as_table_mut())?;
601 if let Some(profiles) = document
602 .get_mut("profiles")
603 .and_then(toml_edit::Item::as_table_mut)
604 {
605 for (_, profile) in profiles.iter_mut() {
606 if let Some(table) = profile.as_table_mut() {
607 changed |= migrate_table(table)?;
608 }
609 }
610 }
611 Ok(changed.then(|| document.to_string()))
612 }
613
614 pub fn load_global() -> Self {
623 Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
624 }
625
626 pub fn try_load_global() -> Result<Self, super::error::LeanCtxError> {
631 let path = Self::path().ok_or_else(|| {
632 super::error::LeanCtxError::Config("cannot determine home directory".into())
633 })?;
634 Self::try_load_global_from(&path)
635 }
636
637 pub(super) fn try_load_global_from(path: &Path) -> Result<Self, super::error::LeanCtxError> {
638 match std::fs::read_to_string(path) {
639 Ok(raw) if !raw.trim().is_empty() => toml::from_str(&raw).map_err(|error| {
640 super::error::LeanCtxError::Config(
641 format!("refusing invalid global config.toml ({error})").into(),
642 )
643 }),
644 Ok(_) => Ok(Self::default()),
645 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
646 Err(error) => Err(error.into()),
647 }
648 }
649
650 pub(super) fn load_global_from(path: &Path) -> Self {
655 Self::try_load_global_from(path).unwrap_or_default()
656 }
657}
658
659fn allows_automatic_config_migration(path: &Path) -> bool {
662 path.parent().is_some_and(|parent| {
663 [path, parent].iter().all(|entry| {
664 std::fs::metadata(entry).is_ok_and(|metadata| !metadata.permissions().readonly())
665 })
666 })
667}
668
669fn migrate_legacy_contribute_document(raw: &str, preserve_opt_out: bool) -> Option<String> {
670 let mut document = raw.parse::<toml_edit::DocumentMut>().ok()?;
671 document["cloud"]["contribute_enabled"] = toml_edit::value(false);
672 if !preserve_opt_out {
673 document["telemetry"]["enabled"] = toml_edit::value(true);
674 document["telemetry"]["preference"] = toml_edit::value("explicitly_enabled");
675 }
676 Some(document.to_string())
677}
678
679#[cfg(test)]
680mod telemetry_migration_tests {
681 use super::*;
682
683 #[test]
684 #[cfg(unix)]
685 fn automatic_migration_respects_readonly_file_and_directory() {
686 use std::os::unix::fs::PermissionsExt;
687 let directory = tempfile::tempdir().expect("migration directory");
688 let path = directory.path().join("config.toml");
689 std::fs::write(&path, "ultra_compact = true\n").expect("legacy config");
690 assert!(allows_automatic_config_migration(&path));
691 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap();
692 let readonly_file = allows_automatic_config_migration(&path);
693 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
694 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o500)).unwrap();
695 let readonly_directory = allows_automatic_config_migration(&path);
696 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
697 assert!(!readonly_file);
698 assert!(!readonly_directory);
699 assert!(!allows_automatic_config_migration(
700 &directory.path().join("missing.toml")
701 ));
702 }
703
704 #[test]
705 fn legacy_opt_in_becomes_explicit_and_send_eligible() {
706 let migrated = migrate_legacy_contribute_document(
707 "# keep me\n[cloud]\ncontribute_enabled = true\n",
708 false,
709 )
710 .expect("valid TOML");
711 assert!(migrated.contains("# keep me"));
712 let cfg: Config = toml::from_str(&migrated).expect("migrated config");
713 assert!(!cfg.cloud.contribute_enabled);
714 assert!(cfg.telemetry.enabled);
715 assert_eq!(
716 cfg.telemetry.preference,
717 super::super::TelemetryPreference::ExplicitlyEnabled
718 );
719 assert!(cfg.telemetry.send_eligible(None, None));
720 }
721
722 #[test]
723 fn legacy_contribute_never_overrides_explicit_opt_out() {
724 let migrated = migrate_legacy_contribute_document(
725 "[cloud]\ncontribute_enabled = true\n[telemetry]\nenabled = false\n",
726 true,
727 )
728 .expect("valid TOML");
729 let cfg: Config = toml::from_str(&migrated).expect("migrated config");
730 assert!(!cfg.cloud.contribute_enabled);
731 assert!(cfg.telemetry.explicitly_disabled());
732 }
733}