Skip to main content

vtcode_config/loader/manager/
mod.rs

1mod cache;
2mod inspect;
3mod migrate;
4mod persistence;
5mod repository;
6mod validation;
7
8use cache::{
9    RepositoryProviderSecurityViolation, canonicalize_workspace_root, push_unique_layer_source,
10    should_skip_optional_global_error,
11};
12#[cfg(not(test))]
13use cache::{cache_get, cache_insert, cache_remove, with_cache_mut};
14use migrate::migrate_custom_api_keys_if_needed;
15
16use std::collections::HashMap;
17use std::fmt;
18use std::fs;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, Mutex};
21
22use anyhow::{Context, Result, bail};
23
24use crate::api_keys::{api_key_env_var, credential_metadata_key, store_credential_with_mode};
25use crate::defaults::{self};
26use crate::hooks::{HooksConfig, LifecycleHooksConfig, WorkspaceHookCommand, WorkspaceLifecycleHooks};
27use crate::loader::config::VTCodeConfig;
28use crate::loader::layers::{
29    ConfigLayerEntry, ConfigLayerMetadata, ConfigLayerSource, ConfigLayerStack, LayerDisabledReason,
30};
31use crate::loader::session_override;
32use vtcode_commons::VtCodePaths;
33use vtcode_commons::canonicalize;
34
35/// Timing metrics (in microseconds) for configuration loading phases
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37pub struct ConfigPhaseTiming {
38    /// Duration of workspace path resolution (in microseconds)
39    pub path_resolution_us: u64,
40    /// Duration of layer probing and loading (in microseconds)
41    pub layer_loading_us: u64,
42    /// Duration of TOML merging and deserialization (in microseconds)
43    pub merge_and_parse_us: u64,
44    /// Duration of validation and API key migration (in microseconds)
45    pub validation_us: u64,
46}
47
48/// Configuration manager for loading and validating configurations
49#[derive(Clone)]
50pub struct ConfigManager {
51    pub(crate) config: VTCodeConfig,
52    pub(super) config_path: Option<PathBuf>,
53    pub(super) canonical_user_config_path: Option<PathBuf>,
54    pub(super) tracked_user_config_paths: Vec<PathBuf>,
55    write_global_config_to_canonical: bool,
56    /// Whether the associated file was explicitly selected by the user.
57    ///
58    /// Explicit files are trusted even when they are represented as a
59    /// workspace layer internally. Repository and project layers are not.
60    pub(super) explicit_config_is_trusted: bool,
61    pub(super) workspace_root: Option<PathBuf>,
62    pub(super) config_file_name: String,
63    pub(crate) layer_stack: ConfigLayerStack,
64    pub(super) phase_timing: Option<ConfigPhaseTiming>,
65}
66
67impl ConfigManager {
68    /// Load configuration from the default locations rooted at the current directory.
69    pub fn load() -> Result<Self> {
70        if let Some(override_path) = session_override::explicit_config_path() {
71            return Self::load_for_session(std::env::current_dir()?, &override_path).with_context(|| {
72                format!("Failed to load configuration from explicit path {}", override_path.display())
73            });
74        }
75
76        Self::load_from_workspace_with_repository_repair(std::env::current_dir()?)
77    }
78
79    /// Load configuration for an interactive session with an explicit config file.
80    ///
81    /// The explicit file takes the highest file-layer precedence (the same
82    /// position a workspace root `vtcode.toml` would occupy), while the
83    /// system/user global layers are still loaded underneath it. Unlike
84    /// [`Self::load_from_file`], the manager's `workspace_root` remains the
85    /// session workspace (not the explicit file's parent directory), so
86    /// workspace-relative config writes and project-level paths keep
87    /// resolving against the workspace.
88    pub fn load_for_session(workspace: impl AsRef<Path>, explicit_path: impl AsRef<Path>) -> Result<Self> {
89        let workspace = workspace.as_ref();
90        let explicit_path = explicit_path.as_ref();
91        #[cfg(not(test))]
92        let canonical_workspace = canonicalize_workspace_root(workspace);
93
94        #[cfg(not(test))]
95        if let Some(cached) = cache_get(&canonical_workspace) {
96            return Ok(cached.as_ref().clone());
97        }
98
99        let mut manager = Self::load_from_file_impl(explicit_path, false).with_context(|| {
100            format!(
101                "Failed to load explicit session config file {} (from --config / VTCODE_CONFIG_PATH)",
102                explicit_path.display()
103            )
104        })?;
105        // The session workspace, not the explicit file's parent, anchors
106        // workspace-relative config resolution for the rest of the session.
107        manager.workspace_root = Some(canonicalize_workspace_root(workspace));
108
109        #[cfg(not(test))]
110        cache_insert(canonical_workspace, Arc::new(manager.clone()));
111
112        Ok(manager)
113    }
114
115    /// Load only the system and user configuration layers.
116    ///
117    /// This is used by global configuration commands that must honor legacy
118    /// and XDG search precedence without accidentally importing the current
119    /// workspace's `vtcode.toml`.
120    pub fn load_global() -> Result<Self> {
121        let defaults_provider = defaults::current_config_defaults();
122        let config_file_name = defaults_provider.config_file_name().to_string();
123        let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
124        let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
125        if let Some(path) = &canonical_user_config_path
126            && !tracked_user_config_paths.iter().any(|existing| existing == path)
127        {
128            tracked_user_config_paths.push(path.clone());
129        }
130
131        let mut layer_sources = Vec::new();
132        for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
133            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
134        }
135        for home_config_path in &tracked_user_config_paths {
136            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
137        }
138
139        let mut layer_stack = ConfigLayerStack::default();
140        for source in layer_sources {
141            if let Some(layer) = Self::load_optional_layer(source) {
142                layer_stack.push(layer);
143            }
144        }
145
146        if let Some((layer, error)) = layer_stack.first_layer_error() {
147            bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
148        }
149
150        let (config, config_path) = if layer_stack.layers().is_empty() {
151            let config = VTCodeConfig::default();
152            config.validate().context("Default configuration failed validation")?;
153            (config, None)
154        } else {
155            let (effective_toml, origins) = layer_stack.effective_config_with_origins();
156            let mut config: VTCodeConfig = effective_toml
157                .try_into()
158                .context("Failed to deserialize effective global configuration")?;
159            Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
160            Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
161            Self::validate_sandbox_security_fields(&layer_stack, &origins, false)?;
162            config.validate().context("Global configuration failed validation")?;
163            config.workspace_lifecycle_hooks =
164                Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
165            let config_path = layer_stack
166                .layers()
167                .iter()
168                .rev()
169                .find(|layer| layer.is_enabled())
170                .and_then(|layer| match &layer.source {
171                    ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => Some(file.clone()),
172                    _ => None,
173                });
174            (config, config_path)
175        };
176
177        Ok(Self {
178            config,
179            config_path,
180            canonical_user_config_path,
181            tracked_user_config_paths,
182            write_global_config_to_canonical: false,
183            explicit_config_is_trusted: false,
184            workspace_root: None,
185            config_file_name,
186            layer_stack,
187            phase_timing: None,
188        })
189    }
190
191    /// Invalidate the cached configuration for a specific workspace.
192    ///
193    /// Call this when config files may have changed on disk and the next
194    /// `load_from_workspace` call should perform a fresh read instead of
195    /// returning a previously cached result.
196    pub fn invalidate_workspace_cache(workspace: impl AsRef<Path>) {
197        let workspace = workspace.as_ref();
198        #[cfg(not(test))]
199        {
200            let canonical_workspace = canonicalize_workspace_root(workspace);
201            cache_remove(&canonical_workspace);
202        }
203        #[cfg(test)]
204        let _ = workspace;
205    }
206
207    /// Invalidate every cached workspace configuration.
208    ///
209    /// Used when a session-scoped override changes or is cleared: the cache is
210    /// keyed by canonical workspace only, so an override-loaded manager for any
211    /// workspace must not leak into later default loads. This is a rare event
212    /// (startup and tests), so a full sweep is cheap and safe.
213    pub fn invalidate_all_workspace_cache() {
214        #[cfg(not(test))]
215        with_cache_mut(|map| map.clear());
216    }
217
218    /// Load configuration from a specific workspace
219    ///
220    /// When the session has an explicit config-file override (captured at
221    /// startup via [`session_override::set_explicit_config_path`]), the
222    /// override file takes precedence and is loaded as the highest file
223    /// layer above the default global layers.
224    pub fn load_from_workspace(workspace: impl AsRef<Path>) -> Result<Self> {
225        if let Some(override_path) = session_override::explicit_config_path() {
226            return Self::load_for_session(workspace, override_path);
227        }
228
229        let workspace = workspace.as_ref();
230        #[cfg(not(test))]
231        let canonical_workspace = canonicalize_workspace_root(workspace);
232
233        #[cfg(not(test))]
234        if let Some(cached) = cache_get(&canonical_workspace) {
235            return Ok(cached.as_ref().clone());
236        }
237
238        let manager = Self::load_from_workspace_impl(workspace)?;
239
240        #[cfg(not(test))]
241        cache_insert(canonical_workspace, Arc::new(manager.clone()));
242
243        Ok(manager)
244    }
245
246    /// Load a workspace configuration and repair provider settings left by
247    /// older versions that persisted the merged configuration into a
248    /// repository-controlled file.
249    ///
250    /// The strict loader still rejects repository-controlled provider
251    /// definitions and endpoint/credential overrides. This entry point only
252    /// handles that specific, already-validated violation by removing the
253    /// prohibited fields from the exact repository layer that introduced it,
254    /// then retrying the normal load. Explicit session files remain trusted
255    /// and are never repaired.
256    pub fn load_from_workspace_with_repository_repair(workspace: impl AsRef<Path>) -> Result<Self> {
257        let workspace = workspace.as_ref();
258        let mut error = match Self::load_from_workspace(workspace) {
259            Ok(manager) => return Ok(manager),
260            Err(error) => error,
261        };
262
263        // More than one repository layer can contain a stale flattened copy.
264        // Repair and retry until the strict loader succeeds or every known
265        // repository layer has had a chance to be cleaned.
266        let repository_paths = Self::repository_config_paths(workspace);
267        for _ in 0..=repository_paths.len() {
268            let Some(violation) = error.downcast_ref::<RepositoryProviderSecurityViolation>() else {
269                return Err(error);
270            };
271
272            let source = violation.source.clone();
273            let Some(path) = repository_paths
274                .iter()
275                .find(|candidate| Self::repository_source_matches_path(&source, candidate))
276            else {
277                return Err(error);
278            };
279
280            if !Self::repair_repository_config_file(path)? {
281                return Err(error);
282            }
283
284            tracing::warn!(
285                path = %path.display(),
286                "Removed prohibited provider settings left by an older repository configuration write"
287            );
288
289            Self::invalidate_workspace_cache(workspace);
290            match Self::load_from_workspace(workspace) {
291                Ok(manager) => return Ok(manager),
292                Err(next_error) => error = next_error,
293            }
294        }
295
296        Err(error).context("Failed to load workspace configuration after repairing prohibited provider settings")
297    }
298
299    fn load_from_workspace_impl(workspace: impl AsRef<Path>) -> Result<Self> {
300        let t0 = std::time::Instant::now();
301        let workspace = workspace.as_ref();
302        let defaults_provider = defaults::current_config_defaults();
303        let workspace_paths = defaults_provider.workspace_paths_for(workspace);
304        let workspace_root = canonicalize_workspace_root(workspace_paths.workspace_root());
305        let config_dir = workspace_paths.config_dir();
306        let config_file_name = defaults_provider.config_file_name().to_string();
307        let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
308        let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
309        if let Some(path) = &canonical_user_config_path
310            && !tracked_user_config_paths.iter().any(|existing| existing == path)
311        {
312            tracked_user_config_paths.push(path.clone());
313        }
314        let path_res_duration = t0.elapsed();
315
316        let t1 = std::time::Instant::now();
317
318        // Collect layer sources in precedence order so we can load them
319        // concurrently and then push results while preserving order.
320        let mut layer_sources: Vec<ConfigLayerSource> = Vec::with_capacity(8);
321
322        // 1. System configuration: /etc compatibility followed by
323        // XDG_CONFIG_DIRS candidates, all low-to-high precedence.
324        for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
325            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
326        }
327
328        // 2. Legacy user config followed by the canonical XDG user config.
329        for home_config_path in &tracked_user_config_paths {
330            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
331        }
332
333        // 3. Project-specific config (.vtcode/projects/<project>/config/vtcode.toml)
334        if let Some(project_config_path) = Self::project_config_path(&config_dir, &workspace_root, &config_file_name) {
335            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Project { file: project_config_path });
336        }
337
338        // 4. Config directory fallback (.vtcode/vtcode.toml)
339        let fallback_path = config_dir.join(&config_file_name);
340        let workspace_config_path = workspace_root.join(&config_file_name);
341        if fallback_path != workspace_config_path {
342            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Workspace { file: fallback_path });
343        }
344
345        // 5. Workspace config (vtcode.toml in workspace root)
346        push_unique_layer_source(
347            &mut layer_sources,
348            ConfigLayerSource::Workspace { file: workspace_config_path.clone() },
349        );
350
351        // Load all layers concurrently. Each load is independent I/O, so
352        // spawning threads overlaps the disk reads and canonicalization
353        // syscalls. The results are collected in source order to preserve
354        // layer precedence.
355        let raw_layers: Vec<Option<ConfigLayerEntry>> = std::thread::scope(|s| {
356            let handles = layer_sources
357                .into_iter()
358                .map(|source| s.spawn(move || Self::load_optional_layer(source)))
359                .collect::<Vec<_>>();
360            // Join every handle first: `scope` re-panics if any panicked thread is left unjoined.
361            let joined = handles.into_iter().map(|h| h.join()).collect::<Vec<_>>();
362            joined
363                .into_iter()
364                .map(|r| r.map_err(|_payload| anyhow::anyhow!("config layer loader thread panicked")))
365                .collect::<Result<Vec<_>>>()
366        })?;
367
368        let mut layer_stack = ConfigLayerStack::default();
369        for layer in raw_layers.into_iter().flatten() {
370            layer_stack.push(layer);
371        }
372
373        let layer_load_duration = t1.elapsed();
374
375        // If no layers found, use default config
376        if layer_stack.layers().is_empty() {
377            let t_val = std::time::Instant::now();
378            let config = VTCodeConfig::default();
379            config.validate().context("Default configuration failed validation")?;
380            let val_duration = t_val.elapsed();
381
382            let phase_timing = ConfigPhaseTiming {
383                path_resolution_us: path_res_duration.as_micros() as u64,
384                layer_loading_us: layer_load_duration.as_micros() as u64,
385                merge_and_parse_us: 0,
386                validation_us: val_duration.as_micros() as u64,
387            };
388            tracing::debug!(target: "vtcode_config", ?phase_timing, "Default configuration loaded");
389
390            return Ok(Self {
391                config,
392                config_path: None,
393                canonical_user_config_path,
394                tracked_user_config_paths,
395                write_global_config_to_canonical: false,
396                explicit_config_is_trusted: false,
397                workspace_root: Some(workspace_root),
398                config_file_name,
399                layer_stack,
400                phase_timing: Some(phase_timing),
401            });
402        }
403
404        // If the workspace root vtcode.toml sets workspace.use_root_config = true,
405        // discard all lower-precedence layers and re-merge with only the workspace
406        // root and runtime layers.
407        let use_root_config = layer_stack
408            .layers()
409            .iter()
410            .find(|l| {
411                matches!(
412                    &l.source,
413                    ConfigLayerSource::Workspace { file }
414                        if *file == workspace_config_path
415                )
416            })
417            .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
418            .unwrap_or(false);
419        if use_root_config {
420            layer_stack.retain(|layer| {
421                matches!(
422                    &layer.source,
423                    ConfigLayerSource::Workspace { file }
424                        if *file == workspace_config_path
425                ) || matches!(&layer.source, ConfigLayerSource::Runtime)
426            });
427            if layer_stack.layers().is_empty() {
428                bail!(
429                    "workspace.use_root_config is true but no workspace root config was found at {}",
430                    workspace_config_path.display()
431                );
432            }
433        }
434
435        if let Some((layer, error)) = layer_stack.first_layer_error() {
436            bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
437        }
438
439        let t2 = std::time::Instant::now();
440        let (effective_toml, origins) = layer_stack.effective_config_with_origins();
441        let mut config: VTCodeConfig = effective_toml
442            .try_into()
443            .context("Failed to deserialize effective configuration")?;
444        let merge_duration = t2.elapsed();
445
446        let t3 = std::time::Instant::now();
447        Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
448        Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
449        Self::validate_sandbox_security_fields(&layer_stack, &origins, false)?;
450
451        config.validate().context("Configuration failed validation")?;
452        config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
453
454        // Migrate any plain-text API keys from config to secure storage
455        migrate_custom_api_keys_if_needed(&mut config)?;
456        let val_duration = t3.elapsed();
457
458        let phase_timing = ConfigPhaseTiming {
459            path_resolution_us: path_res_duration.as_micros() as u64,
460            layer_loading_us: layer_load_duration.as_micros() as u64,
461            merge_and_parse_us: merge_duration.as_micros() as u64,
462            validation_us: val_duration.as_micros() as u64,
463        };
464        tracing::debug!(target: "vtcode_config", ?phase_timing, "Workspace configuration loaded");
465
466        let config_path = layer_stack
467            .layers()
468            .iter()
469            .rev()
470            .find(|layer| layer.is_enabled())
471            .and_then(|l| match &l.source {
472                ConfigLayerSource::User { file } => Some(file.clone()),
473                ConfigLayerSource::Project { file } => Some(file.clone()),
474                ConfigLayerSource::Workspace { file } => Some(file.clone()),
475                ConfigLayerSource::System { file } => Some(file.clone()),
476                ConfigLayerSource::Runtime => None,
477            });
478
479        Ok(Self {
480            config,
481            config_path,
482            canonical_user_config_path,
483            tracked_user_config_paths,
484            write_global_config_to_canonical: false,
485            explicit_config_is_trusted: false,
486            workspace_root: Some(workspace_root),
487            config_file_name,
488            layer_stack,
489            phase_timing: Some(phase_timing),
490        })
491    }
492
493    fn load_toml_from_file(path: &Path) -> Result<toml::Value> {
494        let content =
495            fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
496        Self::parse_layer_value(&content, path)
497    }
498
499    /// Parse one layer's TOML, normalize legacy top-level provider aliases,
500    /// and warn about keys removed from the schema. Single chokepoint so
501    /// every layer kind (required workspace path and optional system/user
502    /// layers) gets identical treatment.
503    fn parse_layer_value(content: &str, path: &Path) -> Result<toml::Value> {
504        let mut value: toml::Value =
505            toml::from_str(content).with_context(|| format!("Failed to parse config file: {}", path.display()))?;
506        crate::loader::merge::normalize_legacy_top_level_provider_aliases(&mut value);
507        Self::warn_removed_config_keys(&value, path);
508        Ok(value)
509    }
510
511    /// Warn once per loaded file about keys that were removed from the schema
512    /// (they still parse — serde ignores unknown fields — but no longer do
513    /// anything). The next config save prunes them
514    /// (`remove_deprecated_config_keys`).
515    fn warn_removed_config_keys(value: &toml::Value, path: &Path) {
516        for key_path in removed_config_key_paths_present(value) {
517            let joined = key_path.join(".");
518            tracing::warn!(
519                config = %path.display(),
520                "Configuration key `{joined}` was removed and is ignored; it will be pruned on the next config save."
521            );
522        }
523    }
524
525    fn load_optional_layer(source: ConfigLayerSource) -> Option<ConfigLayerEntry> {
526        let file = match &source {
527            ConfigLayerSource::System { file }
528            | ConfigLayerSource::User { file }
529            | ConfigLayerSource::Project { file }
530            | ConfigLayerSource::Workspace { file } => file,
531            ConfigLayerSource::Runtime => {
532                return Some(ConfigLayerEntry::new(source, toml::Value::Table(toml::Table::new())));
533            }
534        };
535
536        // Read first so missing files return None without a redundant canonicalize.
537        let content = match fs::read_to_string(file) {
538            Ok(content) => content,
539            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
540            Err(err) if should_skip_optional_global_error(&source, &err) => {
541                tracing::debug!(path = %file.display(), "skipping inaccessible optional configuration layer");
542                return None;
543            }
544            Err(err) => {
545                let resolved_file = canonicalize_workspace_root(file);
546                let resolved_source = source.with_file(resolved_file);
547                return Some(Self::disabled_layer_from_error(resolved_source, err.into()));
548            }
549        };
550
551        let resolved_file = canonicalize_workspace_root(file);
552        let parsed = Self::parse_layer_value(&content, &resolved_file);
553        let resolved_source = source.with_file(resolved_file);
554
555        match parsed {
556            Ok(toml) => Some(ConfigLayerEntry::new(resolved_source, toml)),
557            Err(error) => Some(Self::disabled_layer_from_error(resolved_source, error)),
558        }
559    }
560
561    fn disabled_layer_from_error(source: ConfigLayerSource, error: anyhow::Error) -> ConfigLayerEntry {
562        let reason = if error.is::<toml::de::Error>() {
563            LayerDisabledReason::ParseError
564        } else {
565            LayerDisabledReason::LoadError
566        };
567        ConfigLayerEntry::disabled(source, reason, format!("{error:#}"))
568    }
569
570    /// Check whether a parsed TOML value has `workspace.use_root_config = true`.
571    ///
572    /// This is checked against the already-loaded workspace root layer config
573    /// to avoid a redundant file read.
574    fn workspace_root_wants_root_config_only(config: &toml::Value) -> bool {
575        config
576            .get("workspace")
577            .and_then(|v| v.get("use_root_config"))
578            .and_then(|v| v.as_bool())
579            .unwrap_or(false)
580    }
581
582    /// Load configuration from a specific file
583    pub fn load_from_file(path: impl AsRef<Path>) -> Result<Self> {
584        Self::load_from_file_impl(path, false)
585    }
586
587    fn load_from_file_impl(path: impl AsRef<Path>, write_global_config_to_canonical: bool) -> Result<Self> {
588        let path = path.as_ref();
589        let defaults_provider = defaults::current_config_defaults();
590        // Global layer probing always uses the canonical config file name, never
591        // the basename of the explicit override file. Deriving it from the file
592        // previously caused global layers (e.g. `~/.config/vtcode/vtcode.toml`
593        // with `[[custom_providers]]`) to be skipped whenever the override file
594        // was named something else (e.g. `night.toml`), silently dropping
595        // custom providers and other user-global settings.
596        let config_file_name = defaults_provider.config_file_name().to_string();
597        let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
598        let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
599        if let Some(path) = &canonical_user_config_path
600            && !tracked_user_config_paths.iter().any(|existing| existing == path)
601        {
602            tracked_user_config_paths.push(path.clone());
603        }
604
605        let mut layer_stack = ConfigLayerStack::default();
606        let mut global_sources = Vec::new();
607
608        for system_config in defaults_provider.system_config_paths(&config_file_name)? {
609            push_unique_layer_source(&mut global_sources, ConfigLayerSource::System { file: system_config });
610        }
611        for home_config_path in &tracked_user_config_paths {
612            push_unique_layer_source(&mut global_sources, ConfigLayerSource::User { file: home_config_path.clone() });
613        }
614        for source in global_sources {
615            if let Some(layer) = Self::load_optional_layer(source) {
616                layer_stack.push(layer);
617            }
618        }
619
620        // 3. The specific file provided (Workspace layer)
621        let file = path.to_path_buf();
622        match Self::load_toml_from_file(path) {
623            Ok(toml) => layer_stack.push(ConfigLayerEntry::new(ConfigLayerSource::Workspace { file }, toml)),
624            Err(error) => {
625                layer_stack.push(Self::disabled_layer_from_error(ConfigLayerSource::Workspace { file }, error))
626            }
627        }
628
629        // If the provided file sets workspace.use_root_config = true, discard
630        // lower-precedence layers so only this file and runtime overrides apply.
631        let use_root_config = layer_stack
632            .layers()
633            .iter()
634            .find(|l| {
635                matches!(
636                    &l.source,
637                    ConfigLayerSource::Workspace { file }
638                        if *file == path
639                )
640            })
641            .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
642            .unwrap_or(false);
643        if use_root_config {
644            layer_stack.retain(|layer| {
645                matches!(
646                    &layer.source,
647                    ConfigLayerSource::Workspace { file }
648                        if *file == path
649                ) || matches!(&layer.source, ConfigLayerSource::Runtime)
650            });
651        }
652
653        if let Some((layer, error)) = layer_stack.first_layer_error() {
654            bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
655        }
656
657        let (effective_toml, origins) = layer_stack.effective_config_with_origins();
658        let mut config: VTCodeConfig = effective_toml
659            .try_into()
660            .with_context(|| format!("Failed to parse effective config with file: {}", path.display()))?;
661        Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
662        // A path supplied explicitly by the user is an opt-in trusted layer,
663        // even though it uses the Workspace source variant for precedence and
664        // compatibility with the existing loader.
665        Self::validate_provider_security_fields(&layer_stack, &origins, &config, true)?;
666        Self::validate_sandbox_security_fields(&layer_stack, &origins, true)?;
667
668        config
669            .validate()
670            .with_context(|| format!("Failed to validate effective config with file: {}", path.display()))?;
671        config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
672
673        Ok(Self {
674            config,
675            config_path: Some(canonicalize_workspace_root(path)),
676            canonical_user_config_path,
677            tracked_user_config_paths,
678            write_global_config_to_canonical,
679            explicit_config_is_trusted: true,
680            workspace_root: path.parent().map(canonicalize_workspace_root),
681            config_file_name,
682            layer_stack,
683            phase_timing: None,
684        })
685    }
686
687    /// Resolve the current project name used for project-level config overlays.
688    pub fn current_project_name(workspace_root: &Path) -> Option<String> {
689        Self::identify_current_project(workspace_root)
690    }
691
692    fn enabled_layer_for_origin<'a>(
693        layer_stack: &'a ConfigLayerStack,
694        origin: &ConfigLayerMetadata,
695    ) -> Option<&'a ConfigLayerEntry> {
696        layer_stack
697            .layers()
698            .iter()
699            .find(|layer| layer.is_enabled() && layer.metadata == *origin)
700    }
701
702    fn is_repository_controlled_source(source: &ConfigLayerSource) -> bool {
703        matches!(source, ConfigLayerSource::Project { .. } | ConfigLayerSource::Workspace { .. })
704    }
705
706    fn is_provider_endpoint_or_credential_path(path: &str) -> bool {
707        let mut segments = path.split('.');
708        matches!(segments.next(), Some("provider_overrides"))
709            && segments.next().is_some()
710            && matches!(segments.next(), Some("base_url" | "api_key_env"))
711            && segments.next().is_none()
712    }
713
714    /// Collect lifecycle hook commands whose effective origin is a
715    /// workspace-controlled layer: the workspace-root `vtcode.toml`, the
716    /// workspace `.vtcode/vtcode.toml` fallback, or a project profile stored
717    /// inside the workspace. These are attacker-influenceable in an untrusted
718    /// repository and must be gated behind explicit user approval.
719    pub(crate) fn collect_workspace_lifecycle_hooks(
720        layer_stack: &ConfigLayerStack,
721        hooks: &HooksConfig,
722    ) -> WorkspaceLifecycleHooks {
723        let (_, origins) = layer_stack.effective_config_with_origins();
724        let mut commands = Vec::new();
725
726        for event in crate::hooks::LIFECYCLE_HOOK_EVENTS {
727            let origin_key = format!("hooks.lifecycle.{event}");
728            let Some(origin) = origins.get(&origin_key) else {
729                continue;
730            };
731            let workspace_controlled = layer_stack.layers().iter().any(|layer| {
732                layer.is_enabled()
733                    && layer.metadata == *origin
734                    && matches!(layer.source, ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Project { .. })
735            });
736            if !workspace_controlled {
737                continue;
738            }
739
740            // Deprecated aliases fold into `stop` at engine normalization.
741            let tag = match *event {
742                "task_completion" | "task_completed" => "stop",
743                other => other,
744            };
745            for group in hooks.lifecycle.groups_for_event(event) {
746                for command in &group.hooks {
747                    commands.push(WorkspaceHookCommand {
748                        event: tag.to_string(),
749                        matcher: group.matcher.clone(),
750                        command: command.command.clone(),
751                        timeout_seconds: command.timeout_seconds,
752                    });
753                }
754            }
755        }
756
757        WorkspaceLifecycleHooks { commands }
758    }
759}
760
761mod removed_keys;
762pub(super) use removed_keys::{REMOVED_CONFIG_KEY_PATHS, removed_config_key_paths_present};
763
764#[cfg(test)]
765mod sparse_config_tests;
766#[cfg(test)]
767mod workspace_lifecycle_hooks_tests;