Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(config): graceful per-layer degradation instead of all-or-nothing fallback (#2120)

Maximilian Roos65020f3bc6bb
diff --git a/src/config/user/mod.rs b/src/config/user/mod.rs
index 95a046ee4..51eccf685 100644
--- a/src/config/user/mod.rs
+++ b/src/config/user/mod.rs
@@ -32,8 +32,13 @@ pub use sections::{
StepConfig, SwitchConfig, SwitchPickerConfig, UserProjectOverrides,
};
-/// Distinguishes *why* `UserConfig::load()` failed so callers can emit
-/// targeted diagnostics (file errors with line/col vs env-var attribution).
+/// Describes a problem encountered during config loading. Each variant
+/// identifies which layer failed so callers can emit targeted diagnostics
+/// (file errors with line/col vs env-var attribution).
+///
+/// Used as an error by [`UserConfig::load_with_cause()`] (first issue is
+/// fatal) and as warnings by [`UserConfig::load_with_warnings()`] (issues
+/// are collected, best-effort config returned).
#[derive(Debug)]
pub enum LoadError {
/// A config file failed to parse. The `toml::de::Error` includes
@@ -44,8 +49,12 @@ pub enum LoadError {
err: Box<toml::de::Error>,
},
/// Config files parsed cleanly; applying env-var overrides failed.
- /// `vars` lists the exact `WORKTRUNK_*` env vars that were parsed.
- Env { err: String, vars: Vec<String> },
+ /// `vars` lists the exact `WORKTRUNK_*` env vars that were parsed
+ /// as `(name, value)` pairs.
+ Env {
+ err: String,
+ vars: Vec<(String, String)>,
+ },
/// Validation errors (e.g. empty worktree-path).
Validation(String),
}
@@ -348,9 +357,27 @@ impl UserConfig {
/// Like [`load()`](Self::load), but returns a [`LoadError`] that
/// distinguishes file-level parse failures (with line/col) from
- /// env-var override failures. Used by `Repository::user_config()`
- /// to emit targeted diagnostics.
+ /// env-var override failures.
pub(crate) fn load_with_cause() -> Result<Self, LoadError> {
+ let (config, warnings) = Self::load_with_warnings();
+ if let Some(err) = warnings.into_iter().next() {
+ return Err(err);
+ }
+ Ok(config)
+ }
+
+ /// Load the best config achievable, collecting issues as warnings.
+ ///
+ /// Each config layer (system file, user file, env-var overlay) degrades
+ /// independently — a failure in one preserves data from earlier layers
+ /// instead of falling back to defaults. This means:
+ /// - Bad system config → skipped, user config + env vars still apply
+ /// - Bad user config → skipped, system config + env vars still apply
+ /// - Bad env vars → ignored, file-based config preserved
+ /// - Validation failure → warning emitted, defaults used (invalid config
+ /// causes bad behavior if applied, e.g. empty worktree-path template)
+ pub(crate) fn load_with_warnings() -> (Self, Vec<LoadError>) {
+ let mut warnings = Vec::new();
let mut merged_table = toml::Table::new();
// 1. System config (lowest priority)
@@ -363,8 +390,10 @@ impl UserConfig {
"System config",
);
let migrated = super::deprecation::migrate_content(&content);
- let table = load_config_file(&system_path, &migrated, "System config")?;
- deep_merge_table(&mut merged_table, table);
+ match load_config_file(&system_path, &migrated, "System config") {
+ Ok(table) => deep_merge_table(&mut merged_table, table),
+ Err(e) => warnings.push(e),
+ }
}
// 2. User config (overrides system)
@@ -390,8 +419,10 @@ impl UserConfig {
"User config",
);
- let table = load_config_file(config_path, &migrated, "User config")?;
- deep_merge_table(&mut merged_table, table);
+ match load_config_file(config_path, &migrated, "User config") {
+ Ok(table) => deep_merge_table(&mut merged_table, table),
+ Err(e) => warnings.push(e),
+ }
}
} else if let Some(config_path) = config_path.as_ref()
&& path::is_config_path_explicit()
@@ -409,11 +440,7 @@ impl UserConfig {
let env_vars = parse_worktrunk_env_vars();
if env_vars.is_empty() {
- let config: Self = toml::Value::Table(merged_table)
- .try_into()
- .map_err(|err: toml::de::Error| LoadError::Validation(err.to_string()))?;
- config.validate().map_err(|e| LoadError::Validation(e.0))?;
- return Ok(config);
+ return Self::finalize(merged_table, warnings);
}
// Resolve each env var's type independently: probe typed form against
@@ -424,17 +451,50 @@ impl UserConfig {
let env_overlay = resolve_env_overlay(&file_table, &env_vars);
deep_merge_table(&mut merged_table, env_overlay);
- let config: Self =
- toml::Value::Table(merged_table)
- .try_into()
- .map_err(|err: toml::de::Error| LoadError::Env {
+ match toml::Value::Table(merged_table).try_into::<Self>() {
+ Ok(config) => match config.validate() {
+ Ok(()) => (config, warnings),
+ Err(e) => {
+ warnings.push(LoadError::Validation(e.0));
+ (Self::default(), warnings)
+ }
+ },
+ Err(err) => {
+ warnings.push(LoadError::Env {
err: err.to_string(),
- vars: env_vars.iter().map(|v| v.name.clone()).collect(),
- })?;
-
- config.validate().map_err(|e| LoadError::Validation(e.0))?;
+ vars: env_vars
+ .iter()
+ .map(|v| (v.name.clone(), v.raw_value.clone()))
+ .collect(),
+ });
+ // Env overlay broke deserialization — fall back to file-only config.
+ // Each file was individually validated by load_config_file(), so the
+ // merged table should deserialize cleanly. If it doesn't, finalize()
+ // falls back to defaults.
+ Self::finalize(file_table, warnings)
+ }
+ }
+ }
- Ok(config)
+ /// Deserialize a merged table into `UserConfig`, validate, and collect
+ /// any issues as warnings. Shared by the no-env and env-fallback paths.
+ fn finalize(table: toml::Table, mut warnings: Vec<LoadError>) -> (Self, Vec<LoadError>) {
+ match toml::Value::Table(table).try_into::<Self>() {
+ Ok(config) => match config.validate() {
+ Ok(()) => (config, warnings),
+ Err(e) => {
+ // Validation means the config is semantically wrong (e.g.,
+ // worktree-path=""). Using it causes bad behavior, so fall
+ // back to defaults rather than applying the broken config.
+ warnings.push(LoadError::Validation(e.0));
+ (Self::default(), warnings)
+ }
+ },
+ Err(err) => {
+ warnings.push(LoadError::Validation(err.to_string()));
+ (Self::default(), warnings)
+ }
+ }
}
/// Load configuration from a TOML string for testing.
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 34e9b4cf5..655bb33fa 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -2422,7 +2422,7 @@ fn test_load_error_display_file() {
fn test_load_error_display_env() {
let err = LoadError::Env {
err: "invalid type".into(),
- vars: vec!["WORKTRUNK__LIST__BRANCHES".into()],
+ vars: vec![("WORKTRUNK__LIST__BRANCHES".into(), "not-a-bool".into())],
};
assert_eq!(err.to_string(), "invalid type");
}
@@ -2449,6 +2449,24 @@ fn test_try_parse_value() {
);
}
+// =========================================================================
+// finalize() — defensive fallback
+// =========================================================================
+
+#[test]
+fn test_finalize_with_undeserializable_table() {
+ // finalize() falls back to defaults when the table can't deserialize.
+ // This shouldn't happen in practice (files are individually validated),
+ // but the fallback exists for safety.
+ let mut table = toml::Table::new();
+ table.insert("list".into(), toml::Value::String("not-a-table".into()));
+
+ let (config, warnings) = UserConfig::finalize(table, Vec::new());
+ assert_eq!(config.worktree_path, None); // defaults
+ assert_eq!(warnings.len(), 1);
+ assert!(matches!(&warnings[0], LoadError::Validation(_)));
+}
+
// =========================================================================
// save_to() tests — existing-file branch
// =========================================================================
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 2fe89ded9..35c456de6 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -390,18 +390,19 @@ impl Repository {
/// for operations that require the full `UserConfig` (e.g., path template formatting,
/// approval state, hook resolution).
///
- /// Falls back to defaults on load errors so a single bad field does not break
- /// unrelated commands, but surfaces the error on stderr — a silent `log::warn!`
- /// would hide it from anyone not running with `RUST_LOG=warn`.
+ /// Each config layer (system file, user file, env vars) degrades
+ /// independently — a failure in one preserves data from earlier layers.
+ /// Issues are surfaced on stderr so they're visible without `RUST_LOG`.
pub fn user_config(&self) -> &UserConfig {
self.cache.user_config.get_or_init(|| {
- UserConfig::load_with_cause()
- .inspect_err(|err| match err {
+ let (config, warnings) = UserConfig::load_with_warnings();
+ for warning in &warnings {
+ match warning {
LoadError::File { path, label, err } => {
crate::styling::eprintln!(
"{}",
crate::styling::warning_message(format!(
- "{label} at {} failed to parse, using defaults",
+ "{label} at {} failed to parse, skipping",
crate::path::format_path_for_display(path),
))
);
@@ -411,33 +412,33 @@ impl Repository {
);
}
LoadError::Env { err, vars } => {
+ let var_list: Vec<_> = vars
+ .iter()
+ .map(|(name, value)| format!("{name}={value}"))
+ .collect();
crate::styling::eprintln!(
"{}",
crate::styling::warning_message(format!(
- "Failed to apply WORKTRUNK_* env var override, using defaults: {}",
- err.trim()
+ "Ignoring env var overrides: {}",
+ var_list.join(", ")
))
);
- if !vars.is_empty() {
- crate::styling::eprintln!(
- "{}",
- crate::styling::hint_message(format!(
- "Currently set: {}",
- vars.join(", ")
- ))
- );
- }
+ crate::styling::eprintln!(
+ "{}",
+ crate::styling::format_with_gutter(err.trim(), None)
+ );
}
LoadError::Validation(err) => {
crate::styling::eprintln!(
"{}",
crate::styling::warning_message(format!(
- "Failed to load user config, using defaults: {err}"
+ "Config validation warning: {err}"
))
);
}
- })
- .unwrap_or_default()
+ }
+ }
+ config
})
}
diff --git a/tests/integration_tests/list_config.rs b/tests/integration_tests/list_config.rs
index 9eb205c42..a4468e1fb 100644
--- a/tests/integration_tests/list_config.rs
+++ b/tests/integration_tests/list_config.rs
@@ -492,6 +492,43 @@ fn test_list_config_env_override_mixed_typed_and_string(repo: TestRepo) {
});
}
+/// Bad env var with valid file config: the file config must be preserved.
+/// Before the load_with_warnings refactor, any env var failure would drop
+/// the entire config (including file-based settings) to defaults.
+#[rstest]
+fn test_list_config_env_override_bad_value_preserves_file_config(repo: TestRepo) {
+ // File config enables branch listing
+ fs::write(repo.test_config_path(), "[list]\nbranches = true\n").unwrap();
+ repo.run_git(&["branch", "feature"]);
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ // Bad env var: "not-a-bool" for a bool field
+ cmd.env("WORKTRUNK__LIST__BRANCHES", "not-a-bool");
+ cmd.arg("list").current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
+/// Env var that deserializes successfully but fails validation (empty
+/// worktree-path). Exercises the validation-after-env-overlay path.
+#[rstest]
+fn test_list_config_env_override_validation_failure(repo: TestRepo) {
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ // Empty worktree-path deserializes as Some("") but fails validation
+ cmd.env("WORKTRUNK_WORKTREE_PATH", "");
+ cmd.arg("list").current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
+
/// Bad values in non-section fields (projects, skip-*-prompt) must still be
/// attributed to the file, not to env vars.
#[rstest]
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_preserves_file_config.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_preserves_file_config.snap
new file mode 100644
index 000000000..2741ff821
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_preserves_file_config.snap
@@ -0,0 +1,57 @@
+---
+source: tests/integration_tests/list_config.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK__LIST__BRANCHES: not-a-bool
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
+@ main ^| | . 05a4a45d 16h Initial commit
++ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b ↑ ↑1 ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 16h Add feature-c file
+ feature /_ 05a4a45d 16h Initial commit
+
+○ Showing 4 worktrees, 1 branches, 3 ahead
+
+----- stderr -----
+▲ Ignoring env var overrides: WORKTRUNK__LIST__BRANCHES=not-a-bool
+  invalid type: string "not-a-bool", expected a boolean
+  in `list.branches`
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap
index 30e1f0114..045a64c81 100644
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_bad_value_warns_on_stderr.snap
@@ -51,6 +51,6 @@ exit_code: 0
○ Showing 4 worktrees, 3 ahead
----- stderr -----
-▲ Failed to apply WORKTRUNK_* env var override, using defaults: invalid type: string "not-a-bool", expected a boolean
-in `list.branches`
-↳ Currently set: WORKTRUNK__LIST__BRANCHES
+▲ Ignoring env var overrides: WORKTRUNK__LIST__BRANCHES=not-a-bool
+  invalid type: string "not-a-bool", expected a boolean
+  in `list.branches`
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snap
new file mode 100644
index 000000000..ea3a29e61
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_env_override_validation_failure.snap
@@ -0,0 +1,54 @@
+---
+source: tests/integration_tests/list_config.rs
+info:
+ program: wt
+ args:
+ - list
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_WORKTREE_PATH: ""
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Remote⇅ Path Commit Age Message
+@ main ^| | . 05a4a45d 16h Initial commit
++ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b ↑ ↑1 ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 16h Add feature-c file
+
+○ Showing 4 worktrees, 3 ahead
+
+----- stderr -----
+▲ Config validation warning: worktree-path cannot be empty
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap
index cceebdacc..d3745c3f5 100644
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_config_warns_on_stderr.snap
@@ -50,7 +50,7 @@ exit_code: 0
○ Showing 4 worktrees, 3 ahead
----- stderr -----
-▲ User config at [TEST_CONFIG] failed to parse, using defaults
+▲ User config at [TEST_CONFIG] failed to parse, skipping
  TOML parse error at line 2, column 12
  |
  2 | branches = "not-a-bool"
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_non_section_field_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_non_section_field_warns_on_stderr.snap
index 1d1fd785a..477ed0231 100644
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_non_section_field_warns_on_stderr.snap
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_non_section_field_warns_on_stderr.snap
@@ -50,7 +50,7 @@ exit_code: 0
○ Showing 4 worktrees, 3 ahead
----- stderr -----
-▲ User config at [TEST_CONFIG] failed to parse, using defaults
+▲ User config at [TEST_CONFIG] failed to parse, skipping
  TOML parse error at line 1, column 33
  |
  1 | skip-shell-integration-prompt = "not-a-bool"
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_non_section_field.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_non_section_field.snap
index ea862c711..f4899714e 100644
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_non_section_field.snap
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_non_section_field.snap
@@ -50,7 +50,7 @@ exit_code: 0
○ Showing 4 worktrees, 1 with changes, 3 ahead
----- stderr -----
-▲ System config at [TEST_SYSTEM_CONFIG_FILE] failed to parse, using defaults
+▲ System config at [TEST_SYSTEM_CONFIG_FILE] failed to parse, skipping
  TOML parse error at line 1, column 33
  |
  1 | skip-shell-integration-prompt = "not-a-bool"
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_warns_on_stderr.snap
index a21b3bc18..c24cc9a3d 100644
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_warns_on_stderr.snap
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_malformed_system_config_warns_on_stderr.snap
@@ -50,7 +50,7 @@ exit_code: 0
○ Showing 4 worktrees, 1 with changes, 3 ahead
----- stderr -----
-▲ System config at [TEST_SYSTEM_CONFIG_FILE] failed to parse, using defaults
+▲ System config at [TEST_SYSTEM_CONFIG_FILE] failed to parse, skipping
  TOML parse error at line 2, column 12
  |
  2 | branches = "not-a-bool"
diff --git a/tests/snapshots/integration__integration_tests__list_config__list_config_validation_error_warns_on_stderr.snap b/tests/snapshots/integration__integration_tests__list_config__list_config_validation_error_warns_on_stderr.snap
index 7479ed024..9229c3116 100644
--- a/tests/snapshots/integration__integration_tests__list_config__list_config_validation_error_warns_on_stderr.snap
+++ b/tests/snapshots/integration__integration_tests__list_config__list_config_validation_error_warns_on_stderr.snap
@@ -50,4 +50,4 @@ exit_code: 0
○ Showing 4 worktrees, 3 ahead
----- stderr -----
-▲ Failed to load user config, using defaults: worktree-path cannot be empty
+▲ Config validation warning: worktree-path cannot be empty