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        Self::remove_path_and_prune_empty_parents(table, &["agent", "harness", "max_tool_calls_per_turn"]);
167        Self::remove_path_and_prune_empty_parents(table, &["tools", "max_tool_loops"]);
168        Self::remove_path_and_prune_empty_parents(table, &["automation", "full_auto", "auto_grant_tool_limits"]);
169    }
170
171    fn remove_table_keys(table: &mut toml_edit::Table, section: &str, keys: &[&str]) {
172        let Some(section) = table.get_mut(section).and_then(toml_edit::Item::as_table_mut) else {
173            return;
174        };
175
176        for key in keys {
177            section.remove(key);
178        }
179    }
180
181    pub fn sparse_config_value(config: &VTCodeConfig) -> Result<toml::Value> {
182        let mut value = toml::Value::try_from(config).context("Failed to serialize configuration")?;
183        let default_value =
184            toml::Value::try_from(VTCodeConfig::default()).context("Failed to serialize default configuration")?;
185        Self::prune_default_values(&mut value, &default_value);
186        Ok(value)
187    }
188
189    fn prune_default_values(value: &mut toml::Value, default_value: &toml::Value) -> bool {
190        match (value, default_value) {
191            (toml::Value::Table(table), toml::Value::Table(default_table)) => {
192                table.retain(|key, child| {
193                    default_table
194                        .get(key)
195                        .is_none_or(|default_child| !Self::prune_default_values(child, default_child))
196                });
197                table.is_empty()
198            }
199            (value, default_value) => value == default_value,
200        }
201    }
202
203    /// Merge TOML documents, preserving comments and structure from original
204    fn merge_sparse_toml_documents(
205        original: &mut toml_edit::DocumentMut,
206        new: &toml_edit::DocumentMut,
207        default_doc: &toml_edit::DocumentMut,
208    ) {
209        Self::merge_sparse_tables(original.as_table_mut(), new.as_table(), default_doc.as_table());
210    }
211
212    fn merge_sparse_tables(original: &mut toml_edit::Table, new: &toml_edit::Table, default_table: &toml_edit::Table) {
213        let mut remove_keys = Vec::with_capacity(default_table.len());
214
215        for (key, default_value) in default_table.iter() {
216            if let Some(new_value) = new.get(key) {
217                if let Some(original_value) = original.get_mut(key) {
218                    Self::merge_sparse_items(original_value, new_value, default_value);
219                } else {
220                    original[key] = new_value.clone();
221                }
222            } else {
223                let Some(original_value) = original.get_mut(key) else {
224                    continue;
225                };
226                if Self::remove_known_default_item(original_value, default_value) {
227                    remove_keys.push(key.to_string());
228                }
229            }
230        }
231
232        for key in remove_keys {
233            original.remove(&key);
234        }
235
236        for (key, new_value) in new.iter() {
237            if default_table.contains_key(key) {
238                continue;
239            }
240            if let Some(original_value) = original.get_mut(key) {
241                *original_value = new_value.clone();
242            } else {
243                original[key] = new_value.clone();
244            }
245        }
246    }
247
248    fn merge_sparse_items(original: &mut toml_edit::Item, new: &toml_edit::Item, default_value: &toml_edit::Item) {
249        match (original, new, default_value) {
250            (
251                toml_edit::Item::Table(orig_table),
252                toml_edit::Item::Table(new_table),
253                toml_edit::Item::Table(default_table),
254            ) => Self::merge_sparse_tables(orig_table, new_table, default_table),
255            (orig, new, _) => {
256                *orig = new.clone();
257            }
258        }
259    }
260
261    fn remove_known_default_item(original: &mut toml_edit::Item, default_value: &toml_edit::Item) -> bool {
262        match (original, default_value) {
263            (toml_edit::Item::Table(orig_table), toml_edit::Item::Table(default_table)) => {
264                let mut remove_keys = Vec::new();
265                for (key, default_child) in default_table.iter() {
266                    let Some(orig_child) = orig_table.get_mut(key) else {
267                        continue;
268                    };
269                    if Self::remove_known_default_item(orig_child, default_child) {
270                        remove_keys.push(key.to_string());
271                    }
272                }
273                for key in remove_keys {
274                    orig_table.remove(&key);
275                }
276                orig_table.is_empty()
277            }
278            _ => true,
279        }
280    }
281
282    /// Persist configuration to the manager's associated path or workspace
283    pub fn save_config(&mut self, config: &VTCodeConfig) -> Result<()> {
284        let (target, repository_controlled) = if let Some(path) = &self.config_path {
285            if self.write_global_config_to_canonical || self.is_global_config_path(path) {
286                (self.preferred_user_config_path().unwrap_or_else(|| path.clone()), false)
287            } else {
288                (path.clone(), !self.explicit_config_is_trusted)
289            }
290        } else if let Some(workspace_root) = &self.workspace_root {
291            (workspace_root.join(&self.config_file_name), !self.explicit_config_is_trusted)
292        } else {
293            let cwd = std::env::current_dir().context("Failed to resolve current directory")?;
294            (cwd.join(&self.config_file_name), !self.explicit_config_is_trusted)
295        };
296
297        if repository_controlled {
298            Self::save_repository_config_to_path(target, config)?;
299        } else {
300            Self::save_config_to_path(target, config)?;
301        }
302
303        #[cfg(not(test))]
304        if let Some(workspace) = &self.workspace_root {
305            Self::invalidate_workspace_cache(workspace);
306        }
307
308        self.sync_from_config(config)
309    }
310
311    fn is_global_config_path(&self, path: &Path) -> bool {
312        self.layer_stack.layers().iter().any(|layer| {
313            layer.is_enabled()
314                && matches!(layer.source, ConfigLayerSource::System { .. } | ConfigLayerSource::User { .. })
315                && match &layer.source {
316                    ConfigLayerSource::System { file } | ConfigLayerSource::User { file } => file == path,
317                    _ => false,
318                }
319        })
320    }
321
322    /// Sync internal config from a saved config
323    /// Call this after save_config to keep internal state in sync
324    fn sync_from_config(&mut self, config: &VTCodeConfig) -> Result<()> {
325        self.config = config.clone();
326        Ok(())
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn save_prunes_removed_budget_keys_from_existing_config() {
336        let temp = tempfile::tempdir().expect("tempdir");
337        let path = temp.path().join("vtcode.toml");
338        fs::write(
339            &path,
340            "[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",
341        )
342        .expect("seed stale config");
343
344        // The save merges a sparse serialization of this config, so surviving
345        // keys must be non-default to appear in it.
346        let mut config = VTCodeConfig::default();
347        config.tools.max_repeated_tool_calls = 4;
348        config.automation.full_auto.enabled = true;
349        ConfigManager::save_config_to_path(&path, &config).expect("save");
350
351        let rewritten = fs::read_to_string(&path).expect("rewritten config");
352        assert!(!rewritten.contains("max_tool_calls_per_turn"));
353        assert!(!rewritten.contains("max_tool_loops"));
354        assert!(!rewritten.contains("auto_grant_tool_limits"));
355        // Surviving non-default keys stay.
356        assert!(rewritten.contains("max_repeated_tool_calls"));
357        assert!(rewritten.contains("enabled = true"));
358    }
359}