vtcode-config 0.185.1

Config loader components shared across VT Code and downstream adopters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use super::*;

#[test]
fn default_config_selects_build_primary_agent() {
    assert_eq!(VTCodeConfig::default().default_primary_agent, "build");
}

#[test]
fn compiled_default_config_contains_release_loop_budgets() {
    let config = VTCodeConfig::default();

    assert_eq!(config.automation.full_auto.max_turns, tool_limits::DEFAULT_FULL_AUTO_MAX_TURNS);
    assert_eq!(config.agent.max_conversation_turns, tool_limits::DEFAULT_MAX_CONVERSATION_TURNS);
}

/// A config file that names a section but omits keys inside it must fall back
/// to the same built-in defaults as `VTCodeConfig::default()`, not to the
/// type's zero value.
///
/// Regression: these fields carried a bare `#[serde(default)]`, so `[security]`
/// with any single key silently flipped `zero_trust_mode`/`encrypt_payloads`
/// from `true` to `false`, and a `[commands]` section dropped all 57 built-in
/// `deny_list` entries — including `rm -rf /` — to nothing. With no section at
/// all the inner `Default` applies, which is why the bug only appeared for
/// partially specified configs.
#[test]
fn partial_section_keeps_builtin_defaults() {
    // Each section contains exactly one key, so every sibling must come from
    // its own default_*() source.
    let partial: VTCodeConfig = toml::from_str(
        r#"
[security]
human_in_the_loop = true

[commands]
approval_prefixes = []

[telemetry]
trajectory_enabled = true

[plugins]
manifests = []
"#,
    )
    .expect("partial sections parse");

    let compiled = VTCodeConfig::default();

    assert_eq!(
        partial.security.zero_trust_mode, compiled.security.zero_trust_mode,
        "omitting zero_trust_mode must not disable zero-trust checks"
    );
    assert!(partial.security.zero_trust_mode, "zero-trust must stay on for a partial [security]");

    assert_eq!(partial.commands.deny_list, compiled.commands.deny_list, "built-in deny rules must survive");
    assert!(!partial.commands.deny_list.is_empty(), "a [commands] section must not wipe the deny list");
    assert_eq!(partial.commands.allow_glob, compiled.commands.allow_glob);
    assert_eq!(partial.commands.allow_list, compiled.commands.allow_list);
    assert_eq!(partial.commands.deny_regex, compiled.commands.deny_regex);
    assert_eq!(
        partial.telemetry.trajectory_max_files, compiled.telemetry.trajectory_max_files,
        "sibling telemetry keys must keep their defaults"
    );

    // An explicit value must still win over the built-in.
    let overridden: VTCodeConfig = toml::from_str("[commands]\ndeny_list = []\n").expect("explicit parse");
    assert!(overridden.commands.deny_list.is_empty(), "an explicit empty list must still override");
}

/// `data/default_config.toml` is what `vtcode init` scaffolds as the user's
/// starting config, so a section it declares must not weaken the compiled
/// defaults by restating a subset of them.
///
/// Restating a list *replaces* it during deserialization; it does not extend it.
/// The scaffold therefore omits the curated security lists, and this test pins
/// that: a scaffolded config must carry at least the safety rules a config with
/// no file at all would get.
///
/// Deliberately narrow rather than a full field-by-field diff: the scaffold
/// legitimately differs from `VTCodeConfig::default()` in quickstart
/// presentation (provider, theme, status-line timings, a commented example MCP
/// server). Only the security-relevant invariants are asserted here.
#[test]
fn scaffold_config_does_not_weaken_security_defaults() {
    let scaffold_text = include_str!("../../../data/default_config.toml");
    let scaffold: VTCodeConfig = toml::from_str(scaffold_text).expect("scaffold config must parse");
    let compiled = VTCodeConfig::default();

    assert!(
        scaffold.commands.deny_list.len() >= compiled.commands.deny_list.len(),
        "scaffold deny_list has {} entries but the built-in default has {}; restating a shorter \
         list replaces the built-in rules instead of extending them",
        scaffold.commands.deny_list.len(),
        compiled.commands.deny_list.len()
    );
    assert!(
        scaffold.commands.deny_regex.len() >= compiled.commands.deny_regex.len(),
        "scaffold deny_regex must not drop the built-in deny patterns"
    );
    assert!(
        scaffold.commands.deny_glob.len() >= compiled.commands.deny_glob.len(),
        "scaffold deny_glob must not drop the built-in deny globs"
    );

    // The same rule for the security switches: a scaffolded config must not be
    // less strict than a default-constructed one.
    assert!(
        scaffold.security.zero_trust_mode || !compiled.security.zero_trust_mode,
        "scaffold must not disable zero-trust checks that are on by default"
    );
    assert!(
        scaffold.tools.policies.len() <= compiled.tools.policies.len(),
        "scaffold must not add tool policies the built-in default does not set"
    );
}

