Skip to main content

vtcode_config/loader/manager/
persistence.rs

1//! Sparse configuration saves and comment-preserving TOML persistence.
2
3use std::fs;
4use std::path::Path;
5
6use anyhow::{Context, Result, bail};
7use vtcode_commons::VtCodePaths;
8
9use super::super::toml_patch::render_toml_edit;
10use super::{ConfigLayerSource, ConfigManager, VTCodeConfig};
11
12fn ensure_private_parent_dir(path: &Path) -> Result<()> {
13    let Some(parent) = path.parent() else {
14        return Ok(());
15    };
16    let _ = VtCodePaths::ensure_user_dir(parent)
17        .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
18    Ok(())
19}
20
21impl ConfigManager {
22    /// Persist configuration to a specific path, preserving comments.
23    pub fn save_config_to_path(path: impl AsRef<Path>, config: &VTCodeConfig) -> Result<()> {
24        Self::save_config_to_path_internal(path, config, false)
25    }
26
27    /// Persist configuration to a repository-controlled path.
28    ///
29    /// Repository and project files may contain ordinary settings, but they
30    /// must never receive trusted provider definitions or provider endpoint and
31    /// credential overrides from the merged configuration. Existing protected
32    /// keys are removed as well so this method can repair files written by an
33    /// older version that flattened the effective configuration.
34    pub fn save_repository_config_to_path(path: impl AsRef<Path>, config: &VTCodeConfig) -> Result<()> {
35        Self::save_config_to_path_internal(path, config, true)
36    }
37
38    /// Render a targeted edit, pruning deprecated configuration keys.
39    ///
40    /// # Errors
41    ///
42    /// Returns an error if the original document or requested update cannot be rendered.
43    pub fn merge_config_edit(original: &str, updated: &toml::Value) -> Result<String> {
44        render_toml_edit(original, updated, Self::remove_deprecated_config_keys)
45    }
46
47    /// Render a targeted edit while applying the repository provider trust policy.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if the original document or requested update cannot be rendered.
52    pub fn merge_repository_config_edit(original: &str, updated: &toml::Value) -> Result<String> {
53        render_toml_edit(original, updated, |doc| {
54            let removed_deprecated = Self::remove_deprecated_config_keys(doc);
55            Self::remove_protected_repository_keys(doc) || removed_deprecated
56        })
57    }
58
59    fn remove_protected_repository_keys(doc: &mut toml_edit::DocumentMut) -> bool {
60        let provider_changed = Self::remove_repository_provider_settings(doc);
61        let auth_changed =
62            Self::remove_path_and_prune_empty_parents(doc.as_table_mut(), &["auth", "copilot", "command"]);
63        provider_changed || auth_changed
64    }
65
66    fn save_config_to_path_internal(
67        path: impl AsRef<Path>,
68        config: &VTCodeConfig,
69        repository_controlled: bool,
70    ) -> Result<()> {
71        let path = path.as_ref();
72        ensure_private_parent_dir(path)?;
73        let config_to_persist = if repository_controlled {
74            Self::repository_safe_config(config)
75        } else {
76            config.clone()
77        };
78        let sparse_value =
79            Self::sparse_config_value(&config_to_persist).context("Failed to prepare sparse configuration")?;
80        let sparse_content =
81            toml::to_string_pretty(&sparse_value).context("Failed to serialize sparse configuration")?;
82
83        // If file exists, preserve comments by using toml_edit. Read and
84        // publish through the shared no-follow/atomic file policy so a
85        // user-controlled symlink cannot redirect configuration writes.
86        let existing_content = match fs::symlink_metadata(path) {
87            Ok(metadata) if metadata.file_type().is_symlink() => {
88                bail!("Refusing to read symlinked config file: {}", path.display())
89            }
90            Ok(metadata) if !metadata.is_file() => {
91                bail!("Config path is not a regular file: {}", path.display())
92            }
93            Ok(_) => Some(
94                String::from_utf8(VtCodePaths::read_file_no_follow(path)?)
95                    .with_context(|| format!("Failed to read existing config: {}", path.display()))?,
96            ),
97            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
98            Err(error) => {
99                return Err(error).with_context(|| format!("Failed to inspect config: {}", path.display()));
100            }
101        };
102
103        if let Some(original_content) = existing_content {
104            let mut doc = original_content
105                .parse::<toml_edit::DocumentMut>()
106                .with_context(|| format!("Failed to parse existing config: {}", path.display()))?;
107            Self::remove_deprecated_config_keys(&mut doc);
108            if repository_controlled {
109                Self::remove_protected_repository_keys(&mut doc);
110            }
111
112            let new_doc: toml_edit::DocumentMut = sparse_content
113                .parse()
114                .context("Failed to parse sparse serialized configuration")?;
115            let default_value =
116                toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
117            let default_doc: toml_edit::DocumentMut = toml::to_string_pretty(&default_value)
118                .context("Failed to serialize default configuration")?
119                .parse()
120                .context("Failed to parse default serialized configuration")?;
121
122            // Update values while preserving structure and comments
123            Self::merge_sparse_toml_documents(&mut doc, &new_doc, &default_doc);
124            // The sparse merge cannot express the deletion of optional fields
125            // whose default serializes to absent (they appear in neither the
126            // sparse update nor the defaults), so resets issued through save
127            // paths (e.g. service_tier back to Project default) would leave
128            // stale file values behind forever. Reconcile those explicitly.
129            Self::prune_cleared_optional_fields(&mut doc, &config_to_persist);
130
131            VtCodePaths::write_private_file_atomic(path, doc.to_string().as_bytes())
132                .with_context(|| format!("Failed to write config file: {}", path.display()))?;
133        } else {
134            VtCodePaths::write_private_file_atomic(path, sparse_content.as_bytes())
135                .with_context(|| format!("Failed to write config file: {}", path.display()))?;
136        }
137
138        Ok(())
139    }
140
141    fn repository_safe_config(config: &VTCodeConfig) -> VTCodeConfig {
142        let mut safe_config = config.clone();
143        safe_config.custom_providers.clear();
144        safe_config.auth.copilot.command = None;
145        for provider_override in safe_config.provider_overrides.values_mut() {
146            provider_override.base_url = None;
147            provider_override.api_key_env = None;
148        }
149        safe_config
150    }
151
152    /// Remove file values for optional fields the effective config reset to
153    /// their absent default (e.g. `provider.openai.service_tier` back to
154    /// Project default). The sparse merge cannot express these deletions
155    /// (absent from both the sparse update and the defaults), so each entry
156    /// pairs a dotted path with a typed cleared-check. Only listed paths are
157    /// touched; foreign keys are never removed. Extend the list when a new
158    /// resettable optional reaches a save path.
159    fn prune_cleared_optional_fields(doc: &mut toml_edit::DocumentMut, config: &VTCodeConfig) {
160        // Each entry: (dotted path, is_cleared).
161        let cleared: &[(&[&str], bool)] = &[
162            (&["provider", "openai", "service_tier"], config.provider.openai.service_tier.is_none()),
163            (&["provider", "anthropic", "speed"], config.provider.anthropic.speed.is_none()),
164        ];
165        for (path, is_cleared) in cleared {
166            if *is_cleared {
167                Self::remove_path_and_prune_empty_parents(doc.as_table_mut(), path);
168            }
169        }
170    }
171
172    /// Remove `path` from `table`, then drop ancestor tables left empty.
173    /// Returns true when anything was removed.
174    fn remove_path_and_prune_empty_parents(table: &mut dyn toml_edit::TableLike, path: &[&str]) -> bool {
175        let Some((first, rest)) = path.split_first() else {
176            return false;
177        };
178        if rest.is_empty() {
179            return table.remove(first).is_some();
180        }
181        let Some(child) = table.get_mut(first).and_then(toml_edit::Item::as_table_like_mut) else {
182            return false;
183        };
184        let changed = Self::remove_path_and_prune_empty_parents(child, rest);
185        if child.is_empty() {
186            table.remove(first);
187            return true;
188        }
189        changed
190    }
191
192    fn remove_deprecated_config_keys(doc: &mut toml_edit::DocumentMut) -> bool {
193        let table = doc.as_table_mut();
194        let mut changed = table.remove("project_doc_max_bytes").is_some();
195        changed |= table.remove("project_doc_fallback_filenames").is_some();
196        changed |= Self::remove_table_keys(table, "agent", &["autonomous_mode", "default_editing_mode"]);
197        changed |=
198            Self::remove_table_keys(table, "permissions", &["allowed_tools", "disallowed_tools", "auto_permission"]);
199        // Keep this in sync with the loader warning that retired keys are pruned on save.
200        for &key_path in super::REMOVED_CONFIG_KEY_PATHS {
201            changed |= Self::remove_path_and_prune_empty_parents(table, key_path);
202        }
203        changed
204    }
205
206    fn remove_table_keys(table: &mut toml_edit::Table, section: &str, keys: &[&str]) -> bool {
207        let Some(section) = table.get_mut(section).and_then(toml_edit::Item::as_table_mut) else {
208            return false;
209        };
210        let mut changed = false;
211        for key in keys {
212            changed |= section.remove(key).is_some();
213        }
214        changed
215    }
216
217    pub fn sparse_config_value(config: &VTCodeConfig) -> Result<toml::Value> {
218        let mut value = toml::Value::try_from(config).context("Failed to serialize configuration")?;
219        let default_value =
220            toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
221        Self::prune_default_values(&mut value, &default_value);
222        Ok(value)
223    }
224
225    fn prune_default_values(value: &mut toml::Value, default_value: &toml::Value) -> bool {
226        match (value, default_value) {
227            (toml::Value::Table(table), toml::Value::Table(default_table)) => {
228                table.retain(|key, child| {
229                    default_table
230                        .get(key)
231                        .is_none_or(|default_child| !Self::prune_default_values(child, default_child))
232                });
233                table.is_empty()
234            }
235            (value, default_value) => value == default_value,
236        }
237    }
238
239    /// Merge TOML documents, preserving comments and structure from original
240    fn merge_sparse_toml_documents(
241        original: &mut toml_edit::DocumentMut,
242        new: &toml_edit::DocumentMut,
243        default_doc: &toml_edit::DocumentMut,
244    ) {
245        Self::merge_sparse_tables(original.as_table_mut(), new.as_table(), default_doc.as_table());
246    }
247
248    fn merge_sparse_tables(original: &mut toml_edit::Table, new: &toml_edit::Table, default_table: &toml_edit::Table) {
249        let mut remove_keys = Vec::with_capacity(default_table.len());
250
251        for (key, default_value) in default_table.iter() {
252            if let Some(new_value) = new.get(key) {
253                if let Some(original_value) = original.get_mut(key) {
254                    Self::merge_sparse_items(original_value, new_value, default_value);
255                } else {
256                    original[key] = new_value.clone();
257                }
258            } else {
259                let Some(original_value) = original.get_mut(key) else {
260                    continue;
261                };
262                if Self::remove_known_default_item(original_value, default_value) {
263                    remove_keys.push(key.to_string());
264                }
265            }
266        }
267
268        for key in remove_keys {
269            original.remove(&key);
270        }
271
272        for (key, new_value) in new.iter() {
273            if default_table.contains_key(key) {
274                continue;
275            }
276            if let Some(original_value) = original.get_mut(key) {
277                *original_value = new_value.clone();
278            } else {
279                original[key] = new_value.clone();
280            }
281        }
282    }
283
284    fn merge_sparse_items(original: &mut toml_edit::Item, new: &toml_edit::Item, default_value: &toml_edit::Item) {
285        match (original, new, default_value) {
286            (
287                toml_edit::Item::Table(orig_table),
288                toml_edit::Item::Table(new_table),
289                toml_edit::Item::Table(default_table),
290            ) => Self::merge_sparse_tables(orig_table, new_table, default_table),
291            (orig, new, _) => {
292                *orig = new.clone();
293            }
294        }
295    }
296
297    fn remove_known_default_item(original: &mut toml_edit::Item, default_value: &toml_edit::Item) -> bool {
298        match (original, default_value) {
299            (toml_edit::Item::Table(orig_table), toml_edit::Item::Table(default_table)) => {
300                let mut remove_keys = Vec::new();
301                for (key, default_child) in default_table.iter() {
302                    let Some(orig_child) = orig_table.get_mut(key) else {
303                        continue;
304                    };
305                    if Self::remove_known_default_item(orig_child, default_child) {
306                        remove_keys.push(key.to_string());
307                    }
308                }
309                for key in remove_keys {
310                    orig_table.remove(&key);
311                }
312                orig_table.is_empty()
313            }
314            _ => true,
315        }
316    }
317
318    /// Persist configuration to the manager's associated path or workspace
319    pub fn save_config(&mut self, config: &VTCodeConfig) -> Result<()> {
320        let (target, repository_controlled) = if let Some(path) = &self.config_path {
321            if self.write_global_config_to_canonical || self.is_global_config_path(path) {
322                (self.preferred_user_config_path().unwrap_or_else(|| path.clone()), false)
323            } else {
324                (path.clone(), !self.explicit_config_is_trusted)
325            }
326        } else if let Some(workspace_root) = &self.workspace_root {
327            (workspace_root.join(&self.config_file_name), !self.explicit_config_is_trusted)
328        } else {
329            let cwd = std::env::current_dir().context("Failed to resolve current directory")?;
330            (cwd.join(&self.config_file_name), !self.explicit_config_is_trusted)
331        };
332
333        if repository_controlled {
334            Self::save_repository_config_to_path(target, config)?;
335        } else {
336            Self::save_config_to_path(target, config)?;
337        }
338
339        #[cfg(not(test))]
340        if let Some(workspace) = &self.workspace_root {
341            Self::invalidate_workspace_cache(workspace);
342        }
343
344        self.sync_from_config(config)
345    }
346
347    fn is_global_config_path(&self, path: &Path) -> bool {
348        self.layer_stack.layers().iter().any(|layer| {
349            layer.is_enabled()
350                && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
351                && match &layer.source {
352                    ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => file == path,
353                    _ => false,
354                }
355        })
356    }
357
358    /// Sync internal config from a saved config
359    /// Call this after save_config to keep internal state in sync
360    fn sync_from_config(&mut self, config: &VTCodeConfig) -> Result<()> {
361        self.config = config.clone();
362        Ok(())
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369
370    #[test]
371    fn repository_edit_writes_cleanup_when_setting_did_not_change() {
372        let original = concat!(
373            "[ui]\nshow_timeline_pane = false\n",
374            "[ui.fullscreen]\ncopy_on_select = true\n",
375            "\n[auth.copilot]\ncommand = 'helper'\n",
376        );
377        let updated = toml::from_str(original).expect("parse update");
378
379        let rendered = ConfigManager::merge_repository_config_edit(original, &updated).expect("patch repository");
380        let saved: toml::Value = toml::from_str(&rendered).expect("parse output");
381        assert_eq!(saved["ui"]["fullscreen"]["copy_on_select"].as_bool(), Some(true));
382        assert!(saved["ui"].get("show_timeline_pane").is_none());
383        assert!(saved.get("auth").is_none());
384    }
385
386    #[test]
387    fn repository_edit_preserves_explicit_defaults_and_strips_trusted_fields() {
388        let original = "# notes\n[ui.fullscreen]\ncopy_on_select  =  true # pinned\n";
389        let updated: toml::Value = toml::from_str(concat!(
390            "[ui.fullscreen]\ncopy_on_select = true\n",
391            "[auth.copilot]\ncommand = 'helper'\n",
392            "[provider_overrides.openai]\nbase_url = 'https://example.com'\napi_key_env = 'SENSITIVE'\n",
393        ))
394        .expect("parse update");
395
396        let rendered = ConfigManager::merge_repository_config_edit(original, &updated).expect("patch repository");
397        assert_eq!(rendered, original);
398    }
399
400    #[test]
401    fn save_prunes_removed_budget_keys_from_existing_config() {
402        let temp = tempfile::tempdir().expect("tempdir");
403        let path = temp.path().join("vtcode.toml");
404        fs::write(
405            &path,
406            "[agent.harness]\nmax_tool_calls_per_turn = 32\n\n[tools]\nmax_tool_loops = 20\nmax_repeated_tool_calls = 4\n\n[automation.full_auto]\nauto_grant_tool_limits = false\nenabled = true\n",
407        )
408        .expect("seed stale config");
409
410        // The save merges a sparse serialization of this config, so surviving
411        // keys must be non-default to appear in it.
412        let mut config = VTCodeConfig::default();
413        config.tools.max_repeated_tool_calls = 4;
414        config.automation.full_auto.enabled = true;
415        ConfigManager::save_config_to_path(&path, &config).expect("save");
416
417        let rewritten = fs::read_to_string(&path).expect("rewritten config");
418        assert!(!rewritten.contains("max_tool_calls_per_turn"));
419        assert!(!rewritten.contains("max_tool_loops"));
420        assert!(!rewritten.contains("auto_grant_tool_limits"));
421        // Surviving non-default keys stay.
422        assert!(rewritten.contains("max_repeated_tool_calls"));
423        assert!(rewritten.contains("enabled = true"));
424    }
425}