Skip to main content

vtcode_config/loader/manager/
mod.rs

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