/// The scaffold must not contradict the compiled program-status default: it
/// either omits the section or restates the default, so `vtcode init` users
/// get the documented on-by-default reporting.
#[test]
fn scaffold_config_inherits_program_status_default() {
    let scaffold_text = include_str!("../../../data/default_config.toml");
    let scaffold: VTCodeConfig = toml::from_str(scaffold_text).expect("scaffold config must parse");
    let compiled = VTCodeConfig::default();
    assert_eq!(
        scaffold.ui.program_status.enabled, compiled.ui.program_status.enabled,
        "scaffold program_status.enabled must match the compiled default"
    );
}

/// The scaffold must never restate a removed configuration key: `vtcode init`
/// writes it into the user's config verbatim, and every subsequent load then
/// raises the removed-key warning against a file the tool itself created. Pin
/// the scaffold to the same path list the loader warns on, so the template
/// cannot drift behind the schema again.
/// The scaffold's full-auto allowlist must match the compiled default: every
/// entry must name a tool in the default profile, otherwise a scaffolded
/// config silently collapses exec toward a zero-tool catalog on local routes
/// (2026-11-23: the scaffold listed legacy file-tool names that match nothing
/// in the default VtCode profile).
#[test]
fn scaffold_full_auto_allowlist_matches_compiled_default() {
    let scaffold_text = include_str!("../../../data/default_config.toml");
    let scaffold: VTCodeConfig = toml::from_str(scaffold_text).expect("scaffold config must parse");
    let compiled = VTCodeConfig::default();
    assert_eq!(
        scaffold.automation.full_auto.allowed_tools, compiled.automation.full_auto.allowed_tools,
        "scaffold allowed_tools must mirror default_full_auto_allowed_tools"
    );
}

#[test]
fn scaffold_config_carries_no_removed_keys() {
    let scaffold_text = include_str!("../../../data/default_config.toml");
    let scaffold: toml::Value = toml::from_str(scaffold_text).expect("scaffold config must parse");
    let stale = manager::removed_config_key_paths_present(&scaffold);
    assert!(
        stale.is_empty(),
        "scaffold still carries removed keys {stale:?}; drop them from data/default_config.toml"
    );
}

#[test]
fn tool_profile_parses_and_serialises_in_tools_table() {
    let config: VTCodeConfig = toml::from_str(
        r#"
[tools]
profile = "advanced_vtcode"
"#,
    )
    .expect("tool profile should parse from the tools table");
    assert_eq!(config.tools.profile, crate::core::ToolProfile::AdvancedVtCode);

    let serialised = toml::to_string(&config).expect("configuration should serialise");
    assert!(serialised.contains("[tools]"));
    assert!(serialised.contains("profile = \"advanced_vtcode\""));
}

#[test]
#[serial]
fn test_layered_config_loading() {
    let workspace = assert_fs::TempDir::new().expect("failed to create workspace");
    let workspace_root = workspace.path();

    // 1. User config
    let home_dir = workspace_root.join("home");
    fs::create_dir_all(&home_dir).expect("failed to create home dir");
    let user_config_path = home_dir.join("vtcode.toml");
    fs::write(&user_config_path, "agent.provider = \"anthropic\"").expect("failed to write user config");

    // 2. Workspace config
    let workspace_config_path = workspace_root.join("vtcode.toml");
    fs::write(&workspace_config_path, "agent.default_model = \"claude-sonnet-5\"")
        .expect("failed to write workspace config");

    let static_paths = StaticWorkspacePaths::new(workspace_root, workspace_root.join(".vtcode"));
    let provider = WorkspacePathsDefaults::new(Arc::new(static_paths)).with_home_paths(vec![user_config_path.clone()]);

    defaults::provider::with_config_defaults_provider_for_test(Arc::new(provider), || {
        let manager = ConfigManager::load_from_workspace(workspace_root).expect("failed to load config");

        assert_eq!(manager.config().agent.provider, "anthropic");
        assert_eq!(manager.config().agent.default_model, "claude-sonnet-5");

        let layers = manager.layer_stack().layers();
        // User + Workspace
        assert_eq!(layers.len(), 2);
        assert!(matches!(layers[0].source, ConfigLayerSource::User { .. }));
        assert!(matches!(layers[1].source, ConfigLayerSource::Workspace { .. }));
    });
}

