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