Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(config): require an explicit path for config mutations (#2862)
Maximilian Roosc06b71b379a0
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 004445e73..1967de43f 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -22,7 +22,7 @@ use std::path::Path;use anyhow::Context;use color_print::cformat;-use worktrunk::config::Approvals;+use worktrunk::config::{Approvals, require_approvals_path};use worktrunk::git::{GitError, HookType};use worktrunk::styling::{INFO_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter, format_with_gutter,@@ -77,7 +77,10 @@ pub fn approve_command_batch(.iter().map(|cmd| cmd.command.template.clone()).collect();- if let Err(e) = fresh_approvals.approve_commands(project_id.to_string(), commands, None) {+ let save_result = require_approvals_path().and_then(|path| {+ fresh_approvals.approve_commands(project_id.to_string(), commands, &path)+ });+ if let Err(e) = save_result {eprintln!("{}",warning_message(format!("Failed to save command approval: {e}"))diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rsindex b273aea1f..bbe85c2f9 100644--- a/src/commands/config/approvals.rs+++ b/src/commands/config/approvals.rs@@ -6,7 +6,7 @@use anyhow::Context;use strum::IntoEnumIterator;use worktrunk::HookType;-use worktrunk::config::Approvals;+use worktrunk::config::{Approvals, require_approvals_path};use worktrunk::git::{GitError, Repository};use worktrunk::styling::{eprintln, info_message, success_message};@@ -96,7 +96,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {}approvals- .clear_all(None)+ .clear_all(&require_approvals_path()?).context("Failed to clear approvals")?;eprintln!(@@ -124,7 +124,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {}approvals- .revoke_project(&project_id, None)+ .revoke_project(&project_id, &require_approvals_path()?).context("Failed to clear project approvals")?;eprintln!(diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rsindex 4abe48ce8..7f952b13e 100644--- a/src/commands/hook_plan.rs+++ b/src/commands/hook_plan.rs@@ -187,20 +187,20 @@ impl HookPlan {out}- /// Interactive / `--yes` gate. Reuses [`approve_command_batch`] so the- /// prompt, the `--yes` path, and the saved approvals are byte-identical to- /// before. `Ok(None)` means the user declined — the caller prints its own+ /// Interactive / `--yes` gate. The interactive path reuses+ /// [`approve_command_batch`] for its prompt and for the approvals it+ /// saves. `Ok(None)` means the user declined: the caller prints its own/// "continuing without hooks" message and proceeds with/// [`ApprovedHookPlan::empty`].///- /// When no project-source command needs the gate (no project config, or- /// only user hooks), this returns the frozen plan **without** loading- /// `Approvals` or requiring `project_id`. That keeps a malformed- /// `approvals.toml` or an unresolvable project identifier from aborting a- /// command that has nothing to authorize, matching the pre-plan behaviour- /// where the empty-batch fast path ran before any approval state was- /// touched. `project_id` is therefore `Option`: it is consulted only when- /// there is something to approve, where it must be present.+ /// `Approvals` is loaded only on the interactive path. Two paths skip the+ /// load. When nothing project-sourced needs the gate (no project config,+ /// or only user hooks) the frozen plan returns at once. `--yes` also+ /// approves every project command unconditionally and persists nothing, so+ /// it has no approval state to read. A malformed `approvals.toml` therefore+ /// never aborts a command that would not consult it. `project_id` is+ /// `Option` only because that no-approvable fast path needs none; every+ /// path that has something to approve requires it.pub fn approve(self,project_id: Option<&str>,@@ -214,8 +214,14 @@ impl HookPlan {}let project_id =project_id.context("project identifier is required to approve project commands")?;- let approvals = Approvals::load().context("Failed to load approvals")?;- let approved = approve_command_batch(&approvable, project_id, &approvals, yes, false)?;+ // `approve_command_batch` with `yes = true` is an unconditional+ // `Ok(true)`, so loading `Approvals` here would be dead work.+ let approved = if yes {+ true+ } else {+ let approvals = Approvals::load().context("Failed to load approvals")?;+ approve_command_batch(&approvable, project_id, &approvals, false, false)?+ };if !approved {return Ok(None);}@@ -462,7 +468,7 @@ mod tests {.approve_command("proj".to_string(),"echo project-hook".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();let mut builder = HookPlanBuilder::new();diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 95aa7f9d9..3b049972e 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -385,7 +385,7 @@ pub fn offer_bare_repo_worktree_path_fix(config.set_project_worktree_path(&project_id,BARE_REPO_WORKTREE_PATH.to_string(),- None,+ &worktrunk::config::require_config_path()?,)?;print_accepted_message(&display_path, &config_path_display);Ok(true)diff --git a/src/config/approvals.rs b/src/config/approvals.rsindex 1410098f2..f3ae66625 100644--- a/src/config/approvals.rs+++ b/src/config/approvals.rs@@ -54,12 +54,23 @@ struct ApprovedProject {// Path resolution// =========================================================================-/// Get the approvals file path.+/// Resolve the approvals file path.////// Priority:/// 1. `WORKTRUNK_APPROVALS_PATH` environment variable-/// 2. In test builds: panic if env var not set-/// 3. Production: sibling of config.toml (`approvals.toml` in same directory)+/// 2. Lib-crate test builds with the variable unset: panic (see below)+/// 3. Production: `approvals.toml` beside `config.toml`+///+/// Called by [`Approvals::load`] and [`require_approvals_path`]. The mutation+/// methods take an explicit `&Path`, so they never resolve here.+///+/// The step-2 guard is `#[cfg(test)]`, so it fires only when the `worktrunk`+/// lib crate is itself compiled as a test target. A unit test in the `wt` bin+/// crate (anything under `src/commands/`) links the lib in non-test mode, so+/// the guard is compiled out and step 3 resolves the real user config+/// directory. In-process unit tests must not resolve here, directly or via+/// [`Approvals::load`]; they pass tempdir-backed paths instead. See+/// `tests/CLAUDE.md`.pub fn approvals_path() -> Option<PathBuf> {if let Ok(path) = std::env::var("WORKTRUNK_APPROVALS_PATH") {return Some(PathBuf::from(path));@@ -67,8 +78,9 @@ pub fn approvals_path() -> Option<PathBuf> {#[cfg(test)]panic!(- "WORKTRUNK_APPROVALS_PATH not set in test. Tests must use TestRepo which sets this \- automatically, or set it manually to an isolated test approvals path."+ "WORKTRUNK_APPROVALS_PATH not set in test. Subprocess tests set it via TestRepo. \+ An in-process unit test must pass explicit tempdir paths to the mutation \+ methods and must not resolve the approvals path globally. See tests/CLAUDE.md.");#[cfg(not(test))]@@ -77,6 +89,16 @@ pub fn approvals_path() -> Option<PathBuf> {}}+/// Resolve the approvals path, erroring when no location can be determined.+///+/// The `Result`-returning counterpart of [`approvals_path`], for the callers+/// that save approvals and need a concrete path.+pub fn require_approvals_path() -> Result<PathBuf, ConfigError> {+ approvals_path().ok_or_else(|| {+ ConfigError("Cannot determine approvals path. Set $HOME or $XDG_CONFIG_HOME".to_string())+ })+}+// =========================================================================// Loading// =========================================================================@@ -253,25 +275,17 @@ impl Approvals {/// Acquires lock, reloads from disk, calls the mutator, and saves if mutator returns true.fn with_locked_mutation<F>(&mut self,- approvals_path: Option<&Path>,+ approvals_path: &Path,mutate: F,) -> Result<(), ConfigError>whereF: FnOnce(&mut Self) -> bool,{- let path = match approvals_path {- Some(p) => p.to_path_buf(),- None => self::approvals_path().ok_or_else(|| {- ConfigError(- "Cannot determine approvals path. Set $HOME or $XDG_CONFIG_HOME".to_string(),- )- })?,- };- let _lock = super::user::mutation::acquire_config_lock(&path)?;- self.reload_from(&path)?;+ let _lock = super::user::mutation::acquire_config_lock(approvals_path)?;+ self.reload_from(approvals_path)?;if mutate(self) {- self.save_to(&path)?;+ self.save_to(approvals_path)?;}Ok(())}@@ -321,7 +335,7 @@ impl Approvals {&mut self,project: String,command: String,- approvals_path: Option<&Path>,+ approvals_path: &Path,) -> Result<(), ConfigError> {self.with_locked_mutation(approvals_path, |approvals| {if approvals.is_command_approved(&project, &command) {@@ -342,7 +356,7 @@ impl Approvals {&mut self,project: String,commands: Vec<String>,- approvals_path: Option<&Path>,+ approvals_path: &Path,) -> Result<(), ConfigError> {self.with_locked_mutation(approvals_path, |approvals| {let entry = approvals.projects.entry(project).or_default();@@ -366,7 +380,7 @@ impl Approvals {pub fn revoke_project(&mut self,project: &str,- approvals_path: Option<&Path>,+ approvals_path: &Path,) -> Result<(), ConfigError> {let project = project.to_string();self.with_locked_mutation(approvals_path, |approvals| {@@ -382,7 +396,7 @@ impl Approvals {}/// Clear all approvals for all projects and save.- pub fn clear_all(&mut self, approvals_path: Option<&Path>) -> Result<(), ConfigError> {+ pub fn clear_all(&mut self, approvals_path: &Path) -> Result<(), ConfigError> {self.with_locked_mutation(approvals_path, |approvals| {if approvals.projects.is_empty() {return false;@@ -458,7 +472,7 @@ mod tests {.approve_command("github.com/user/repo".to_string(),"npm install".to_string(),- Some(&path),+ &path,).unwrap();@@ -476,14 +490,14 @@ mod tests {.approve_command("github.com/user/repo".to_string(),"npm install".to_string(),- Some(&path),+ &path,).unwrap();approvals.approve_command("github.com/user/repo".to_string(),"npm install".to_string(),- Some(&path),+ &path,).unwrap();@@ -505,7 +519,7 @@ mod tests {.approve_commands("github.com/user/repo".to_string(),vec!["npm install".to_string(), "npm test".to_string()],- Some(&path),+ &path,).unwrap();@@ -522,19 +536,19 @@ mod tests {.approve_commands("github.com/user/repo1".to_string(),vec!["npm install".to_string(), "npm test".to_string()],- Some(&path),+ &path,).unwrap();approvals.approve_command("github.com/user/repo2".to_string(),"cargo build".to_string(),- Some(&path),+ &path,).unwrap();approvals- .revoke_project("github.com/user/repo1", Some(&path))+ .revoke_project("github.com/user/repo1", &path).unwrap();assert!(!approvals.projects.contains_key("github.com/user/repo1"));assert!(approvals.projects.contains_key("github.com/user/repo2"));@@ -549,18 +563,18 @@ mod tests {.approve_command("github.com/user/repo1".to_string(),"npm install".to_string(),- Some(&path),+ &path,).unwrap();approvals.approve_command("github.com/user/repo2".to_string(),"cargo build".to_string(),- Some(&path),+ &path,).unwrap();- approvals.clear_all(Some(&path)).unwrap();+ approvals.clear_all(&path).unwrap();assert!(approvals.projects.is_empty());}@@ -573,7 +587,7 @@ mod tests {.approve_commands("github.com/user/repo".to_string(),vec!["npm install".to_string(), "npm test".to_string()],- Some(&path),+ &path,).unwrap();@@ -641,7 +655,7 @@ mod tests {.approve_commands("github.com/user/repo".to_string(),vec!["npm install".to_string(), "npm test".to_string()],- Some(&path),+ &path,).unwrap();@@ -665,7 +679,7 @@ mod tests {.approve_command("project".to_string(),"echo {{ repo_root }}".to_string(),- Some(&path),+ &path,).unwrap();@@ -679,11 +693,7 @@ mod tests {let mut approvals = Approvals::default();approvals- .approve_command(- "project".to_string(),- "echo repo_root".to_string(),- Some(&path),- )+ .approve_command("project".to_string(), "echo repo_root".to_string(), &path).unwrap();assert!(!approvals.is_command_approved("project", "echo repo_path"));@@ -711,7 +721,7 @@ mod tests {.approve_command("github.com/user/repo".to_string(),format!("command_{i}"),- Some(&config_path),+ &config_path,).unwrap();})@@ -780,7 +790,7 @@ approved-commands = ["npm install"].approve_command("github.com/user/repo".to_string(),"npm test".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -873,12 +883,10 @@ approved-command = ["npm test"]let (_temp_dir, path) = test_dir();let mut approvals = Approvals::default();approvals- .approve_command("project-a".to_string(), "cmd1".to_string(), Some(&path))+ .approve_command("project-a".to_string(), "cmd1".to_string(), &path).unwrap();// Revoke a project that doesn't exist — should be a no-op- approvals- .revoke_project("nonexistent", Some(&path))- .unwrap();+ approvals.revoke_project("nonexistent", &path).unwrap();assert!(approvals.is_command_approved("project-a", "cmd1"));}@@ -887,7 +895,7 @@ approved-command = ["npm test"]let (_temp_dir, path) = test_dir();let mut approvals = Approvals::default();// Clear when there's nothing — should be a no-op- approvals.clear_all(Some(&path)).unwrap();+ approvals.clear_all(&path).unwrap();assert!(approvals.projects.is_empty());}@@ -921,7 +929,7 @@ approved-command = ["npm test"]let (_temp_dir, path) = test_dir();let mut approvals = Approvals::default();approvals- .approve_command("project-a".to_string(), "cmd1".to_string(), Some(&path))+ .approve_command("project-a".to_string(), "cmd1".to_string(), &path).unwrap();// Manually clear the commands (without removing the project entry)approvals@@ -933,7 +941,7 @@ approved-command = ["npm test"]// Write this state to diskapprovals.save_to(&path).unwrap();// Now revoke_project should find the project but see empty commands → no-op- approvals.revoke_project("project-a", Some(&path)).unwrap();+ approvals.revoke_project("project-a", &path).unwrap();}#[test]@@ -942,10 +950,10 @@ approved-command = ["npm test"]let mut approvals = Approvals::default();approvals- .approve_command("project1".to_string(), "cmd1".to_string(), Some(&path))+ .approve_command("project1".to_string(), "cmd1".to_string(), &path).unwrap();approvals- .approve_command("project2".to_string(), "cmd2".to_string(), Some(&path))+ .approve_command("project2".to_string(), "cmd2".to_string(), &path).unwrap();let projects: Vec<_> = approvals.projects().collect();diff --git a/src/config/mod.rs b/src/config/mod.rsindex 61b44d874..bef2ced7e 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -101,7 +101,7 @@ pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {}// Re-export public types-pub use approvals::{Approvals, approvals_path};+pub use approvals::{Approvals, approvals_path, require_approvals_path};pub use commands::{Command, CommandConfig, HookStep, append_aliases};pub use deprecation::CheckAndMigrateResult;pub use deprecation::DeprecationInfo;@@ -140,7 +140,7 @@ pub use user::{CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListConfig, MergeConfig, RemoveConfig,ResolvedConfig, StageMode, StepConfig, SwitchConfig, SwitchPickerConfig, UserConfig,UserProjectOverrides, config_path, default_config_path, default_system_config_path,- set_config_path, system_config_path, valid_user_config_keys,+ require_config_path, set_config_path, system_config_path, valid_user_config_keys,};#[cfg(test)]diff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex 2a015984f..186b7240a 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -22,8 +22,8 @@ use serde::{Deserialize, Serialize};// Re-export public typespub use merge::Merge;pub use path::{- config_path, default_config_path, default_system_config_path, set_config_path,- system_config_path,+ config_path, default_config_path, default_system_config_path, require_config_path,+ set_config_path, system_config_path,};pub use resolved::ResolvedConfig;pub use schema::valid_user_config_keys;diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rsindex 88006fdf4..5870f3380 100644--- a/src/config/user/mutation.rs+++ b/src/config/user/mutation.rs@@ -10,11 +10,8 @@ use crate::config::ConfigError;use crate::path::format_path_for_display;use super::UserConfig;-use super::path;use super::sections::CommitGenerationConfig;-const NO_CONFIG_DIR_MSG: &str = "Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME";-/// Acquire an exclusive lock on the config file for read-modify-write operations.////// Uses a `.lock` file alongside the config file to coordinate between processes.@@ -50,21 +47,17 @@ impl UserConfig {/// Acquires lock, reloads from disk, calls the mutator, and saves if mutator returns true.pub(super) fn with_locked_mutation<F>(&mut self,- config_path: Option<&std::path::Path>,+ config_path: &std::path::Path,mutate: F,) -> Result<(), ConfigError>whereF: FnOnce(&mut Self) -> bool,{- let path = match config_path {- Some(p) => p.to_path_buf(),- None => path::config_path().ok_or_else(|| ConfigError(NO_CONFIG_DIR_MSG.into()))?,- };- let _lock = acquire_config_lock(&path)?;- self.reload_from(&path)?;+ let _lock = acquire_config_lock(config_path)?;+ self.reload_from(config_path)?;if mutate(self) {- self.save_to(&path)?;+ self.save_to(config_path)?;}Ok(())}@@ -106,10 +99,9 @@ impl UserConfig {/// Set `skip-shell-integration-prompt = true` and save.////// Acquires lock, reloads from disk, sets flag if not already set, and saves.- /// Pass `None` for default config path, or `Some(path)` for testing.pub fn set_skip_shell_integration_prompt(&mut self,- config_path: Option<&std::path::Path>,+ config_path: &std::path::Path,) -> Result<(), ConfigError> {self.with_locked_mutation(config_path, |config| {if config.skip_shell_integration_prompt {@@ -123,10 +115,9 @@ impl UserConfig {/// Set `skip-commit-generation-prompt = true` and save.////// Acquires lock, reloads from disk, sets flag if not already set, and saves.- /// Pass `None` for default config path, or `Some(path)` for testing.pub fn set_skip_commit_generation_prompt(&mut self,- config_path: Option<&std::path::Path>,+ config_path: &std::path::Path,) -> Result<(), ConfigError> {self.with_locked_mutation(config_path, |config| {if config.skip_commit_generation_prompt {@@ -140,12 +131,11 @@ impl UserConfig {/// Set worktree-path for a specific project and save.////// Creates the project entry if it doesn't exist.- /// Pass `None` for default config path, or `Some(path)` for testing.pub fn set_project_worktree_path(&mut self,project: &str,worktree_path: String,- config_path: Option<&std::path::Path>,+ config_path: &std::path::Path,) -> Result<(), ConfigError> {self.with_locked_mutation(config_path, |config| {let entry = config.projects.entry(project.to_string()).or_default();@@ -161,11 +151,10 @@ impl UserConfig {////// Sets `[commit.generation] command = ...` in the user config./// Acquires lock, reloads from disk, sets the command, and saves.- /// Pass `None` for default config path, or `Some(path)` for testing.pub fn set_commit_generation_command(&mut self,command: String,- config_path: Option<&std::path::Path>,+ config_path: &std::path::Path,) -> Result<(), ConfigError> {self.with_locked_mutation(config_path, |config| {let gen_config = configdiff --git a/src/config/user/path.rs b/src/config/user/path.rsindex 0cd0101b0..08545dac4 100644--- a/src/config/user/path.rs+++ b/src/config/user/path.rs@@ -8,6 +8,8 @@ use std::sync::OnceLock;use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};+use crate::config::ConfigError;+/// Override for user config path, set via --config CLI flagstatic CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();@@ -46,6 +48,17 @@ pub fn config_path() -> Option<PathBuf> {default_config_path()}+/// Resolve the user config path, erroring when no location can be determined.+///+/// The `Result`-returning counterpart of [`config_path`], for callers that+/// must produce a concrete path (config mutation) rather than tolerate its+/// absence.+pub fn require_config_path() -> Result<PathBuf, ConfigError> {+ config_path().ok_or_else(|| {+ ConfigError("Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME".to_string())+ })+}+/// Platform-specific default config path, without CLI or env var overrides.////// Returns the etcetera-based platform default. Called by `config_path()`diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex a9088696e..4dedbc2cc 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -578,7 +578,7 @@ fn test_set_project_worktree_path() {.set_project_worktree_path("github.com/user/repo","../{{ branch | sanitize }}".to_string(),- Some(&config_path),+ &config_path,).unwrap();@@ -2156,7 +2156,7 @@ fn test_reload_from_invalid_toml() {// Try to reload via a mutation — should fail with parse errorlet mut config = UserConfig::default();- let result = config.set_skip_shell_integration_prompt(Some(&config_path));+ let result = config.set_skip_shell_integration_prompt(&config_path);assert!(result.is_err());let err = result.unwrap_err().to_string();@@ -2372,7 +2372,7 @@ fn test_reload_from_permission_error() {// Try to reload via a mutation — should fail with read errorlet mut config = UserConfig::default();- let result = config.set_skip_shell_integration_prompt(Some(&config_path));+ let result = config.set_skip_shell_integration_prompt(&config_path);assert!(result.is_err());let err = result.unwrap_err().to_string();@@ -3281,7 +3281,7 @@ fn test_set_project_worktree_path_noop_when_unchanged() {let mut config = UserConfig::default();config- .set_project_worktree_path("user/repo", "../custom".to_string(), Some(&config_path))+ .set_project_worktree_path("user/repo", "../custom".to_string(), &config_path).unwrap();let after_first = std::fs::read_to_string(&config_path).unwrap();@@ -3293,7 +3293,7 @@ fn test_set_project_worktree_path_noop_when_unchanged() {// false, so save is skipped.let mut config2 = UserConfig::default();config2- .set_project_worktree_path("user/repo", "../custom".to_string(), Some(&config_path))+ .set_project_worktree_path("user/repo", "../custom".to_string(), &config_path).unwrap();let after_second = std::fs::read_to_string(&config_path).unwrap();@@ -3315,7 +3315,7 @@ fn test_set_skip_shell_integration_prompt_noop_on_second_call() {let mut config = UserConfig::default();config- .set_skip_shell_integration_prompt(Some(&config_path))+ .set_skip_shell_integration_prompt(&config_path).unwrap();let after_first = std::fs::read_to_string(&config_path).unwrap();assert!(after_first.contains("skip-shell-integration-prompt = true"));@@ -3323,7 +3323,7 @@ fn test_set_skip_shell_integration_prompt_noop_on_second_call() {// Second call with the flag already true in-memory — mutator returns// false, save is skipped, file is byte-identical.config- .set_skip_shell_integration_prompt(Some(&config_path))+ .set_skip_shell_integration_prompt(&config_path).unwrap();let after_second = std::fs::read_to_string(&config_path).unwrap();assert_eq!(after_first, after_second);@@ -3339,7 +3339,7 @@ fn test_acquire_config_lock_handles_root_path() {// None branch executes cleanly.let mut config = UserConfig::default();let err = config- .set_skip_shell_integration_prompt(Some(std::path::Path::new("/")))+ .set_skip_shell_integration_prompt(std::path::Path::new("/")).unwrap_err();let msg = err.to_string();assert!(@@ -3365,7 +3365,7 @@ fn test_acquire_config_lock_fails_when_parent_is_file() {let mut config = UserConfig::default();let err = config- .set_skip_shell_integration_prompt(Some(&config_path))+ .set_skip_shell_integration_prompt(&config_path).unwrap_err();let msg = err.to_string();assert!(@@ -3407,7 +3407,7 @@ fn test_with_locked_mutation_propagates_save_error() {let cfg_path_for_closure = config_path.clone();let mut config = UserConfig::default();let err = config- .with_locked_mutation(Some(&config_path), move |_config| {+ .with_locked_mutation(&config_path, move |_config| {// Mid-mutation: strip read permissions from the config file.// reload_from already ran; save_to will try to read again and fail.let mut perms = std::fs::metadata(&cfg_path_for_closure)diff --git a/src/output/commit_generation.rs b/src/output/commit_generation.rsindex e80e520fb..ff0552870 100644--- a/src/output/commit_generation.rs+++ b/src/output/commit_generation.rs@@ -11,7 +11,7 @@ use std::path::PathBuf;use std::sync::LazyLock;use color_print::cformat;-use worktrunk::config::UserConfig;+use worktrunk::config::{UserConfig, require_config_path};use worktrunk::styling::{eprintln, format_toml, hint_message, info_message, success_message};use super::prompt::{PromptResponse, prompt_yes_no_preview};@@ -180,7 +180,8 @@ pub fn prompt_commit_generation(config: &mut UserConfig) -> anyhow::Result<bool>// Detect available toollet Some(tool) = detect_llm_tool() else {// No tool found - set skip flag so we don't check every time- let _ = config.set_skip_commit_generation_prompt(None);+ let _ =+ require_config_path().and_then(|path| config.set_skip_commit_generation_prompt(&path));return Ok(false);};@@ -208,7 +209,9 @@ pub fn prompt_commit_generation(config: &mut UserConfig) -> anyhow::Result<bool>PromptResponse::Accepted => {// Set the configurationlet command = command.to_string();- if let Err(e) = config.set_commit_generation_command(command.clone(), None) {+ let save_result = require_config_path()+ .and_then(|path| config.set_commit_generation_command(command.clone(), &path));+ if let Err(e) = save_result {log::error!("Failed to save config: {}", e);eprintln!("{}",@@ -234,7 +237,8 @@ pub fn prompt_commit_generation(config: &mut UserConfig) -> anyhow::Result<bool>}PromptResponse::Declined => {// Set skip flag so we don't prompt again- let _ = config.set_skip_commit_generation_prompt(None);+ let _ = require_config_path()+ .and_then(|path| config.set_skip_commit_generation_prompt(&path));Ok(false)}}diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rsindex 35dca2cad..0a7bf3cdd 100644--- a/src/output/shell_integration.rs+++ b/src/output/shell_integration.rs@@ -61,7 +61,7 @@use std::io::IsTerminal;use color_print::cformat;-use worktrunk::config::UserConfig;+use worktrunk::config::{UserConfig, require_config_path};use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;use worktrunk::shell::{Shell, current_shell, extract_filename_from_path};@@ -470,7 +470,8 @@ pub fn prompt_shell_integration(if !confirmed {// Only skip future prompts after explicit decline (not Ctrl+C)- let _ = config.set_skip_shell_integration_prompt(None);+ let _ =+ require_config_path().and_then(|path| config.set_skip_shell_integration_prompt(&path));print_shell_integration_hint(repo);return Ok(false);}diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex 4107ee48a..a32a6f272 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -96,6 +96,51 @@ call `.current_dir(...)` explicitly.| `wt_command()` | `Command` | Running wt without a TestRepo (free function) || `repo.git_command()` | `Cmd` | Running git commands (use `.run()` not `.output()`) |+## Config Isolation for In-Process Unit Tests++`repo.wt_command()` / `wt_command()` isolate *subprocess* tests (above). An+in-process unit test that calls library functions directly gets no such+isolation: it runs in the test process, which inherits the real environment.++The `Approvals` and `UserConfig` mutation methods take an explicit `&Path`, so+a unit test passes a tempdir-backed path and the write stays isolated. The+global resolvers do not isolate: `Approvals::load()`, `approvals_path()`,+`config_path()`, and `system_config_path()` all fall back to the real+`~/.config/worktrunk/`.++<example>+<bad reason="Approvals::load() reads the real ~/.config/worktrunk/approvals.toml">++Bad:++```rust+let mut approvals = Approvals::load().unwrap();+approvals.approve_command(project, command, &approvals_path).unwrap();+```++</bad>+<good reason="Default state plus a tempdir path touches no real config">++Good:++```rust+let temp_dir = tempfile::tempdir().unwrap();+let approvals_path = temp_dir.path().join("approvals.toml");+let mut approvals = Approvals::default();+approvals.approve_command(project, command, &approvals_path).unwrap();+```++</good>+</example>++`approvals_path()` panics when `WORKTRUNK_APPROVALS_PATH` is unset, but+`#[cfg(test)]` makes that guard fire only for `worktrunk` lib-crate tests. A+bin-crate test (anything under `src/commands/`) links the lib in non-test+mode, so the guard is compiled out and a global read hits the real config+silently: it passes wherever `$HOME` is writable and fails only in a sandbox+that forbids it. `config_path()` and `system_config_path()` have no guard at+all.+## Timing Tests: Long Timeouts with Fast Polling**Core principle:** Use long timeouts (5+ seconds) for reliability on slow CI, but poll frequently (10-50ms) so tests complete quickly when things work.diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rsindex cb6fecc10..52153467f 100644--- a/tests/integration_tests/approval_save.rs+++ b/tests/integration_tests/approval_save.rs@@ -19,7 +19,7 @@ fn test_approval_saves_to_disk() {.approve_command("github.com/test/repo".to_string(),"test command".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -55,14 +55,14 @@ fn test_duplicate_approvals_not_saved_twice() {.approve_command("github.com/test/repo".to_string(),"test".to_string(),- Some(&approvals_path),+ &approvals_path,).ok();approvals.approve_command("github.com/test/repo".to_string(),"test".to_string(),- Some(&approvals_path),+ &approvals_path,).ok();@@ -88,21 +88,21 @@ fn test_multiple_project_approvals() {.approve_command("github.com/user1/repo1".to_string(),"npm install".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();approvals.approve_command("github.com/user2/repo2".to_string(),"cargo build".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();approvals.approve_command("github.com/user1/repo1".to_string(),"npm test".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -159,7 +159,7 @@ fn test_isolated_config_safety() {.approve_command("github.com/safety-test/repo".to_string(),"THIS SHOULD NOT APPEAR IN USER APPROVALS".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -217,7 +217,7 @@ fn test_approval_saves_to_new_approvals_file() {.approve_command("github.com/test/nested".to_string(),"test command".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -263,7 +263,7 @@ command = "llm -m claude-haiku-4.5"// Change a non-approval setting and save back to the same fileconfig- .set_commit_generation_command("llm -m claude-sonnet-4".to_string(), Some(&config_path))+ .set_commit_generation_command("llm -m claude-sonnet-4".to_string(), &config_path).unwrap();// Read back the saved config@@ -310,7 +310,7 @@ fn test_concurrent_approve_preserves_all_approvals() {.approve_command("github.com/user/repo".to_string(),"npm install".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -327,7 +327,7 @@ fn test_concurrent_approve_preserves_all_approvals() {.approve_command("github.com/user/repo".to_string(),"npm test".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -362,14 +362,14 @@ fn test_concurrent_revoke_preserves_all_changes() {.approve_command("github.com/user/repo".to_string(),"npm install".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();setup_approvals.approve_command("github.com/user/repo".to_string(),"npm test".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -381,7 +381,7 @@ fn test_concurrent_revoke_preserves_all_changes() {// Process A: revokes the projectlet mut approvals_a = Approvals::default();approvals_a- .revoke_project("github.com/user/repo", Some(&approvals_path))+ .revoke_project("github.com/user/repo", &approvals_path).unwrap();// Read the final state from disk@@ -414,7 +414,7 @@ fn test_concurrent_approve_different_projects() {.approve_command("github.com/user/project1".to_string(),"npm install".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -424,7 +424,7 @@ fn test_concurrent_approve_different_projects() {.approve_command("github.com/user/project2".to_string(),"cargo build".to_string(),- Some(&approvals_path),+ &approvals_path,).unwrap();@@ -482,7 +482,7 @@ fn test_truly_concurrent_approve_with_threads() {.approve_command("github.com/user/repo".to_string(),format!("command_{i}"),- Some(&approvals_path),+ &approvals_path,).unwrap();})@@ -559,7 +559,7 @@ fn test_permission_error_prevents_save() {let result = approvals.approve_command("github.com/test/readonly".to_string(),"test command".to_string(),- Some(&approvals_path),+ &approvals_path,);// Restore write permissions so temp_dir can be cleaned up@@ -592,7 +592,7 @@ fn test_skip_shell_integration_prompt_saves_to_disk() {let mut config = UserConfig::default();config- .set_skip_shell_integration_prompt(Some(&config_path))+ .set_skip_shell_integration_prompt(&config_path).unwrap();// Verify file was created@@ -616,10 +616,10 @@ fn test_skip_shell_integration_prompt_idempotent() {// Call twice - should not errorconfig- .set_skip_shell_integration_prompt(Some(&config_path))+ .set_skip_shell_integration_prompt(&config_path).unwrap();config- .set_skip_shell_integration_prompt(Some(&config_path))+ .set_skip_shell_integration_prompt(&config_path).unwrap();// Field should still be true@@ -640,7 +640,7 @@ fn test_skip_commit_generation_prompt_saves_to_disk() {let mut config = UserConfig::default();config- .set_skip_commit_generation_prompt(Some(&config_path))+ .set_skip_commit_generation_prompt(&config_path).unwrap();// Verify file was created@@ -664,10 +664,10 @@ fn test_skip_commit_generation_prompt_idempotent() {// Call twice - should not errorconfig- .set_skip_commit_generation_prompt(Some(&config_path))+ .set_skip_commit_generation_prompt(&config_path).unwrap();config- .set_skip_commit_generation_prompt(Some(&config_path))+ .set_skip_commit_generation_prompt(&config_path).unwrap();// Field should still be true@@ -688,7 +688,7 @@ fn test_set_commit_generation_command_saves_to_disk() {let mut config = UserConfig::default();config- .set_commit_generation_command("llm -m haiku".to_string(), Some(&config_path))+ .set_commit_generation_command("llm -m haiku".to_string(), &config_path).unwrap();// Verify file was created@@ -716,7 +716,7 @@ fn test_set_commit_generation_command_with_special_chars() {let command ="MAX_THINKING_TOKENS=0 claude -p --model=haiku --tools='' --system-prompt=''".to_string();config- .set_commit_generation_command(command, Some(&config_path))+ .set_commit_generation_command(command, &config_path).unwrap();// Verify TOML can be parsed back@@ -769,7 +769,7 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"let mut config: UserConfig = toml::from_str(&toml_str).unwrap();config- .set_commit_generation_command("llm -m haiku".to_string(), Some(&symlink_path))+ .set_commit_generation_command("llm -m haiku".to_string(), &symlink_path).unwrap();// Verify symlink is preserved@@ -829,7 +829,7 @@ approved-commands = [let mut config: UserConfig = toml::from_str(&toml_str).unwrap();config- .set_commit_generation_command("llm -m haiku".to_string(), Some(&config_path))+ .set_commit_generation_command("llm -m haiku".to_string(), &config_path).unwrap();// Read back what was saveddiff --git a/tests/integration_tests/approvals.rs b/tests/integration_tests/approvals.rsindex 72576e50d..8a40826c5 100644--- a/tests/integration_tests/approvals.rs+++ b/tests/integration_tests/approvals.rs@@ -114,7 +114,7 @@ fn test_clear_approvals_with_approvals(repo: TestRepo) {.approve_command(repo.project_id(),"echo 'test'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();@@ -142,7 +142,7 @@ fn test_clear_approvals_global_with_approvals(repo: TestRepo) {.approve_command(repo.project_id(),"echo 'test'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();@@ -169,7 +169,7 @@ fn test_clear_approvals_after_clear(repo: TestRepo) {.approve_command(repo.project_id(),"echo 'test'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();@@ -243,21 +243,21 @@ lint = "echo 'third'".approve_command(project_id.clone(),"echo 'first'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();approvals.approve_command(project_id.clone(),"echo 'second'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();approvals.approve_command(project_id,"echo 'third'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();@@ -284,7 +284,7 @@ fn test_add_approvals_all_already_approved(repo: TestRepo) {.approve_command(repo.project_id(),"echo 'test'".to_string(),- Some(repo.test_approvals_path()),+ repo.test_approvals_path(),).unwrap();