#[test]
#[serial]
fn canonical_xdg_user_config_overrides_legacy_user_config() {
    let workspace = assert_fs::TempDir::new().expect("workspace");
    let legacy_path = workspace.path().join("legacy").join("vtcode.toml");
    let canonical_path = workspace.path().join("xdg").join("vtcode.toml");
    fs::create_dir_all(legacy_path.parent().expect("legacy parent")).expect("legacy dir");
    fs::create_dir_all(canonical_path.parent().expect("canonical parent")).expect("canonical dir");
    fs::write(&legacy_path, "agent.provider = \"openai\"\n").expect("legacy config");
    fs::write(&canonical_path, "agent.provider = \"anthropic\"\n").expect("canonical config");

    let paths = StaticWorkspacePaths::new(workspace.path(), workspace.path().join(".vtcode"));
    let provider =
        WorkspacePathsDefaults::new(Arc::new(paths)).with_home_paths(vec![legacy_path.clone(), canonical_path.clone()]);

    defaults::provider::with_config_defaults_provider_for_test(Arc::new(provider), || {
        let manager = ConfigManager::load_from_workspace(workspace.path()).expect("load config");
        assert_eq!(manager.config().agent.provider, "anthropic");
        let user_files = manager
            .layer_stack()
            .layers()
            .iter()
            .filter_map(|layer| match &layer.source {
                ConfigLayerSource::User { file } => Some(file),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            user_files
                .into_iter()
                .map(|path| canonicalize(path).expect("canonical user path"))
                .collect::<Vec<_>>(),
            vec![
                canonicalize(&legacy_path).expect("canonical legacy path"),
                canonicalize(&canonical_path).expect("canonical XDG path"),
            ]
        );
    });
}

#[test]
#[serial]
fn system_config_candidates_are_loaded_low_to_high_without_duplicates() {
    let workspace = assert_fs::TempDir::new().expect("workspace");
    let first_path = workspace.path().join("system-first.toml");
    let second_path = workspace.path().join("system-second.toml");
    fs::write(&first_path, "agent.provider = \"openai\"\n").expect("first system config");
    fs::write(&second_path, "agent.provider = \"anthropic\"\n").expect("second system config");

    let paths = StaticWorkspacePaths::new(workspace.path(), workspace.path().join(".vtcode"));
    let provider = WorkspacePathsDefaults::new(Arc::new(paths))
        .with_home_paths(Vec::new())
        .with_system_config_paths(vec![second_path.clone(), first_path.clone(), first_path.clone()]);

    defaults::provider::with_config_defaults_provider_for_test(Arc::new(provider), || {
        let manager = ConfigManager::load_from_workspace(workspace.path()).expect("load config");
        let system_files = manager
            .layer_stack()
            .layers()
            .iter()
            .filter_map(|layer| match &layer.source {
                ConfigLayerSource::System { file } => Some(file),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(manager.config().agent.provider, "openai");
        assert_eq!(
            system_files
                .into_iter()
                .map(|path| canonicalize(path).expect("canonical system path"))
                .collect::<Vec<_>>(),
            vec![
                canonicalize(&second_path).expect("canonical second system path"),
                canonicalize(&first_path).expect("canonical first system path"),
            ]
        );
    });
}

#[test]
#[serial]
fn save_config_uses_the_canonical_path_captured_during_load() {
    let workspace = assert_fs::TempDir::new().expect("workspace");
    let canonical_path = workspace.path().join("canonical/vtcode.toml");
    let other_path = workspace.path().join("other/vtcode.toml");
    fs::create_dir_all(canonical_path.parent().expect("canonical parent")).expect("canonical directory");
    fs::write(&canonical_path, "agent.provider = \"openai\"\n").expect("canonical config");

    let paths = StaticWorkspacePaths::new(workspace.path(), workspace.path().join(".vtcode"));
    let provider = WorkspacePathsDefaults::new(Arc::new(paths)).with_home_paths(vec![canonical_path.clone()]);

    defaults::provider::with_config_defaults_provider_for_test(Arc::new(provider), || {
        let mut manager = ConfigManager::load_from_workspace(workspace.path()).expect("load config");
        fs::remove_file(&canonical_path).expect("remove loaded config before save");

        let replacement_paths = StaticWorkspacePaths::new(workspace.path(), workspace.path().join(".vtcode"));
        let replacement_provider =
            WorkspacePathsDefaults::new(Arc::new(replacement_paths)).with_home_paths(vec![other_path.clone()]);
        let previous = defaults::provider::install_config_defaults_provider(Arc::new(replacement_provider));

        let config = manager.config().clone();
        manager.save_config(&config).expect("save canonical config");

        let _ = defaults::provider::install_config_defaults_provider(previous);

        assert!(canonical_path.exists());
        assert!(!other_path.exists());
    });
}

#[test]
#[serial]
fn test_invalid_layer_is_reported_with_source_context() {
    let workspace = assert_fs::TempDir::new().expect("failed to create workspace");
    let workspace_root = workspace.path();

    let home_dir = workspace_root.join("home");
    fs::create_dir_all(&home_dir).expect("failed to create home dir");
    let user_config_path = home_dir.join("vtcode.toml");
    fs::write(&user_config_path, "[agent\nprovider = \"openai\"").expect("failed to write invalid user config");

    let workspace_config_path = workspace_root.join("vtcode.toml");
    fs::write(&workspace_config_path, "agent.provider = \"anthropic\"").expect("failed to write workspace config");

    let static_paths = StaticWorkspacePaths::new(workspace_root, workspace_root.join(".vtcode"));
    let provider = WorkspacePathsDefaults::new(Arc::new(static_paths)).with_home_paths(vec![user_config_path.clone()]);

    defaults::provider::with_config_defaults_provider_for_test(Arc::new(provider), || {
        let result = ConfigManager::load_from_workspace(workspace_root);
        assert!(result.is_err(), "expected load to fail for invalid layer");
        let error = match result {
            Ok(_) => String::new(),
            Err(err) => format!("{err:#}"),
        };
        assert!(
            error.contains(&user_config_path.display().to_string()),
            "error should include invalid layer path, got: {error}"
        );
    });
}

#[test]
#[serial]
fn test_config_builder_overrides() {
    let workspace = assert_fs::TempDir::new().expect("failed to create workspace");
    let workspace_root = workspace.path();

    let workspace_config_path = workspace_root.join("vtcode.toml");
    fs::write(&workspace_config_path, "agent.provider = \"openai\"").expect("failed to write workspace config");

    let static_paths = StaticWorkspacePaths::new(workspace_root, workspace_root.join(".vtcode"));
    let provider = WorkspacePathsDefaults::new(Arc::new(static_paths)).with_home_paths(vec![]);

    defaults::provider::with_config_defaults_provider_for_test(Arc::new(provider), || {
        let manager = ConfigBuilder::new()
            .workspace(workspace_root.to_path_buf())
            .cli_override("agent.provider".to_string(), toml::Value::String("gemini".to_string()))
            .cli_override("agent.default_model".to_string(), toml::Value::String("gemini-1.5-pro".to_string()))
            .cli_overrides(&[("tools.profile".to_string(), "advanced_vtcode".to_string())])
            .build()
            .expect("failed to build config");

        assert_eq!(manager.config().agent.provider, "gemini");
        assert_eq!(manager.config().agent.default_model, "gemini-1.5-pro");
        assert_eq!(manager.config().tools.profile, crate::core::ToolProfile::AdvancedVtCode);

        let layers = manager.layer_stack().layers();
        // Workspace + Runtime
        assert_eq!(layers.len(), 2);
        assert!(matches!(layers[0].source, ConfigLayerSource::Workspace { .. }));
        assert!(matches!(layers[1].source, ConfigLayerSource::Runtime));
    });
}

#[test]
fn removed_config_key_paths_detect_stale_keys() {
    use crate::loader::manager::removed_config_key_paths_present;

    let stale: toml::Value = toml::from_str(
        "[agent.harness]\nmax_tool_calls_per_turn = 32\n\n\
         [tools]\nmax_tool_loops = 20\n\n\
         [automation.full_auto]\nauto_grant_tool_limits = false\n\n\
         [telemetry]\nsample_interval_ms = 1000\nretention_days = 14\nbottleneck_tracing = false\n\n\
         [ui]\nshow_timeline_pane = false\n\n\
         [context]\ntrim_to_percent = 60\n\n\
         [prompt_cache.providers.anthropic]\ndefault_ttl_seconds = 300\n",
    )
    .unwrap();
    let found = removed_config_key_paths_present(&stale);
    assert_eq!(found.len(), 9, "every removed config key path must be detected");

    let clean: toml::Value = toml::from_str("[tools]\nmax_repeated_tool_calls = 2\n").unwrap();
    assert!(removed_config_key_paths_present(&clean).is_empty());
}