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            Self::validate_sandbox_security_fields(&layer_stack, &origins, false)?;
161            config.validate().context("Global configuration failed validation")?;
162            config.workspace_lifecycle_hooks =
163                Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
164            let config_path = layer_stack
165                .layers()
166                .iter()
167                .rev()
168                .find(|layer| layer.is_enabled())
169                .and_then(|layer| match &layer.source {
170                    ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => Some(file.clone()),
171                    _ => None,
172                });
173            (config, config_path)
174        };
175
176        Ok(Self {
177            config,
178            config_path,
179            canonical_user_config_path,
180            tracked_user_config_paths,
181            write_global_config_to_canonical: false,
182            explicit_config_is_trusted: false,
183            workspace_root: None,
184            config_file_name,
185            layer_stack,
186            phase_timing: None,
187        })
188    }
189
190    /// Invalidate the cached configuration for a specific workspace.
191    ///
192    /// Call this when config files may have changed on disk and the next
193    /// `load_from_workspace` call should perform a fresh read instead of
194    /// returning a previously cached result.
195    pub fn invalidate_workspace_cache(workspace: impl AsRef<Path>) {
196        let workspace = workspace.as_ref();
197        #[cfg(not(test))]
198        {
199            let canonical_workspace = canonicalize_workspace_root(workspace);
200            cache_remove(&canonical_workspace);
201        }
202        #[cfg(test)]
203        let _ = workspace;
204    }
205
206    /// Invalidate every cached workspace configuration.
207    ///
208    /// Used when a session-scoped override changes or is cleared: the cache is
209    /// keyed by canonical workspace only, so an override-loaded manager for any
210    /// workspace must not leak into later default loads. This is a rare event
211    /// (startup and tests), so a full sweep is cheap and safe.
212    pub fn invalidate_all_workspace_cache() {
213        #[cfg(not(test))]
214        with_cache_mut(|map| map.clear());
215    }
216
217    /// Load configuration from a specific workspace
218    ///
219    /// When the session has an explicit config-file override (captured at
220    /// startup via [`session_override::set_explicit_config_path`]), the
221    /// override file takes precedence and is loaded as the highest file
222    /// layer above the default global layers.
223    pub fn load_from_workspace(workspace: impl AsRef<Path>) -> Result<Self> {
224        if let Some(override_path) = session_override::explicit_config_path() {
225            return Self::load_for_session(workspace, override_path);
226        }
227
228        let workspace = workspace.as_ref();
229        #[cfg(not(test))]
230        let canonical_workspace = canonicalize_workspace_root(workspace);
231
232        #[cfg(not(test))]
233        if let Some(cached) = cache_get(&canonical_workspace) {
234            return Ok(cached.as_ref().clone());
235        }
236
237        let manager = Self::load_from_workspace_impl(workspace)?;
238
239        #[cfg(not(test))]
240        cache_insert(canonical_workspace, Arc::new(manager.clone()));
241
242        Ok(manager)
243    }
244
245    /// Load a workspace configuration and repair provider settings left by
246    /// older versions that persisted the merged configuration into a
247    /// repository-controlled file.
248    ///
249    /// The strict loader still rejects repository-controlled provider
250    /// definitions and endpoint/credential overrides. This entry point only
251    /// handles that specific, already-validated violation by removing the
252    /// prohibited fields from the exact repository layer that introduced it,
253    /// then retrying the normal load. Explicit session files remain trusted
254    /// and are never repaired.
255    pub fn load_from_workspace_with_repository_repair(workspace: impl AsRef<Path>) -> Result<Self> {
256        let workspace = workspace.as_ref();
257        let mut error = match Self::load_from_workspace(workspace) {
258            Ok(manager) => return Ok(manager),
259            Err(error) => error,
260        };
261
262        // More than one repository layer can contain a stale flattened copy.
263        // Repair and retry until the strict loader succeeds or every known
264        // repository layer has had a chance to be cleaned.
265        let repository_paths = Self::repository_config_paths(workspace);
266        for _ in 0..=repository_paths.len() {
267            let Some(violation) = error.downcast_ref::<RepositoryProviderSecurityViolation>() else {
268                return Err(error);
269            };
270
271            let source = violation.source.clone();
272            let Some(path) = repository_paths
273                .iter()
274                .find(|candidate| Self::repository_source_matches_path(&source, candidate))
275            else {
276                return Err(error);
277            };
278
279            if !Self::repair_repository_config_file(path)? {
280                return Err(error);
281            }
282
283            tracing::warn!(
284                path = %path.display(),
285                "Removed prohibited provider settings left by an older repository configuration write"
286            );
287
288            Self::invalidate_workspace_cache(workspace);
289            match Self::load_from_workspace(workspace) {
290                Ok(manager) => return Ok(manager),
291                Err(next_error) => error = next_error,
292            }
293        }
294
295        Err(error).context("Failed to load workspace configuration after repairing prohibited provider settings")
296    }
297
298    fn load_from_workspace_impl(workspace: impl AsRef<Path>) -> Result<Self> {
299        let t0 = std::time::Instant::now();
300        let workspace = workspace.as_ref();
301        let defaults_provider = defaults::current_config_defaults();
302        let workspace_paths = defaults_provider.workspace_paths_for(workspace);
303        let workspace_root = canonicalize_workspace_root(workspace_paths.workspace_root());
304        let config_dir = workspace_paths.config_dir();
305        let config_file_name = defaults_provider.config_file_name().to_string();
306        let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
307        let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
308        if let Some(path) = &canonical_user_config_path
309            && !tracked_user_config_paths.iter().any(|existing| existing == path)
310        {
311            tracked_user_config_paths.push(path.clone());
312        }
313        let path_res_duration = t0.elapsed();
314
315        let t1 = std::time::Instant::now();
316
317        // Collect layer sources in precedence order so we can load them
318        // concurrently and then push results while preserving order.
319        let mut layer_sources: Vec<ConfigLayerSource> = Vec::with_capacity(8);
320
321        // 1. System configuration: /etc compatibility followed by
322        // XDG_CONFIG_DIRS candidates, all low-to-high precedence.
323        for system_config_path in defaults_provider.system_config_paths(&config_file_name)? {
324            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::System { file: system_config_path });
325        }
326
327        // 2. Legacy user config followed by the canonical XDG user config.
328        for home_config_path in &tracked_user_config_paths {
329            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::User { file: home_config_path.clone() });
330        }
331
332        // 3. Project-specific config (.vtcode/projects/<project>/config/vtcode.toml)
333        if let Some(project_config_path) = Self::project_config_path(&config_dir, &workspace_root, &config_file_name) {
334            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Project { file: project_config_path });
335        }
336
337        // 4. Config directory fallback (.vtcode/vtcode.toml)
338        let fallback_path = config_dir.join(&config_file_name);
339        let workspace_config_path = workspace_root.join(&config_file_name);
340        if fallback_path != workspace_config_path {
341            push_unique_layer_source(&mut layer_sources, ConfigLayerSource::Workspace { file: fallback_path });
342        }
343
344        // 5. Workspace config (vtcode.toml in workspace root)
345        push_unique_layer_source(
346            &mut layer_sources,
347            ConfigLayerSource::Workspace { file: workspace_config_path.clone() },
348        );
349
350        // Load all layers concurrently. Each load is independent I/O, so
351        // spawning threads overlaps the disk reads and canonicalization
352        // syscalls. The results are collected in source order to preserve
353        // layer precedence.
354        let raw_layers: Vec<Option<ConfigLayerEntry>> = std::thread::scope(|s| {
355            let handles = layer_sources
356                .into_iter()
357                .map(|source| s.spawn(move || Self::load_optional_layer(source)))
358                .collect::<Vec<_>>();
359            // Join every handle first: `scope` re-panics if any panicked thread is left unjoined.
360            let joined = handles.into_iter().map(|h| h.join()).collect::<Vec<_>>();
361            joined
362                .into_iter()
363                .map(|r| r.map_err(|_payload| anyhow::anyhow!("config layer loader thread panicked")))
364                .collect::<Result<Vec<_>>>()
365        })?;
366
367        let mut layer_stack = ConfigLayerStack::default();
368        for layer in raw_layers.into_iter().flatten() {
369            layer_stack.push(layer);
370        }
371
372        let layer_load_duration = t1.elapsed();
373
374        // If no layers found, use default config
375        if layer_stack.layers().is_empty() {
376            let t_val = std::time::Instant::now();
377            let config = VTCodeConfig::default();
378            config.validate().context("Default configuration failed validation")?;
379            let val_duration = t_val.elapsed();
380
381            let phase_timing = ConfigPhaseTiming {
382                path_resolution_us: path_res_duration.as_micros() as u64,
383                layer_loading_us: layer_load_duration.as_micros() as u64,
384                merge_and_parse_us: 0,
385                validation_us: val_duration.as_micros() as u64,
386            };
387            tracing::debug!(target: "vtcode_config", ?phase_timing, "Default configuration loaded");
388
389            return Ok(Self {
390                config,
391                config_path: None,
392                canonical_user_config_path,
393                tracked_user_config_paths,
394                write_global_config_to_canonical: false,
395                explicit_config_is_trusted: false,
396                workspace_root: Some(workspace_root),
397                config_file_name,
398                layer_stack,
399                phase_timing: Some(phase_timing),
400            });
401        }
402
403        // If the workspace root vtcode.toml sets workspace.use_root_config = true,
404        // discard all lower-precedence layers and re-merge with only the workspace
405        // root and runtime layers.
406        let use_root_config = layer_stack
407            .layers()
408            .iter()
409            .find(|l| {
410                matches!(
411                    &l.source,
412                    ConfigLayerSource::Workspace { file }
413                        if *file == workspace_config_path
414                )
415            })
416            .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
417            .unwrap_or(false);
418        if use_root_config {
419            layer_stack.retain(|layer| {
420                matches!(
421                    &layer.source,
422                    ConfigLayerSource::Workspace { file }
423                        if *file == workspace_config_path
424                ) || matches!(&layer.source, ConfigLayerSource::Runtime)
425            });
426            if layer_stack.layers().is_empty() {
427                bail!(
428                    "workspace.use_root_config is true but no workspace root config was found at {}",
429                    workspace_config_path.display()
430                );
431            }
432        }
433
434        if let Some((layer, error)) = layer_stack.first_layer_error() {
435            bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
436        }
437
438        let t2 = std::time::Instant::now();
439        let (effective_toml, origins) = layer_stack.effective_config_with_origins();
440        let mut config: VTCodeConfig = effective_toml
441            .try_into()
442            .context("Failed to deserialize effective configuration")?;
443        let merge_duration = t2.elapsed();
444
445        let t3 = std::time::Instant::now();
446        Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
447        Self::validate_provider_security_fields(&layer_stack, &origins, &config, false)?;
448        Self::validate_sandbox_security_fields(&layer_stack, &origins, false)?;
449
450        config.validate().context("Configuration failed validation")?;
451        config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
452
453        // Migrate any plain-text API keys from config to secure storage
454        migrate_custom_api_keys_if_needed(&mut config)?;
455        let val_duration = t3.elapsed();
456
457        let phase_timing = ConfigPhaseTiming {
458            path_resolution_us: path_res_duration.as_micros() as u64,
459            layer_loading_us: layer_load_duration.as_micros() as u64,
460            merge_and_parse_us: merge_duration.as_micros() as u64,
461            validation_us: val_duration.as_micros() as u64,
462        };
463        tracing::debug!(target: "vtcode_config", ?phase_timing, "Workspace configuration loaded");
464
465        let config_path = layer_stack
466            .layers()
467            .iter()
468            .rev()
469            .find(|layer| layer.is_enabled())
470            .and_then(|l| match &l.source {
471                ConfigLayerSource::User { file } => Some(file.clone()),
472                ConfigLayerSource::Project { file } => Some(file.clone()),
473                ConfigLayerSource::Workspace { file } => Some(file.clone()),
474                ConfigLayerSource::System { file } => Some(file.clone()),
475                ConfigLayerSource::Runtime => None,
476            });
477
478        Ok(Self {
479            config,
480            config_path,
481            canonical_user_config_path,
482            tracked_user_config_paths,
483            write_global_config_to_canonical: false,
484            explicit_config_is_trusted: false,
485            workspace_root: Some(workspace_root),
486            config_file_name,
487            layer_stack,
488            phase_timing: Some(phase_timing),
489        })
490    }
491
492    fn load_toml_from_file(path: &Path) -> Result<toml::Value> {
493        let content =
494            fs::read_to_string(path).with_context(|| format!("Failed to read config file: {}", path.display()))?;
495        Self::parse_layer_value(&content, path)
496    }
497
498    /// Parse one layer's TOML, normalize legacy top-level provider aliases,
499    /// and warn about keys removed from the schema. Single chokepoint so
500    /// every layer kind (required workspace path and optional system/user
501    /// layers) gets identical treatment.
502    fn parse_layer_value(content: &str, path: &Path) -> Result<toml::Value> {
503        let mut value: toml::Value =
504            toml::from_str(content).with_context(|| format!("Failed to parse config file: {}", path.display()))?;
505        crate::loader::merge::normalize_legacy_top_level_provider_aliases(&mut value);
506        Self::warn_removed_config_keys(&value, path);
507        Ok(value)
508    }
509
510    /// Warn once per loaded file about keys that were removed from the schema
511    /// (they still parse — serde ignores unknown fields — but no longer do
512    /// anything). The next config save prunes them
513    /// (`remove_deprecated_config_keys`).
514    fn warn_removed_config_keys(value: &toml::Value, path: &Path) {
515        for key_path in removed_config_key_paths_present(value) {
516            let joined = key_path.join(".");
517            tracing::warn!(
518                config = %path.display(),
519                "Configuration key `{joined}` was removed and is ignored; it will be pruned on the next config save."
520            );
521        }
522    }
523
524    fn load_optional_layer(source: ConfigLayerSource) -> Option<ConfigLayerEntry> {
525        let file = match &source {
526            ConfigLayerSource::System { file }
527            | ConfigLayerSource::User { file }
528            | ConfigLayerSource::Project { file }
529            | ConfigLayerSource::Workspace { file } => file,
530            ConfigLayerSource::Runtime => {
531                return Some(ConfigLayerEntry::new(source, toml::Value::Table(toml::Table::new())));
532            }
533        };
534
535        // Read first so missing files return None without a redundant canonicalize.
536        let content = match fs::read_to_string(file) {
537            Ok(content) => content,
538            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return None,
539            Err(err) if should_skip_optional_global_error(&source, &err) => {
540                tracing::debug!(path = %file.display(), "skipping inaccessible optional configuration layer");
541                return None;
542            }
543            Err(err) => {
544                let resolved_file = canonicalize_workspace_root(file);
545                let resolved_source = source.with_file(resolved_file);
546                return Some(Self::disabled_layer_from_error(resolved_source, err.into()));
547            }
548        };
549
550        let resolved_file = canonicalize_workspace_root(file);
551        let parsed = Self::parse_layer_value(&content, &resolved_file);
552        let resolved_source = source.with_file(resolved_file);
553
554        match parsed {
555            Ok(toml) => Some(ConfigLayerEntry::new(resolved_source, toml)),
556            Err(error) => Some(Self::disabled_layer_from_error(resolved_source, error)),
557        }
558    }
559
560    fn disabled_layer_from_error(source: ConfigLayerSource, error: anyhow::Error) -> ConfigLayerEntry {
561        let reason = if error.is::<toml::de::Error>() {
562            LayerDisabledReason::ParseError
563        } else {
564            LayerDisabledReason::LoadError
565        };
566        ConfigLayerEntry::disabled(source, reason, format!("{error:#}"))
567    }
568
569    /// Check whether a parsed TOML value has `workspace.use_root_config = true`.
570    ///
571    /// This is checked against the already-loaded workspace root layer config
572    /// to avoid a redundant file read.
573    fn workspace_root_wants_root_config_only(config: &toml::Value) -> bool {
574        config
575            .get("workspace")
576            .and_then(|v| v.get("use_root_config"))
577            .and_then(|v| v.as_bool())
578            .unwrap_or(false)
579    }
580
581    /// Load configuration from a specific file
582    pub fn load_from_file(path: impl AsRef<Path>) -> Result<Self> {
583        Self::load_from_file_impl(path, false)
584    }
585
586    fn load_from_file_impl(path: impl AsRef<Path>, write_global_config_to_canonical: bool) -> Result<Self> {
587        let path = path.as_ref();
588        let defaults_provider = defaults::current_config_defaults();
589        // Global layer probing always uses the canonical config file name, never
590        // the basename of the explicit override file. Deriving it from the file
591        // previously caused global layers (e.g. `~/.config/vtcode/vtcode.toml`
592        // with `[[custom_providers]]`) to be skipped whenever the override file
593        // was named something else (e.g. `night.toml`), silently dropping
594        // custom providers and other user-global settings.
595        let config_file_name = defaults_provider.config_file_name().to_string();
596        let canonical_user_config_path = defaults_provider.canonical_user_config_path(&config_file_name)?;
597        let mut tracked_user_config_paths = defaults_provider.home_config_paths(&config_file_name);
598        if let Some(path) = &canonical_user_config_path
599            && !tracked_user_config_paths.iter().any(|existing| existing == path)
600        {
601            tracked_user_config_paths.push(path.clone());
602        }
603
604        let mut layer_stack = ConfigLayerStack::default();
605        let mut global_sources = Vec::new();
606
607        for system_config in defaults_provider.system_config_paths(&config_file_name)? {
608            push_unique_layer_source(&mut global_sources, ConfigLayerSource::System { file: system_config });
609        }
610        for home_config_path in &tracked_user_config_paths {
611            push_unique_layer_source(&mut global_sources, ConfigLayerSource::User { file: home_config_path.clone() });
612        }
613        for source in global_sources {
614            if let Some(layer) = Self::load_optional_layer(source) {
615                layer_stack.push(layer);
616            }
617        }
618
619        // 3. The specific file provided (Workspace layer)
620        let file = path.to_path_buf();
621        match Self::load_toml_from_file(path) {
622            Ok(toml) => layer_stack.push(ConfigLayerEntry::new(ConfigLayerSource::Workspace { file }, toml)),
623            Err(error) => {
624                layer_stack.push(Self::disabled_layer_from_error(ConfigLayerSource::Workspace { file }, error))
625            }
626        }
627
628        // If the provided file sets workspace.use_root_config = true, discard
629        // lower-precedence layers so only this file and runtime overrides apply.
630        let use_root_config = layer_stack
631            .layers()
632            .iter()
633            .find(|l| {
634                matches!(
635                    &l.source,
636                    ConfigLayerSource::Workspace { file }
637                        if *file == path
638                )
639            })
640            .map(|l| Self::workspace_root_wants_root_config_only(&l.config))
641            .unwrap_or(false);
642        if use_root_config {
643            layer_stack.retain(|layer| {
644                matches!(
645                    &layer.source,
646                    ConfigLayerSource::Workspace { file }
647                        if *file == path
648                ) || matches!(&layer.source, ConfigLayerSource::Runtime)
649            });
650        }
651
652        if let Some((layer, error)) = layer_stack.first_layer_error() {
653            bail!("Configuration layer '{}' failed to load: {}", layer.source.label(), error.message);
654        }
655
656        let (effective_toml, origins) = layer_stack.effective_config_with_origins();
657        let mut config: VTCodeConfig = effective_toml
658            .try_into()
659            .with_context(|| format!("Failed to parse effective config with file: {}", path.display()))?;
660        Self::validate_restricted_agent_fields(&layer_stack, &origins)?;
661        // A path supplied explicitly by the user is an opt-in trusted layer,
662        // even though it uses the Workspace source variant for precedence and
663        // compatibility with the existing loader.
664        Self::validate_provider_security_fields(&layer_stack, &origins, &config, true)?;
665        Self::validate_sandbox_security_fields(&layer_stack, &origins, true)?;
666
667        config
668            .validate()
669            .with_context(|| format!("Failed to validate effective config with file: {}", path.display()))?;
670        config.workspace_lifecycle_hooks = Some(Self::collect_workspace_lifecycle_hooks(&layer_stack, &config.hooks));
671
672        Ok(Self {
673            config,
674            config_path: Some(canonicalize_workspace_root(path)),
675            canonical_user_config_path,
676            tracked_user_config_paths,
677            write_global_config_to_canonical,
678            explicit_config_is_trusted: true,
679            workspace_root: path.parent().map(canonicalize_workspace_root),
680            config_file_name,
681            layer_stack,
682            phase_timing: None,
683        })
684    }
685
686    /// Resolve the current project name used for project-level config overlays.
687    pub fn current_project_name(workspace_root: &Path) -> Option<String> {
688        Self::identify_current_project(workspace_root)
689    }
690
691    fn validate_restricted_agent_fields(
692        layer_stack: &ConfigLayerStack,
693        origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
694    ) -> Result<()> {
695        if let Some(origin) = origins.get("agent.persistent_memory.directory_override")
696            && let Some(layer) = layer_stack.layers().iter().find(|layer| layer.metadata == *origin)
697        {
698            match layer.source {
699                ConfigLayerSource::System { .. }
700                | ConfigLayerSource::User { .. }
701                | ConfigLayerSource::Project { .. } => {}
702                ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Runtime => {
703                    bail!(
704                        "agent.persistent_memory.directory_override may only be set in system, user, or project-profile configuration layers"
705                    );
706                }
707            }
708        }
709
710        Ok(())
711    }
712
713    /// Reject provider settings from repository-controlled layers before they
714    /// can reach provider registration or request handling.
715    ///
716    /// Workspace and project files are repository-controlled input. They may
717    /// configure ordinary agent behavior, but must not introduce executable
718    /// authentication commands or redirect provider requests/credentials.
719    /// `load_from_file` is an explicit user opt-in and therefore passes
720    /// `explicit_config_is_trusted = true`.
721    fn validate_provider_security_fields(
722        layer_stack: &ConfigLayerStack,
723        origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
724        config: &VTCodeConfig,
725        explicit_config_is_trusted: bool,
726    ) -> Result<()> {
727        if explicit_config_is_trusted {
728            return Ok(());
729        }
730
731        if !config.custom_providers.is_empty()
732            && let Some(origin) = origins.get("custom_providers")
733            && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
734            && Self::is_repository_controlled_source(&layer.source)
735        {
736            return Err(RepositoryProviderSecurityViolation {
737                source: layer.source.clone(),
738                message: format!(
739                    "repository-controlled configuration cannot define `custom_providers` (including `auth.command`); move custom provider settings to system, user, or an explicitly selected config file (source: {})",
740                    layer.source.label()
741                ),
742            }
743            .into());
744        }
745
746        for (path, origin) in origins {
747            if path == "auth.copilot.command"
748                && config
749                    .auth
750                    .copilot
751                    .command
752                    .as_deref()
753                    .is_some_and(|command| !command.trim().is_empty())
754                && let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin)
755                && Self::is_repository_controlled_source(&layer.source)
756            {
757                bail!(
758                    "repository-controlled configuration cannot set `auth.copilot.command`; configure it in system, user, or an explicitly selected config file (source: {})",
759                    layer.source.label()
760                );
761            }
762            if !Self::is_provider_endpoint_or_credential_path(path) {
763                continue;
764            }
765
766            let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
767                continue;
768            };
769            if Self::is_repository_controlled_source(&layer.source) {
770                return Err(RepositoryProviderSecurityViolation {
771                    source: layer.source.clone(),
772                    message: format!(
773                        "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: {})",
774                        layer.source.label()
775                    ),
776                }
777                .into());
778            }
779        }
780
781        Ok(())
782    }
783
784    /// Reject *relaxing* sandbox values from repository-controlled layers.
785    ///
786    /// `vtcode.toml` checked into a repository is untrusted input. It may carry
787    /// the ordinary serialized defaults (which are not a widening), but it
788    /// must not turn off a boundary a trusted layer enabled, switch to full
789    /// access, open the network, drop credential path blocking, or weaken
790    /// seccomp/resource limits. System/user config and explicitly selected
791    /// files remain authoritative, matching the provider-security split.
792    fn validate_sandbox_security_fields(
793        layer_stack: &ConfigLayerStack,
794        origins: &hashbrown::HashMap<String, ConfigLayerMetadata>,
795        explicit_config_is_trusted: bool,
796    ) -> Result<()> {
797        if explicit_config_is_trusted {
798            return Ok(());
799        }
800
801        let trusted_enabled = layer_stack.layers().iter().any(|layer| {
802            layer.is_enabled()
803                && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
804                && Self::toml_bool_at(&layer.config, "sandbox.enabled") == Some(true)
805        });
806
807        for (path, origin) in origins {
808            let Some(layer) = Self::enabled_layer_for_origin(layer_stack, origin) else {
809                continue;
810            };
811            if !Self::is_repository_controlled_source(&layer.source) {
812                continue;
813            }
814            let value = Self::toml_value_at(&layer.config, path);
815            let relaxing = match path.as_str() {
816                "sandbox.enabled" => trusted_enabled && value.and_then(toml::Value::as_bool) == Some(false),
817                "sandbox.default_policy" => value
818                    .and_then(toml::Value::as_str)
819                    .is_some_and(|policy| matches!(policy, "danger_full_access" | "external")),
820                "sandbox.network.policy" => value.and_then(toml::Value::as_str) == Some("allow_all"),
821                "sandbox.network.allow_all" => value.and_then(toml::Value::as_bool) == Some(true),
822                "sandbox.sensitive_paths.use_defaults" => value.and_then(toml::Value::as_bool) == Some(false),
823                "sandbox.sensitive_paths.exceptions" => {
824                    value.and_then(toml::Value::as_array).is_some_and(|paths| !paths.is_empty())
825                }
826                "sandbox.resource_limits.preset" => value
827                    .and_then(toml::Value::as_str)
828                    .is_some_and(|preset| matches!(preset, "unlimited" | "generous")),
829                "sandbox.seccomp.enabled" => value.and_then(toml::Value::as_bool) == Some(false),
830                "sandbox.seccomp.profile" => value
831                    .and_then(toml::Value::as_str)
832                    .is_some_and(|profile| matches!(profile, "permissive" | "disabled")),
833                "sandbox.seccomp.log_only" => value.and_then(toml::Value::as_bool) == Some(true),
834                _ => false,
835            };
836            if relaxing {
837                bail!(
838                    "repository-controlled configuration cannot relax `{path}`; the sandbox boundary must come from system, user, or an explicitly selected config file (source: {})",
839                    layer.source.label()
840                );
841            }
842        }
843
844        Ok(())
845    }
846
847    fn toml_value_at<'a>(root: &'a toml::Value, path: &str) -> Option<&'a toml::Value> {
848        path.split('.').try_fold(root, |value, part| value.get(part))
849    }
850
851    fn toml_bool_at(root: &toml::Value, path: &str) -> Option<bool> {
852        Self::toml_value_at(root, path).and_then(toml::Value::as_bool)
853    }
854
855    fn enabled_layer_for_origin<'a>(
856        layer_stack: &'a ConfigLayerStack,
857        origin: &ConfigLayerMetadata,
858    ) -> Option<&'a ConfigLayerEntry> {
859        layer_stack
860            .layers()
861            .iter()
862            .find(|layer| layer.is_enabled() && layer.metadata == *origin)
863    }
864
865    fn is_repository_controlled_source(source: &ConfigLayerSource) -> bool {
866        matches!(source, ConfigLayerSource::Project { .. } | ConfigLayerSource::Workspace { .. })
867    }
868
869    fn is_provider_endpoint_or_credential_path(path: &str) -> bool {
870        let mut segments = path.split('.');
871        matches!(segments.next(), Some("provider_overrides"))
872            && segments.next().is_some()
873            && matches!(segments.next(), Some("base_url" | "api_key_env"))
874            && segments.next().is_none()
875    }
876
877    /// Collect lifecycle hook commands whose effective origin is a
878    /// workspace-controlled layer: the workspace-root `vtcode.toml`, the
879    /// workspace `.vtcode/vtcode.toml` fallback, or a project profile stored
880    /// inside the workspace. These are attacker-influenceable in an untrusted
881    /// repository and must be gated behind explicit user approval.
882    pub(crate) fn collect_workspace_lifecycle_hooks(
883        layer_stack: &ConfigLayerStack,
884        hooks: &HooksConfig,
885    ) -> WorkspaceLifecycleHooks {
886        let (_, origins) = layer_stack.effective_config_with_origins();
887        let mut commands = Vec::new();
888
889        for event in crate::hooks::LIFECYCLE_HOOK_EVENTS {
890            let origin_key = format!("hooks.lifecycle.{event}");
891            let Some(origin) = origins.get(&origin_key) else {
892                continue;
893            };
894            let workspace_controlled = layer_stack.layers().iter().any(|layer| {
895                layer.is_enabled()
896                    && layer.metadata == *origin
897                    && matches!(layer.source, ConfigLayerSource::Workspace { .. } | ConfigLayerSource::Project { .. })
898            });
899            if !workspace_controlled {
900                continue;
901            }
902
903            // Deprecated aliases fold into `stop` at engine normalization.
904            let tag = match *event {
905                "task_completion" | "task_completed" => "stop",
906                other => other,
907            };
908            for group in hooks.lifecycle.groups_for_event(event) {
909                for command in &group.hooks {
910                    commands.push(WorkspaceHookCommand {
911                        event: tag.to_string(),
912                        matcher: group.matcher.clone(),
913                        command: command.command.clone(),
914                        timeout_seconds: command.timeout_seconds,
915                    });
916                }
917            }
918        }
919
920        WorkspaceLifecycleHooks { commands }
921    }
922}
923
924mod removed_keys;
925pub(super) use removed_keys::{REMOVED_CONFIG_KEY_PATHS, removed_config_key_paths_present};
926
927#[cfg(test)]
928mod sparse_config_tests;
929#[cfg(test)]
930mod workspace_lifecycle_hooks_tests;