Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add per-project config overrides (#749)
Maximilian Roos41b241162bda
diff --git a/.claude-plugin/skills/worktrunk/reference/config.md b/.claude-plugin/skills/worktrunk/reference/config.mdindex 199fc8359..30bb1117f 100644--- a/.claude-plugin/skills/worktrunk/reference/config.md+++ b/.claude-plugin/skills/worktrunk/reference/config.md@@ -147,13 +147,21 @@ Pager behavior for `wt select` diff previews.# pager = "delta --paging=never"```-### Approved commands+### Per-project settings (Experimental)-Commands approved for project hooks. Auto-populated when approving hooks on first run, or via `wt hook approvals add`.+Per-project settings are keyed by project identifier (e.g., `github.com/user/repo`).+These contain approved hook commands plus optional overrides of global settings.+Setting overrides (worktree-path, list, commit, merge) are new; approved-commands is stable.```toml[projects."github.com/user/repo"]+# Approved hook commands (auto-populated when approving on first run)approved-commands = ["npm ci", "npm test"]++# Optional overrides (omit to use global settings)+worktree-path = ".worktrees/{{ branch | sanitize }}"+list.full = true+merge.squash = false```For project-specific hooks (post-create, post-start, pre-merge, etc.), use a project config at `<repo>/.config/wt.toml`. Run `wt config create --project` to create one, or see [`wt hook` docs](https://worktrunk.dev/hook/).diff --git a/dev/config.example.toml b/dev/config.example.tomlindex ab134cc1b..19f97bef3 100644--- a/dev/config.example.toml+++ b/dev/config.example.toml@@ -93,13 +93,21 @@# # Example:# # pager = "delta --paging=never"#-# ### Approved commands+# ### Per-project settings (Experimental)#-# Commands approved for project hooks. Auto-populated when approving hooks on first run, or via `wt hook approvals add`.+# Per-project settings are keyed by project identifier (e.g., `github.com/user/repo`).+# These contain approved hook commands plus optional overrides of global settings.+# Setting overrides (worktree-path, list, commit, merge) are new; approved-commands is stable.## [projects."github.com/user/repo"]+# # Approved hook commands (auto-populated when approving on first run)# approved-commands = ["npm ci", "npm test"]#+# # Optional overrides (omit to use global settings)+# worktree-path = ".worktrees/{{ branch | sanitize }}"+# list.full = true+# merge.squash = false+## For project-specific hooks (post-create, post-start, pre-merge, etc.), use a project config at `<repo>/.config/wt.toml`. Run `wt config create --project` to create one, or see `wt hook` docs (https://worktrunk.dev/hook/).## ### Custom prompt templatesdiff --git a/docs/content/config.md b/docs/content/config.mdindex b8d2ceea2..a985a1e99 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -155,13 +155,21 @@ Pager behavior for `wt select` diff previews.# pager = "delta --paging=never"```-### Approved commands+### Per-project settings (Experimental)-Commands approved for project hooks. Auto-populated when approving hooks on first run, or via `wt hook approvals add`.+Per-project settings are keyed by project identifier (e.g., `github.com/user/repo`).+These contain approved hook commands plus optional overrides of global settings.+Setting overrides (worktree-path, list, commit, merge) are new; approved-commands is stable.```toml[projects."github.com/user/repo"]+# Approved hook commands (auto-populated when approving on first run)approved-commands = ["npm ci", "npm test"]++# Optional overrides (omit to use global settings)+worktree-path = ".worktrees/{{ branch | sanitize }}"+list.full = true+merge.squash = false```For project-specific hooks (post-create, post-start, pre-merge, etc.), use a project config at `<repo>/.config/wt.toml`. Run `wt config create --project` to create one, or see [`wt hook` docs](@/hook.md).diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex caf690034..4d513c304 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1597,13 +1597,21 @@ Pager behavior for `wt select` diff previews.# pager = "delta --paging=never"```-### Approved commands+### Per-project settings (Experimental)-Commands approved for project hooks. Auto-populated when approving hooks on first run, or via `wt hook approvals add`.+Per-project settings are keyed by project identifier (e.g., `github.com/user/repo`).+These contain approved hook commands plus optional overrides of global settings.+Setting overrides (worktree-path, list, commit, merge) are new; approved-commands is stable.```toml[projects."github.com/user/repo"]+# Approved hook commands (auto-populated when approving on first run)approved-commands = ["npm ci", "npm test"]++# Optional overrides (omit to use global settings)+worktree-path = ".worktrees/{{ branch | sanitize }}"+list.full = true+merge.squash = false```For project-specific hooks (post-create, post-start, pre-merge, etc.), use a project config at `<repo>/.config/wt.toml`. Run `wt config create --project` to create one, or see [`wt hook` docs](@/hook.md).diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex e4075ffae..7df8066d8 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -45,6 +45,19 @@ impl<'a> CommandContext<'a> {pub fn branch_or_head(&self) -> &str {self.branch.unwrap_or("HEAD")}++ /// Get the project identifier for per-project config lookup.+ ///+ /// Uses the remote URL if available, otherwise the canonical repository path.+ /// Returns None only if the path is not valid UTF-8.+ pub fn project_id(&self) -> Option<String> {+ self.repo.project_identifier().ok()+ }++ /// Get the commit generation config, merging project-specific settings.+ pub fn commit_generation(&self) -> worktrunk::config::CommitGenerationConfig {+ self.config.commit_generation(self.project_id().as_deref())+ }}/// Build hook context as a HashMap for JSON serialization and template expansion.diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex aa731c0dc..70e5f3a15 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -206,7 +206,8 @@ impl CommitOptions<'_> {}}- CommitGenerator::new(&self.ctx.config.commit_generation)+ let effective_config = self.ctx.commit_generation();+ CommitGenerator::new(&effective_config).commit_staged_changes(self.show_no_squash_note, self.stage_mode)}}diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 15914b07b..9a1710044 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -256,9 +256,12 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {}}- // Test commit generation+ // Test commit generation - use effective config for current projectlet config = UserConfig::load()?;- let commit_config = &config.commit_generation;+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());+ let commit_config = config.commit_generation(project_id.as_deref());if !commit_config.is_configured() {writeln!(out, "{}", hint_message("Commit generation not configured"))?;@@ -275,7 +278,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {});- match test_commit_generation(commit_config) {+ match test_commit_generation(&commit_config) {Ok(message) => {writeln!(out,diff --git a/src/commands/context.rs b/src/commands/context.rsindex 71e32046c..e4cf3e666 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -84,4 +84,27 @@ impl CommandEnv {.into()})}++ /// Get the project identifier for per-project config lookup.+ ///+ /// Uses the remote URL if available, otherwise the canonical repository path.+ /// Returns None only if the path is not valid UTF-8.+ pub fn project_id(&self) -> Option<String> {+ self.repo.project_identifier().ok()+ }++ /// Get the commit generation config, merging project-specific settings.+ pub fn commit_generation(&self) -> worktrunk::config::CommitGenerationConfig {+ self.config.commit_generation(self.project_id().as_deref())+ }++ /// Get the commit config, merging project-specific settings.+ pub fn commit(&self) -> Option<worktrunk::config::CommitConfig> {+ self.config.commit(self.project_id().as_deref())+ }++ /// Get the merge config, merging project-specific settings.+ pub fn merge(&self) -> Option<worktrunk::config::MergeConfig> {+ self.config.merge(self.project_id().as_deref())+ }}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 43bfc061b..609effca0 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -324,15 +324,31 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {let mut config = UserConfig::load().context("Failed to load config")?;if global {- // Clear all approvals for all projects- let project_count = config.projects.len();+ // Clear all approvals for all projects (preserving other per-project settings)+ let projects_with_approvals: Vec<String> = config+ .projects+ .iter()+ .filter(|(_, p)| !p.approved_commands.is_empty())+ .map(|(id, _)| id.clone())+ .collect();- if project_count == 0 {+ if projects_with_approvals.is_empty() {crate::output::print(info_message("No approvals to clear"))?;return Ok(());}- config.projects.clear();+ let project_count = projects_with_approvals.len();++ // Clear only approved_commands, preserve other settings+ for project_id in &projects_with_approvals {+ if let Some(project_config) = config.projects.get_mut(project_id) {+ project_config.approved_commands.clear();+ // Remove project entry only if it has no other settings+ if project_config.is_empty() {+ config.projects.remove(project_id);+ }+ }+ }config.save().context("Failed to save config")?;crate::output::print(success_message(format!(@@ -344,8 +360,11 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {let repo = Repository::current()?;let project_id = repo.project_identifier()?;- // Check if project has any approvals- let had_approvals = config.projects.contains_key(&project_id);+ // Check if project has any approvals (not just if it exists)+ let had_approvals = config+ .projects+ .get(&project_id)+ .is_some_and(|p| !p.approved_commands.is_empty());if !had_approvals {crate::output::print(info_message("No approvals to clear for this project"))?;diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex bbd3d5f57..3c05f3f7c 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -214,8 +214,7 @@ impl PrStatus {/// Used for environments that don't support OSC 8 hyperlinks (e.g., Claude Code).pub fn format_indicator(&self, include_link: bool) -> String {let indicator = self.indicator();- if include_link && self.url.is_some() {- let url = self.url.as_ref().unwrap();+ if let (true, Some(url)) = (include_link, &self.url) {let style = self.style().underline();format!("{}{}{}{}{}",diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 7b1a1def1..44e9a35b3 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -17,15 +17,24 @@ use super::worktree::{};/// Options for the merge command+///+/// All boolean fields are optional CLI overrides. If None, the effective config+/// (project-specific merged with global) is used. If that's also None, defaults apply.pub struct MergeOptions<'a> {pub target: Option<&'a str>,- pub squash: bool,- pub commit: bool,- pub rebase: bool,- pub remove: bool,- pub verify: bool,+ /// CLI override for squash. None = use effective config default.+ pub squash: Option<bool>,+ /// CLI override for commit. None = use effective config default.+ pub commit: Option<bool>,+ /// CLI override for rebase. None = use effective config default.+ pub rebase: Option<bool>,+ /// CLI override for remove. None = use effective config default.+ pub remove: Option<bool>,+ /// CLI override for verify. None = use effective config default.+ pub verify: Option<bool>,pub yes: bool,- pub stage_mode: super::commit::StageMode,+ /// CLI override for stage mode. None = use effective config default.+ pub stage: Option<super::commit::StageMode>,}/// Collect all commands that will be executed during merge.@@ -68,13 +77,13 @@ fn collect_merge_commands(pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let MergeOptions {target,- squash,- commit,- rebase,- remove,- verify,+ squash: squash_opt,+ commit: commit_opt,+ rebase: rebase_opt,+ remove: remove_opt,+ verify: verify_opt,yes,- stage_mode,+ stage,} = opts;let env = CommandEnv::for_action("merge")?;@@ -83,6 +92,31 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Merge requires being on a branch (can't merge from detached HEAD)let current_branch = env.require_branch("merge")?.to_string();+ // Get effective merge config (project-specific merged with global)+ let merge_config = env.merge();++ // Determine final values: CLI > project config > global config > default (true)+ let squash = squash_opt+ .or_else(|| merge_config.as_ref().and_then(|m| m.squash))+ .unwrap_or(true);+ let commit = commit_opt+ .or_else(|| merge_config.as_ref().and_then(|m| m.commit))+ .unwrap_or(true);+ let rebase = rebase_opt+ .or_else(|| merge_config.as_ref().and_then(|m| m.rebase))+ .unwrap_or(true);+ let remove = remove_opt+ .or_else(|| merge_config.as_ref().and_then(|m| m.remove))+ .unwrap_or(true);+ let verify = verify_opt+ .or_else(|| merge_config.as_ref().and_then(|m| m.verify))+ .unwrap_or(true);++ // Stage mode: CLI > project commit config > global commit config > default+ let stage_mode = stage+ .or_else(|| env.commit().and_then(|c| c.stage))+ .unwrap_or_default();+// Cache current worktree for multiple querieslet current_wt = repo.current_worktree();@@ -152,7 +186,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {Some(&target_branch),yes,!verify, // skip_pre_commit when !verify- stage_mode+ Some(stage_mode))?,super::step_commands::SquashResult::Squashed)diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex d48e34622..bfd650a13 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -24,18 +24,23 @@ use super::hooks::{HookFailureStrategy, run_hook_with_filter};use super::repository_ext::RepositoryCliExt;/// Handle `wt step commit` command+///+/// `stage` is the CLI-provided stage mode. If None, uses the effective config default.pub fn step_commit(yes: bool,no_verify: bool,- stage_mode: super::commit::StageMode,+ stage: Option<super::commit::StageMode>,show_prompt: bool,) -> anyhow::Result<()> {use super::command_approval::approve_hooks;// Handle --show-prompt early: just build and output the promptif show_prompt {+ let repo = worktrunk::git::Repository::current()?;let config = UserConfig::load().context("Failed to load config")?;- let prompt = crate::llm::build_commit_prompt(&config.commit_generation)?;+ let project_id = repo.project_identifier().ok();+ let commit_config = config.commit_generation(project_id.as_deref());+ let prompt = crate::llm::build_commit_prompt(&commit_config)?;crate::output::stdout(prompt)?;return Ok(());}@@ -43,6 +48,11 @@ pub fn step_commit(let env = CommandEnv::for_action("commit")?;let ctx = env.context(yes);+ // Determine effective stage mode: CLI > project config > global config > default+ let stage_mode = stage+ .or_else(|| env.commit().and_then(|c| c.stage))+ .unwrap_or_default();+// "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)// Shadow no_verify: if user declines approval, skip hooks but continue commitlet no_verify = if !no_verify {@@ -86,12 +96,12 @@ pub enum SquashResult {////// # Arguments/// * `skip_pre_commit` - If true, skip all pre-commit hooks (both user and project)-/// * `stage_mode` - What to stage before committing (All or Tracked; None not supported for squash)+/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.pub fn handle_squash(target: Option<&str>,yes: bool,skip_pre_commit: bool,- stage_mode: super::commit::StageMode,+ stage: Option<super::commit::StageMode>,) -> anyhow::Result<SquashResult> {use super::commit::StageMode;@@ -100,7 +110,13 @@ pub fn handle_squash(// Squash requires being on a branch (can't squash in detached HEAD)let current_branch = env.require_branch("squash")?.to_string();let ctx = env.context(yes);- let generator = CommitGenerator::new(&env.config.commit_generation);+ let effective_config = env.commit_generation();+ let generator = CommitGenerator::new(&effective_config);++ // Determine effective stage mode: CLI > project config > global config > default+ let stage_mode = stage+ .or_else(|| env.commit().and_then(|c| c.stage))+ .unwrap_or_default();// Get and validate target ref (any commit-ish for merge-base calculation)let target_branch = repo.require_target_ref(target)?;@@ -250,7 +266,7 @@ pub fn handle_squash(&subjects,¤t_branch,repo_name,- &env.config.commit_generation,+ &effective_config,)?;// Display the generated commit message@@ -290,11 +306,11 @@ pub fn handle_squash(/// Handle `wt step squash --show-prompt`////// Builds and outputs the squash prompt without running the LLM or squashing.-pub fn step_show_squash_prompt(- target: Option<&str>,- config: &worktrunk::config::CommitGenerationConfig,-) -> anyhow::Result<()> {+pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {let repo = Repository::current()?;+ let config = UserConfig::load().context("Failed to load config")?;+ let project_id = repo.project_identifier().ok();+ let effective_config = config.commit_generation(project_id.as_deref());// Get and validate target ref (any commit-ish for merge-base calculation)let target_branch = repo.require_target_ref(target)?;@@ -325,7 +341,7 @@ pub fn step_show_squash_prompt(&subjects,¤t_branch,repo_name,- config,+ &effective_config,)?;crate::output::stdout(prompt)?;Ok(())diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 57847a085..cf4d4a8ea 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -99,8 +99,9 @@ pub fn compute_worktree_path()})?;+ let project = repo.project_identifier().ok();let relative_path = config- .format_path(repo_name, branch, repo)+ .format_path(repo_name, branch, repo, project.as_deref()).map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;Ok(repo_root.join(relative_path).normalize())diff --git a/src/config/mod.rs b/src/config/mod.rsindex f6f26bcc3..f92e73544 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -38,8 +38,9 @@ pub use project::{find_unknown_keys as find_unknown_project_keys,};pub use user::{- CommitGenerationConfig, StageMode, UserConfig, UserProjectConfig,- find_unknown_keys as find_unknown_user_keys, get_config_path, set_config_path,+ CommitConfig, CommitGenerationConfig, ListConfig, MergeConfig, StageMode, UserConfig,+ UserProjectConfig, find_unknown_keys as find_unknown_user_keys, get_config_path,+ set_config_path,};#[cfg(test)]@@ -112,7 +113,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature-x", &test.repo)+ .format_path("myproject", "feature-x", &test.repo, None).unwrap(),"myproject.feature-x");@@ -127,7 +128,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature-x", &test.repo)+ .format_path("myproject", "feature-x", &test.repo, None).unwrap(),"myproject-feature-x");@@ -142,7 +143,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature-x", &test.repo)+ .format_path("myproject", "feature-x", &test.repo, None).unwrap(),".worktrees/myproject/feature-x");@@ -158,7 +159,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature/foo", &test.repo)+ .format_path("myproject", "feature/foo", &test.repo, None).unwrap(),"myproject.feature-foo");@@ -175,7 +176,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature/sub/task", &test.repo)+ .format_path("myproject", "feature/sub/task", &test.repo, None).unwrap(),".worktrees/myproject/feature-sub-task");@@ -193,7 +194,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature\\foo", &test.repo)+ .format_path("myproject", "feature\\foo", &test.repo, None).unwrap(),".worktrees/myproject/feature-foo");@@ -209,7 +210,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature/foo", &test.repo)+ .format_path("myproject", "feature/foo", &test.repo, None).unwrap(),"myproject.feature/foo");@@ -389,12 +390,15 @@ task2 = "echo 'Task 2 running' > task2.txt"fn test_user_project_config_equality() {let config1 = UserProjectConfig {approved_commands: vec!["npm install".to_string()],+ ..Default::default()};let config2 = UserProjectConfig {approved_commands: vec!["npm install".to_string()],+ ..Default::default()};let config3 = UserProjectConfig {approved_commands: vec!["npm test".to_string()],+ ..Default::default()};assert_eq!(config1, config2);assert_ne!(config1, config3);@@ -407,6 +411,7 @@ task2 = "echo 'Task 2 running' > task2.txt""github.com/user/repo".to_string(),UserProjectConfig {approved_commands: vec!["npm install".to_string()],+ ..Default::default()},);diff --git a/src/config/user.rs b/src/config/user.rsindex 8556d764f..6d9c4176b 100644--- a/src/config/user.rs+++ b/src/config/user.rs@@ -10,6 +10,30 @@ use std::sync::OnceLock;use super::HooksConfig;+/// Trait for merging configuration structs.+///+/// Project-specific config fields override global fields when set.+/// Fields that are `None` in the override fall back to the base value.+pub trait Merge {+ /// Merge with another config, where `other` takes precedence for set fields.+ fn merge_with(&self, other: &Self) -> Self;+}++/// Merge optional global and project configs, returning the effective config.+///+/// - Both set: merge (project takes precedence for set fields)+/// - Only project set: clone project+/// - Only global set: clone global+/// - Neither set: None+fn merge_optional<T: Merge + Clone>(global: Option<&T>, project: Option<&T>) -> Option<T> {+ match (global, project) {+ (Some(g), Some(p)) => Some(g.merge_with(p)),+ (None, Some(p)) => Some(p.clone()),+ (Some(g), None) => Some(g.clone()),+ (None, None) => None,+ }+}+/// 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.@@ -205,7 +229,7 @@ pub struct UserConfig {}/// Configuration for commit message generation-#[derive(Debug, Serialize, Deserialize, Clone, Default)]+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]pub struct CommitGenerationConfig {/// Command to invoke for generating commit messages (e.g., "llm", "claude")#[serde(default)]@@ -247,24 +271,77 @@ impl CommitGenerationConfig {}}+impl Merge for CommitGenerationConfig {+ fn merge_with(&self, other: &Self) -> Self {+ // For template/template_file pairs: if project sets one, it clears the other+ // This prevents violating mutual exclusivity when global has one and project has the other+ let (template, template_file) = if other.template.is_some() {+ (other.template.clone(), None)+ } else if other.template_file.is_some() {+ (None, other.template_file.clone())+ } else {+ (self.template.clone(), self.template_file.clone())+ };++ let (squash_template, squash_template_file) = if other.squash_template.is_some() {+ (other.squash_template.clone(), None)+ } else if other.squash_template_file.is_some() {+ (None, other.squash_template_file.clone())+ } else {+ (+ self.squash_template.clone(),+ self.squash_template_file.clone(),+ )+ };++ Self {+ command: other.command.clone().or_else(|| self.command.clone()),+ // For args: use other's if non-empty, else self's+ args: if other.args.is_empty() {+ self.args.clone()+ } else {+ other.args.clone()+ },+ template,+ template_file,+ squash_template,+ squash_template_file,+ }+ }+}+/// Per-project user configuration////// Stored in the user's config file under `[projects."project-id"]`./// Contains project-specific settings that are user preferences, not checked into git.+/// All fields override the corresponding global settings when set.////// # TOML Format/// ```toml/// [projects."github.com/user/repo"]+/// worktree-path = ".worktrees/{{ branch | sanitize }}"/// approved-commands = ["npm install", "npm test"]-/// ```///-/// # Future Extensibility-/// This structure is designed to accommodate additional per-project settings:-/// - default-target-branch-/// - auto-squash preferences-/// - project-specific hooks+/// [projects."github.com/user/repo".commit-generation]+/// command = "llm"+/// args = ["-m", "gpt-4"]+///+/// [projects."github.com/user/repo".list]+/// full = true+///+/// [projects."github.com/user/repo".merge]+/// squash = false+/// ```#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]pub struct UserProjectConfig {+ /// Worktree path template for this project (overrides global worktree-path)+ #[serde(+ rename = "worktree-path",+ default,+ skip_serializing_if = "Option::is_none"+ )]+ pub worktree_path: Option<String>,+/// Commands that have been approved for automatic execution in this project#[serde(default,@@ -272,6 +349,41 @@ pub struct UserProjectConfig {skip_serializing_if = "Vec::is_empty")]pub approved_commands: Vec<String>,++ /// Per-project commit generation settings (overrides global [commit-generation])+ #[serde(+ default,+ rename = "commit-generation",+ skip_serializing_if = "Option::is_none"+ )]+ pub commit_generation: Option<CommitGenerationConfig>,++ /// Per-project list settings (overrides global `[list]`)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub list: Option<ListConfig>,++ /// Per-project commit settings (overrides global `[commit]`)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub commit: Option<CommitConfig>,++ /// Per-project merge settings (overrides global `[merge]`)+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub merge: Option<MergeConfig>,+}++impl UserProjectConfig {+ /// Returns true if all fields are empty/None (no settings configured).+ ///+ /// Used to determine if a project entry can be removed from config after+ /// clearing approvals.+ pub fn is_empty(&self) -> bool {+ self.worktree_path.is_none()+ && self.approved_commands.is_empty()+ && self.commit_generation.is_none()+ && self.list.is_none()+ && self.commit.is_none()+ && self.merge.is_none()+ }}/// Configuration for the `wt list` command@@ -297,6 +409,17 @@ pub struct ListConfig {pub timeout_ms: Option<u64>,}+impl Merge for ListConfig {+ fn merge_with(&self, other: &Self) -> Self {+ Self {+ full: other.full.or(self.full),+ branches: other.branches.or(self.branches),+ remotes: other.remotes.or(self.remotes),+ timeout_ms: other.timeout_ms.or(self.timeout_ms),+ }+ }+}+/// Configuration for the `wt step commit` command////// Also used by `wt merge` for shared settings like `stage`.@@ -308,10 +431,18 @@ pub struct CommitConfig {pub stage: Option<StageMode>,}+impl Merge for CommitConfig {+ fn merge_with(&self, other: &Self) -> Self {+ Self {+ stage: other.stage.or(self.stage),+ }+ }+}+/// Configuration for the `wt merge` command////// Note: `stage` defaults from `[commit]` section, not here.-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]pub struct MergeConfig {/// Squash commits when merging (default: true)#[serde(skip_serializing_if = "Option::is_none")]@@ -336,6 +467,18 @@ pub struct MergeConfig {pub verify: Option<bool>,}+impl Merge for MergeConfig {+ fn merge_with(&self, other: &Self) -> Self {+ Self {+ squash: other.squash.or(self.squash),+ commit: other.commit.or(self.commit),+ rebase: other.rebase.or(self.rebase),+ remove: other.remove.or(self.remove),+ verify: other.verify.or(self.verify),+ }+ }+}+/// Configuration for the `wt select` command#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]pub struct SelectConfig {@@ -367,6 +510,65 @@ impl UserConfig {self.worktree_path.is_some()}+ /// Returns the worktree path template for a specific project.+ ///+ /// Checks project-specific config first, falls back to global worktree-path,+ /// and finally to the default template if neither is set.+ pub fn worktree_path_for_project(&self, project: &str) -> String {+ self.projects+ .get(project)+ .and_then(|p| p.worktree_path.clone())+ .unwrap_or_else(|| self.worktree_path())+ }++ /// Returns the commit generation config for a specific project.+ ///+ /// Merges project-specific settings with global settings, where project+ /// settings take precedence for fields that are set.+ pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {+ let global = &self.commit_generation;+ match project+ .and_then(|p| self.projects.get(p))+ .and_then(|c| c.commit_generation.as_ref())+ {+ Some(project_config) => global.merge_with(project_config),+ None => global.clone(),+ }+ }++ /// Returns the list config for a specific project.+ ///+ /// Merges project-specific settings with global settings, where project+ /// settings take precedence for fields that are set.+ pub fn list(&self, project: Option<&str>) -> Option<ListConfig> {+ let project_config = project+ .and_then(|p| self.projects.get(p))+ .and_then(|c| c.list.as_ref());+ merge_optional(self.list.as_ref(), project_config)+ }++ /// Returns the commit config for a specific project.+ ///+ /// Merges project-specific settings with global settings, where project+ /// settings take precedence for fields that are set.+ pub fn commit(&self, project: Option<&str>) -> Option<CommitConfig> {+ let project_config = project+ .and_then(|p| self.projects.get(p))+ .and_then(|c| c.commit.as_ref());+ merge_optional(self.commit.as_ref(), project_config)+ }++ /// Returns the merge config for a specific project.+ ///+ /// Merges project-specific settings with global settings, where project+ /// settings take precedence for fields that are set.+ pub fn merge(&self, project: Option<&str>) -> Option<MergeConfig> {+ let project_config = project+ .and_then(|p| self.projects.get(p))+ .and_then(|c| c.merge.as_ref());+ merge_optional(self.merge.as_ref(), project_config)+ }+/// Load configuration from config file and environment variables.////// Configuration is loaded in the following order (later sources override earlier ones):@@ -422,9 +624,14 @@ impl UserConfig {// is preserved (uses IndexMap instead of HashMap internally).// See: https://github.com/max-sixty/worktrunk/issues/737let config: Self = builder.build()?.try_deserialize()?;+ config.validate()?;+ Ok(config)+ }+ /// Validate configuration values.+ fn validate(&self) -> Result<(), ConfigError> {// Validate worktree path (only if explicitly set - default is always valid)- if let Some(ref path) = config.worktree_path {+ if let Some(ref path) = self.worktree_path {if path.is_empty() {return Err(ConfigError::Message("worktree-path cannot be empty".into()));}@@ -435,23 +642,63 @@ impl UserConfig {}}+ // Validate per-project configs+ for (project, project_config) in &self.projects {+ // Validate worktree path+ if let Some(ref path) = project_config.worktree_path {+ if path.is_empty() {+ return Err(ConfigError::Message(format!(+ "projects.{project}.worktree-path cannot be empty"+ )));+ }+ if std::path::Path::new(path).is_absolute() {+ return Err(ConfigError::Message(format!(+ "projects.{project}.worktree-path must be relative, not absolute"+ )));+ }+ }++ // Validate commit generation config+ if let Some(ref cg) = project_config.commit_generation {+ if cg.template.is_some() && cg.template_file.is_some() {+ return Err(ConfigError::Message(format!(+ "projects.{project}.commit-generation.template and template-file are mutually exclusive"+ )));+ }+ if cg.squash_template.is_some() && cg.squash_template_file.is_some() {+ return Err(ConfigError::Message(format!(+ "projects.{project}.commit-generation.squash-template and squash-template-file are mutually exclusive"+ )));+ }+ }+ }+// Validate commit generation config- if config.commit_generation.template.is_some()- && config.commit_generation.template_file.is_some()+ if self.commit_generation.template.is_some()+ && self.commit_generation.template_file.is_some(){return Err(ConfigError::Message("commit-generation.template and commit-generation.template-file are mutually exclusive".into(),));}- if config.commit_generation.squash_template.is_some()- && config.commit_generation.squash_template_file.is_some()+ if self.commit_generation.squash_template.is_some()+ && self.commit_generation.squash_template_file.is_some(){return Err(ConfigError::Message("commit-generation.squash-template and commit-generation.squash-template-file are mutually exclusive".into(),));}+ Ok(())+ }++ /// Load configuration from a TOML string for testing.+ #[cfg(test)]+ fn load_from_str(content: &str) -> Result<Self, ConfigError> {+ let config: Self =+ toml::from_str(content).map_err(|e| ConfigError::Message(e.to_string()))?;+ config.validate()?;Ok(config)}@@ -461,18 +708,25 @@ impl UserConfig {/// * `main_worktree` - Main worktree directory name (replaces {{ main_worktree }} in template)/// * `branch` - Branch name (replaces {{ branch }} in template; use `{{ branch | sanitize }}` for paths)/// * `repo` - Repository for template function access+ /// * `project` - Optional project identifier (e.g., "github.com/user/repo") to look up+ /// project-specific worktree-path templatepub fn format_path(&self,main_worktree: &str,branch: &str,repo: &crate::git::Repository,+ project: Option<&str>,) -> Result<String, String> {use std::collections::HashMap;+ let template = match project {+ Some(p) => self.worktree_path_for_project(p),+ None => self.worktree_path(),+ };let mut vars = HashMap::new();vars.insert("main_worktree", main_worktree);vars.insert("repo", main_worktree);vars.insert("branch", branch);- expand_template(&self.worktree_path(), &vars, false, repo, "worktree-path")+ expand_template(&template, &vars, false, repo, "worktree-path")}/// Execute a mutation under an exclusive file lock.@@ -609,7 +863,8 @@ impl UserConfig {project_config.approved_commands.retain(|c| c != &command);let changed = len_before != project_config.approved_commands.len();- if project_config.approved_commands.is_empty() {+ // Only remove project entry if it has no other settings+ if project_config.is_empty() {config.projects.remove(&project);}changed@@ -618,7 +873,11 @@ impl UserConfig {/// Remove all approvals for a project and save to config file.///- /// Acquires lock, reloads from disk, removes project if present, and saves.+ /// Clears only the approved-commands list, preserving other per-project settings+ /// like worktree-path, commit-generation, list, commit, and merge configs.+ /// The project entry is removed only if all settings are empty after clearing.+ ///+ /// Acquires lock, reloads from disk, clears approvals, and saves./// Pass `None` for default config path, or `Some(path)` for testing.pub fn revoke_project(&mut self,@@ -627,7 +886,18 @@ impl UserConfig {) -> Result<(), ConfigError> {let project = project.to_string();self.with_locked_mutation(config_path, |config| {- config.projects.remove(&project).is_some()+ let Some(project_config) = config.projects.get_mut(&project) else {+ return false;+ };+ if project_config.approved_commands.is_empty() {+ return false; // Nothing to clear+ }+ project_config.approved_commands.clear();+ // Only remove project entry if it has no other settings+ if project_config.is_empty() {+ config.projects.remove(&project);+ }+ true})}@@ -682,6 +952,53 @@ impl UserConfig {array}+ /// Serialize a per-project config section (commit-generation, list, commit, merge).+ ///+ /// If the config is Some, serializes it as a nested table. If None, removes the section.+ /// Used when updating an existing file.+ fn serialize_project_config_section<T: Serialize>(+ projects: &mut toml_edit::Table,+ project_id: &str,+ section_name: &str,+ config: Option<&T>,+ ) {+ if let Some(cfg) = config {+ // Serialize to TOML value, then convert to toml_edit Item+ if let Ok(toml_value) = toml::to_string(cfg)+ && let Ok(parsed) = toml_value.parse::<toml_edit::DocumentMut>()+ {+ let mut table = toml_edit::Table::new();+ for (k, v) in parsed.iter() {+ table[k] = v.clone();+ }+ projects[project_id][section_name] = toml_edit::Item::Table(table);+ }+ } else if let Some(project_table) = projects[project_id].as_table_mut() {+ project_table.remove(section_name);+ }+ }++ /// Serialize a nested config section into a table.+ ///+ /// If the config is Some, serializes it as a nested table. If None, does nothing.+ /// Used when creating a new file from scratch.+ fn serialize_nested_config<T: Serialize>(+ table: &mut toml_edit::Table,+ section_name: &str,+ config: Option<&T>,+ ) {+ if let Some(cfg) = config+ && let Ok(toml_value) = toml::to_string(cfg)+ && let Ok(parsed) = toml_value.parse::<toml_edit::DocumentMut>()+ {+ let mut nested = toml_edit::Table::new();+ for (k, v) in parsed.iter() {+ nested[k] = v.clone();+ }+ table[section_name] = toml_edit::Item::Table(nested);+ }+ }+/// Save the current configuration to a specific file path////// Use this in tests to save to a temporary location instead of the user's config.@@ -732,9 +1049,44 @@ impl UserConfig {if !projects.contains_key(project_id) {projects[project_id] = toml_edit::Item::Table(toml_edit::Table::new());}++ // worktree-path (only if set)+ if let Some(ref path) = project_config.worktree_path {+ projects[project_id]["worktree-path"] = toml_edit::value(path);+ } else if let Some(table) = projects[project_id].as_table_mut() {+ table.remove("worktree-path");+ }++ // approved-commandslet commands =Self::format_multiline_array(project_config.approved_commands.iter());projects[project_id]["approved-commands"] = toml_edit::value(commands);++ // Per-project nested config sections+ Self::serialize_project_config_section(+ projects,+ project_id,+ "commit-generation",+ project_config.commit_generation.as_ref(),+ );+ Self::serialize_project_config_section(+ projects,+ project_id,+ "list",+ project_config.list.as_ref(),+ );+ Self::serialize_project_config_section(+ projects,+ project_id,+ "commit",+ project_config.commit.as_ref(),+ );+ Self::serialize_project_config_section(+ projects,+ project_id,+ "merge",+ project_config.merge.as_ref(),+ );}}@@ -767,9 +1119,35 @@ impl UserConfig {projects_table.set_implicit(true); // Don't emit [projects] headerfor (project_id, project_config) in &self.projects {let mut table = toml_edit::Table::new();++ // worktree-path (only if set)+ if let Some(ref path) = project_config.worktree_path {+ table["worktree-path"] = toml_edit::value(path);+ }++ // approved-commandslet commands =Self::format_multiline_array(project_config.approved_commands.iter());table["approved-commands"] = toml_edit::value(commands);++ // Per-project nested config sections+ Self::serialize_nested_config(+ &mut table,+ "commit-generation",+ project_config.commit_generation.as_ref(),+ );+ Self::serialize_nested_config(&mut table, "list", project_config.list.as_ref());+ Self::serialize_nested_config(+ &mut table,+ "commit",+ project_config.commit.as_ref(),+ );+ Self::serialize_nested_config(+ &mut table,+ "merge",+ project_config.merge.as_ref(),+ );+projects_table[project_id] = toml_edit::Item::Table(table);}doc["projects"] = toml_edit::Item::Table(projects_table);@@ -974,9 +1352,115 @@ rename-tab = "echo 'switched'"#[test]fn test_user_project_config_default() {let config = UserProjectConfig::default();+ assert!(config.worktree_path.is_none());assert!(config.approved_commands.is_empty());}+ #[test]+ fn test_user_project_config_with_worktree_path_serde() {+ let config = UserProjectConfig {+ worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),+ approved_commands: vec!["npm install".to_string()],+ ..Default::default()+ };+ let toml = toml::to_string(&config).unwrap();+ assert!(toml.contains("worktree-path"));+ assert!(toml.contains(".worktrees/{{ branch | sanitize }}"));++ let parsed: UserProjectConfig = toml::from_str(&toml).unwrap();+ assert_eq!(+ parsed.worktree_path,+ Some(".worktrees/{{ branch | sanitize }}".to_string())+ );+ assert_eq!(parsed.approved_commands, vec!["npm install".to_string()]);+ }++ #[test]+ fn test_worktree_path_for_project_uses_project_specific() {+ let mut config = UserConfig::default();+ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectConfig {+ worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),+ approved_commands: vec![],+ ..Default::default()+ },+ );++ // Project-specific path should be used+ assert_eq!(+ config.worktree_path_for_project("github.com/user/repo"),+ ".worktrees/{{ branch | sanitize }}"+ );+ }++ #[test]+ fn test_worktree_path_for_project_falls_back_to_global() {+ let mut config = UserConfig {+ worktree_path: Some("../{{ repo }}-{{ branch | sanitize }}".to_string()),+ ..Default::default()+ };+ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectConfig {+ worktree_path: None, // No project-specific path+ approved_commands: vec!["npm install".to_string()],+ ..Default::default()+ },+ );++ // Should fall back to global worktree-path+ assert_eq!(+ config.worktree_path_for_project("github.com/user/repo"),+ "../{{ repo }}-{{ branch | sanitize }}"+ );+ }++ #[test]+ fn test_worktree_path_for_project_falls_back_to_default() {+ let config = UserConfig::default();++ // Unknown project should fall back to default template+ assert_eq!(+ config.worktree_path_for_project("github.com/unknown/project"),+ "../{{ repo }}.{{ branch | sanitize }}"+ );+ }++ #[test]+ fn test_format_path_with_project_override() {+ let test = test_repo();+ let mut config = UserConfig {+ worktree_path: Some("../{{ repo }}.{{ branch | sanitize }}".to_string()),+ ..Default::default()+ };+ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectConfig {+ worktree_path: Some(".worktrees/{{ branch | sanitize }}".to_string()),+ approved_commands: vec![],+ ..Default::default()+ },+ );++ // With project identifier, should use project-specific template+ let path = config+ .format_path(+ "myrepo",+ "feature/branch",+ &test.repo,+ Some("github.com/user/repo"),+ )+ .unwrap();+ assert_eq!(path, ".worktrees/feature-branch");++ // Without project identifier, should use global template+ let path = config+ .format_path("myrepo", "feature/branch", &test.repo, None)+ .unwrap();+ assert_eq!(path, "../myrepo.feature-branch");+ }+#[test]fn test_list_config_serde() {let config = ListConfig {@@ -1029,6 +1513,7 @@ rename-tab = "echo 'switched'""github.com/user/repo".to_string(),UserProjectConfig {approved_commands: vec!["npm install".to_string(), "npm test".to_string()],+ ..Default::default()},);assert!(config.is_command_approved("github.com/user/repo", "npm install"));@@ -1047,6 +1532,7 @@ rename-tab = "echo 'switched'"approved_commands: vec!["ln -sf {{ repo_root }}/node_modules".to_string(), // old var],+ ..Default::default()},);@@ -1073,6 +1559,7 @@ rename-tab = "echo 'switched'"approved_commands: vec!["cd {{ worktree_path }} && npm install".to_string(), // new var],+ ..Default::default()},);@@ -1092,6 +1579,7 @@ rename-tab = "echo 'switched'"approved_commands: vec!["ln -sf {{ repo_root }}/modules {{ worktree }}/modules".to_string(),],+ ..Default::default()},);@@ -1113,7 +1601,7 @@ rename-tab = "echo 'switched'"let test = test_repo();let config = UserConfig::default();let path = config- .format_path("myrepo", "feature/branch", &test.repo)+ .format_path("myrepo", "feature/branch", &test.repo, None).unwrap();assert_eq!(path, "../myrepo.feature-branch");}@@ -1125,7 +1613,9 @@ rename-tab = "echo 'switched'"worktree_path: Some(".worktrees/{{ branch }}".to_string()),..Default::default()};- let path = config.format_path("myrepo", "feature", &test.repo).unwrap();+ let path = config+ .format_path("myrepo", "feature", &test.repo, None)+ .unwrap();assert_eq!(path, ".worktrees/feature");}@@ -1220,4 +1710,468 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"let config: UserConfig = toml::from_str(content).unwrap();assert!(!config.skip_shell_integration_prompt);}++ // =========================================================================+ // Merge trait tests+ // =========================================================================++ #[test]+ fn test_merge_list_config() {+ let base = ListConfig {+ full: Some(true),+ branches: Some(false),+ remotes: None,+ timeout_ms: Some(1000),+ };+ let override_config = ListConfig {+ full: None, // Should fall back to base+ branches: Some(true), // Should override+ remotes: Some(true), // Should override (base was None)+ timeout_ms: None, // Should fall back to base+ };++ let merged = base.merge_with(&override_config);+ assert_eq!(merged.full, Some(true)); // From base+ assert_eq!(merged.branches, Some(true)); // From override+ assert_eq!(merged.remotes, Some(true)); // From override+ assert_eq!(merged.timeout_ms, Some(1000)); // From base+ }++ #[test]+ fn test_merge_commit_config() {+ let base = CommitConfig {+ stage: Some(StageMode::All),+ };+ let override_config = CommitConfig {+ stage: Some(StageMode::Tracked),+ };++ let merged = base.merge_with(&override_config);+ assert_eq!(merged.stage, Some(StageMode::Tracked));+ }++ #[test]+ fn test_merge_merge_config() {+ let base = MergeConfig {+ squash: Some(true),+ commit: Some(true),+ rebase: Some(true),+ remove: Some(true),+ verify: Some(true),+ };+ let override_config = MergeConfig {+ squash: Some(false), // Override+ commit: None, // Fall back to base+ rebase: None, // Fall back to base+ remove: Some(false), // Override+ verify: None, // Fall back to base+ };++ let merged = base.merge_with(&override_config);+ assert_eq!(merged.squash, Some(false));+ assert_eq!(merged.commit, Some(true));+ assert_eq!(merged.rebase, Some(true));+ assert_eq!(merged.remove, Some(false));+ assert_eq!(merged.verify, Some(true));+ }++ #[test]+ fn test_merge_commit_generation_config() {+ let base = CommitGenerationConfig {+ command: Some("llm".to_string()),+ args: vec!["-s".to_string()],+ template: None,+ template_file: Some("~/.config/template.txt".to_string()),+ squash_template: None,+ squash_template_file: None,+ };+ let override_config = CommitGenerationConfig {+ command: Some("claude".to_string()), // Override+ args: vec![], // Empty = fall back to base+ template: Some("custom".to_string()), // Override (was None)+ template_file: None, // Fall back to base+ squash_template: None,+ squash_template_file: None,+ };++ let merged = base.merge_with(&override_config);+ assert_eq!(merged.command, Some("claude".to_string()));+ assert_eq!(merged.args, vec!["-s".to_string()]); // Base, since override was empty+ assert_eq!(merged.template, Some("custom".to_string()));+ // When project sets template, template_file is cleared to maintain mutual exclusivity+ assert_eq!(merged.template_file, None);+ }++ #[test]+ fn test_commit_generation_merge_mutual_exclusivity() {+ // Global has template_file, project has template+ // Merged result should only have template (project wins, clears template_file)+ let global = CommitGenerationConfig {+ template_file: Some("~/.config/template.txt".to_string()),+ ..Default::default()+ };+ let project = CommitGenerationConfig {+ template: Some("inline template".to_string()),+ ..Default::default()+ };++ let merged = global.merge_with(&project);+ assert_eq!(merged.template, Some("inline template".to_string()));+ assert_eq!(merged.template_file, None); // Cleared because project set template++ // Reverse: global has template, project has template_file+ let global = CommitGenerationConfig {+ template: Some("global template".to_string()),+ ..Default::default()+ };+ let project = CommitGenerationConfig {+ template_file: Some("project-file.txt".to_string()),+ ..Default::default()+ };++ let merged = global.merge_with(&project);+ assert_eq!(merged.template, None); // Cleared because project set template_file+ assert_eq!(merged.template_file, Some("project-file.txt".to_string()));++ // Neither set in project: inherit both from global+ let global = CommitGenerationConfig {+ template: Some("global template".to_string()),+ ..Default::default()+ };+ let project = CommitGenerationConfig::default();++ let merged = global.merge_with(&project);+ assert_eq!(merged.template, Some("global template".to_string()));+ assert_eq!(merged.template_file, None);+ }++ // =========================================================================+ // Effective config methods tests+ // =========================================================================++ #[test]+ fn test_effective_commit_generation_no_project() {+ let mut config = UserConfig::default();+ config.commit_generation.command = Some("global-llm".to_string());++ let effective = config.commit_generation(None);+ assert_eq!(effective.command, Some("global-llm".to_string()));+ }++ #[test]+ fn test_effective_commit_generation_with_project_override() {+ let mut config = UserConfig::default();+ config.commit_generation.command = Some("global-llm".to_string());+ config.commit_generation.args = vec!["--global".to_string()];++ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectConfig {+ commit_generation: Some(CommitGenerationConfig {+ command: Some("project-llm".to_string()),+ args: vec!["--project".to_string()],+ ..Default::default()+ }),+ ..Default::default()+ },+ );++ // With project identifier, should merge project config+ let effective = config.commit_generation(Some("github.com/user/repo"));+ assert_eq!(effective.command, Some("project-llm".to_string()));+ assert_eq!(effective.args, vec!["--project".to_string()]);++ // Without project or unknown project, should use global+ let effective = config.commit_generation(None);+ assert_eq!(effective.command, Some("global-llm".to_string()));++ let effective = config.commit_generation(Some("github.com/other/repo"));+ assert_eq!(effective.command, Some("global-llm".to_string()));+ }++ #[test]+ fn test_effective_merge_with_partial_override() {+ let mut config = UserConfig {+ merge: Some(MergeConfig {+ squash: Some(true),+ commit: Some(true),+ rebase: Some(true),+ remove: Some(true),+ verify: Some(true),+ }),+ ..Default::default()+ };++ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectConfig {+ merge: Some(MergeConfig {+ squash: Some(false), // Only override squash+ commit: None,+ rebase: None,+ remove: None,+ verify: None,+ }),+ ..Default::default()+ },+ );++ let effective = config.merge(Some("github.com/user/repo")).unwrap();+ assert_eq!(effective.squash, Some(false)); // From project+ assert_eq!(effective.commit, Some(true)); // From global+ assert_eq!(effective.rebase, Some(true)); // From global+ }++ #[test]+ fn test_effective_list_project_only() {+ // No global list config, only project config+ let mut config = UserConfig::default();+ assert!(config.list.is_none());++ config.projects.insert(+ "github.com/user/repo".to_string(),+ UserProjectConfig {+ list: Some(ListConfig {+ full: Some(true),+ branches: None,+ remotes: None,+ timeout_ms: None,+ }),+ ..Default::default()+ },+ );++ let effective = config.list(Some("github.com/user/repo")).unwrap();+ assert_eq!(effective.full, Some(true));+ assert!(effective.branches.is_none());++ // No global, no matching project = None+ assert!(config.list(Some("github.com/other/repo")).is_none());+ }++ #[test]+ fn test_effective_commit_global_only() {+ // Only global config, no project config+ let config = UserConfig {+ commit: Some(CommitConfig {+ stage: Some(StageMode::Tracked),+ }),+ ..Default::default()+ };++ let effective = config.commit(Some("github.com/any/project")).unwrap();+ assert_eq!(effective.stage, Some(StageMode::Tracked));+ }++ // =========================================================================+ // Per-project config serde tests+ // =========================================================================++ #[test]+ fn test_user_project_config_with_nested_configs_serde() {+ let config = UserProjectConfig {+ worktree_path: Some(".worktrees/{{ branch }}".to_string()),+ approved_commands: vec!["npm install".to_string()],+ commit_generation: Some(CommitGenerationConfig {+ command: Some("llm".to_string()),+ args: vec!["-m".to_string(), "gpt-4".to_string()],+ ..Default::default()+ }),+ list: Some(ListConfig {+ full: Some(true),+ ..Default::default()+ }),+ commit: Some(CommitConfig {+ stage: Some(StageMode::Tracked),+ }),+ merge: Some(MergeConfig {+ squash: Some(false),+ ..Default::default()+ }),+ };++ let toml = toml::to_string(&config).unwrap();+ let parsed: UserProjectConfig = toml::from_str(&toml).unwrap();++ assert_eq!(+ parsed.worktree_path,+ Some(".worktrees/{{ branch }}".to_string())+ );+ assert_eq!(+ parsed.commit_generation.as_ref().unwrap().command,+ Some("llm".to_string())+ );+ assert_eq!(parsed.list.as_ref().unwrap().full, Some(true));+ assert_eq!(+ parsed.commit.as_ref().unwrap().stage,+ Some(StageMode::Tracked)+ );+ assert_eq!(parsed.merge.as_ref().unwrap().squash, Some(false));+ }++ #[test]+ fn test_full_config_with_per_project_sections_serde() {+ let content = r#"+worktree-path = "../{{ repo }}.{{ branch | sanitize }}"++[commit-generation]+command = "llm"++[projects."github.com/user/repo"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+approved-commands = ["npm install"]++[projects."github.com/user/repo".commit-generation]+command = "claude"+args = ["--model", "opus"]++[projects."github.com/user/repo".list]+full = true++[projects."github.com/user/repo".merge]+squash = false+"#;++ let config: UserConfig = toml::from_str(content).unwrap();++ // Global config+ assert_eq!(+ config.worktree_path,+ Some("../{{ repo }}.{{ branch | sanitize }}".to_string())+ );+ assert_eq!(config.commit_generation.command, Some("llm".to_string()));++ // Project config+ let project = config.projects.get("github.com/user/repo").unwrap();+ assert_eq!(+ project.worktree_path,+ Some(".worktrees/{{ branch | sanitize }}".to_string())+ );+ assert_eq!(+ project.commit_generation.as_ref().unwrap().command,+ Some("claude".to_string())+ );+ assert_eq!(+ project.commit_generation.as_ref().unwrap().args,+ vec!["--model".to_string(), "opus".to_string()]+ );+ assert_eq!(project.list.as_ref().unwrap().full, Some(true));+ assert_eq!(project.merge.as_ref().unwrap().squash, Some(false));++ // Effective config for project+ let effective_cg = config.commit_generation(Some("github.com/user/repo"));+ assert_eq!(effective_cg.command, Some("claude".to_string()));++ let effective_merge = config.merge(Some("github.com/user/repo")).unwrap();+ assert_eq!(effective_merge.squash, Some(false));+ }++ // Validation tests++ #[test]+ fn test_validation_empty_worktree_path() {+ let content = r#"worktree-path = """#;+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("worktree-path cannot be empty"), "{err}");+ }++ #[test]+ fn test_validation_absolute_worktree_path() {+ // Use platform-appropriate absolute path+ let content = if cfg!(windows) {+ r#"worktree-path = "C:\\absolute\\path""#+ } else {+ r#"worktree-path = "/absolute/path""#+ };+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("must be relative"), "{err}");+ }++ #[test]+ fn test_validation_project_empty_worktree_path() {+ let content = r#"+[projects."github.com/user/repo"]+worktree-path = ""+"#;+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("worktree-path cannot be empty"), "{err}");+ }++ #[test]+ fn test_validation_project_absolute_worktree_path() {+ // Use platform-appropriate absolute path+ let content = if cfg!(windows) {+ r#"+[projects."github.com/user/repo"]+worktree-path = "C:\\absolute\\path"+"#+ } else {+ r#"+[projects."github.com/user/repo"]+worktree-path = "/absolute/path"+"#+ };+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("must be relative"), "{err}");+ }++ #[test]+ fn test_validation_template_mutual_exclusivity() {+ let content = r#"+[commit-generation]+template = "inline template"+template-file = "path/to/file"+"#;+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("mutually exclusive"), "{err}");+ }++ #[test]+ fn test_validation_squash_template_mutual_exclusivity() {+ let content = r#"+[commit-generation]+squash-template = "inline template"+squash-template-file = "path/to/file"+"#;+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("mutually exclusive"), "{err}");+ }++ #[test]+ fn test_validation_project_template_mutual_exclusivity() {+ let content = r#"+[projects."github.com/user/repo".commit-generation]+template = "inline template"+template-file = "path/to/file"+"#;+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("mutually exclusive"), "{err}");+ }++ #[test]+ fn test_validation_project_squash_template_mutual_exclusivity() {+ let content = r#"+[projects."github.com/user/repo".commit-generation]+squash-template = "inline template"+squash-template-file = "path/to/file"+"#;+ let result = UserConfig::load_from_str(content);+ assert!(result.is_err());+ let err = result.unwrap_err().to_string();+ assert!(err.contains("mutually exclusive"), "{err}");+ }}diff --git a/src/main.rs b/src/main.rsindex 51a859158..e0e0bde25 100644--- a/src/main.rs+++ b/src/main.rs@@ -67,8 +67,7 @@ fn enhance_and_exit_error(err: clap::Error) -> ! {&& let Some(unknown) = err.get(clap::error::ContextKind::InvalidSubcommand){let cmd = cli::build_command();- if let Some(suggestion) = cli::suggest_nested_subcommand(&cmd, unknown.to_string().as_str())- {+ if let Some(suggestion) = cli::suggest_nested_subcommand(&cmd, &unknown.to_string()) {ceprintln!("{}<yellow>tip:</> did you mean <cyan,bold>{suggestion}</cyan,bold>?",@@ -480,68 +479,54 @@ fn main() {verify,stage,show_prompt,- } => UserConfig::load()- .context("Failed to load config")- .and_then(|config| {- let stage_final = stage- .or_else(|| config.commit.and_then(|c| c.stage))- .unwrap_or_default();- step_commit(yes, !verify, stage_final, show_prompt)- }),+ } => step_commit(yes, !verify, stage, show_prompt),StepCommand::Squash {target,yes,verify,stage,show_prompt,- } => UserConfig::load()- .context("Failed to load config")- .and_then(|config| {- let stage_final = stage- .or_else(|| config.commit.and_then(|c| c.stage))- .unwrap_or_default();-- // Handle --show-prompt early: just build and output the prompt- if show_prompt {- return commands::step_show_squash_prompt(- target.as_deref(),- &config.commit_generation,- );- }-- // "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)- // Shadow verify: if user declines approval, skip hooks but continue squash- let verify = if verify {- use commands::command_approval::approve_hooks;- use commands::context::CommandEnv;- let env = CommandEnv::for_action("squash")?;- let ctx = env.context(yes);- let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;- if !approved {- crate::output::print(info_message(- "Commands declined, squashing without hooks",- ))?;- }- approved- } else {- false- };+ } => {+ // Handle --show-prompt early: just build and output the prompt+ if show_prompt {+ commands::step_show_squash_prompt(target.as_deref())+ } else {+ (|| {+ // "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)+ // Shadow verify: if user declines approval, skip hooks but continue squash+ let verify = if verify {+ use commands::command_approval::approve_hooks;+ use commands::context::CommandEnv;+ let env = CommandEnv::for_action("squash")?;+ let ctx = env.context(yes);+ let approved = approve_hooks(&ctx, &[HookType::PreCommit])?;+ if !approved {+ crate::output::print(info_message(+ "Commands declined, squashing without hooks",+ ))?;+ }+ approved+ } else {+ false+ };- match handle_squash(target.as_deref(), yes, !verify, stage_final)? {- SquashResult::Squashed | SquashResult::NoNetChanges => {}- SquashResult::NoCommitsAhead(branch) => {- crate::output::print(info_message(format!(- "Nothing to squash; no commits ahead of {branch}"- )))?;- }- SquashResult::AlreadySingleCommit => {- crate::output::print(info_message(- "Nothing to squash; already a single commit",- ))?;+ match handle_squash(target.as_deref(), yes, !verify, stage)? {+ SquashResult::Squashed | SquashResult::NoNetChanges => {}+ SquashResult::NoCommitsAhead(branch) => {+ crate::output::print(info_message(format!(+ "Nothing to squash; no commits ahead of {branch}"+ )))?;+ }+ SquashResult::AlreadySingleCommit => {+ crate::output::print(info_message(+ "Nothing to squash; already a single commit",+ ))?;+ }}- }- Ok(())- }),+ Ok(())+ })()+ }+ }StepCommand::Push { target } => handle_push(target.as_deref(), "Pushed to", None),StepCommand::Rebase { target } => {handle_rebase(target.as_deref()).and_then(|result| match result {@@ -629,10 +614,14 @@ fn main() {UserConfig::load().context("Failed to load config").and_then(|config| {- // Get config values from [list] config (shared with wt list)+ // Get project ID for per-project config lookup+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());++ // Get effective list config (merges project-specific with global)let (show_branches_config, show_remotes_config) = config- .list- .as_ref()+ .list(project_id.as_deref()).map(|l| (l.branches.unwrap_or(false), l.remotes.unwrap_or(false))).unwrap_or((false, false));@@ -670,10 +659,14 @@ fn main() {UserConfig::load().context("Failed to load config").and_then(|config| {- // Get config values from global list config+ // Get project ID for per-project config lookup+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());++ // Get effective list config (merges project-specific with global)let (show_branches_config, show_remotes_config, show_full_config) = config- .list- .as_ref()+ .list(project_id.as_deref()).map(|l| {(l.branches.unwrap_or(false),@@ -1081,49 +1074,29 @@ fn main() {no_verify,yes,stage,- } => UserConfig::load()- .context("Failed to load config")- .and_then(|config| {- // Convert paired flags to Option<bool>- fn flag_pair(positive: bool, negative: bool) -> Option<bool> {- match (positive, negative) {- (true, _) => Some(true),- (_, true) => Some(false),- _ => None,- }+ } => {+ // Convert paired flags to Option<bool>+ fn flag_pair(positive: bool, negative: bool) -> Option<bool> {+ match (positive, negative) {+ (true, _) => Some(true),+ (_, true) => Some(false),+ _ => None,}+ }- // Get config defaults (positive form: true = do it)- let merge_config = config.merge.as_ref();- let squash_default = merge_config.and_then(|m| m.squash).unwrap_or(true);- let commit_default = merge_config.and_then(|m| m.commit).unwrap_or(true);- let rebase_default = merge_config.and_then(|m| m.rebase).unwrap_or(true);- let remove_default = merge_config.and_then(|m| m.remove).unwrap_or(true);- let verify_default = merge_config.and_then(|m| m.verify).unwrap_or(true);-- // CLI flags override config, config overrides defaults- let squash_final = flag_pair(squash, no_squash).unwrap_or(squash_default);- let commit_final = flag_pair(commit, no_commit).unwrap_or(commit_default);- let rebase_final = flag_pair(rebase, no_rebase).unwrap_or(rebase_default);- let remove_final = flag_pair(remove, no_remove).unwrap_or(remove_default);- let verify_final = flag_pair(verify, no_verify).unwrap_or(verify_default);-- // Stage defaults from [commit] config section- let stage_final = stage- .or_else(|| config.commit.and_then(|c| c.stage))- .unwrap_or_default();-- handle_merge(MergeOptions {- target: target.as_deref(),- squash: squash_final,- commit: commit_final,- rebase: rebase_final,- remove: remove_final,- verify: verify_final,- yes,- stage_mode: stage_final,- })- }),+ // Pass CLI flags as options; handle_merge determines effective defaults+ // using per-project config merged with global config+ handle_merge(MergeOptions {+ target: target.as_deref(),+ squash: flag_pair(squash, no_squash),+ commit: flag_pair(commit, no_commit),+ rebase: flag_pair(rebase, no_rebase),+ remove: flag_pair(remove, no_remove),+ verify: flag_pair(verify, no_verify),+ yes,+ stage,+ })+ }};if let Err(e) = result {diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snapindex 4a1dd96b2..0c13785e4 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap@@ -9,6 +9,7 @@ info:env:CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_EDITOR: ""RUST_LOG: warnSHELL: ""SOURCE_DATE_EPOCH: "1735776000"@@ -142,13 +143,21 @@ Creates [2m~/.config/worktrunk/config.toml[0m with the following content:[2m# # Example:[2m# # pager = "delta --paging=never"[2m#- [2m# ### Approved commands+ [2m# ### Per-project settings (Experimental)[2m#- [2m# Commands approved for project hooks. Auto-populated when approving hooks on first run, or via `wt hook approvals add`.+ [2m# Per-project settings are keyed by project identifier (e.g., `github.com/user/repo`).+ [2m# These contain approved hook commands plus optional overrides of global settings.+ [2m# Setting overrides (worktree-path, list, commit, merge) are new; approved-commands is stable.[2m#[2m# [projects."github.com/user/repo"]+ [2m# # Approved hook commands (auto-populated when approving on first run)[2m# approved-commands = ["npm ci", "npm test"][2m#+ [2m# # Optional overrides (omit to use global settings)+ [2m# worktree-path = ".worktrees/{{ branch | sanitize }}"+ [2m# list.full = true+ [2m# merge.squash = false+ [2m#[2m# For project-specific hooks (post-create, post-start, pre-merge, etc.), use a project config at `<repo>/.config/wt.toml`. Run `wt config create --project` to create one, or see `wt hook` docs (https://worktrunk.dev/hook/).[2m#[2m# ### Custom prompt templatesdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 42fd573b1..aab5dcc21 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -8,6 +8,7 @@ info:env:CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_EDITOR: ""RUST_LOG: warnSHELL: ""SOURCE_DATE_EPOCH: "1735776000"@@ -169,12 +170,20 @@ Pager behavior for [2mwt select[0m diff previews.[2m# Example:[2m# pager = "delta --paging=never"-[32mApproved commands+[32mPer-project settings (Experimental)-Commands approved for project hooks. Auto-populated when approving hooks on first run, or via [2mwt hook approvals add[0m.+Per-project settings are keyed by project identifier (e.g., [2mgithub.com/user/repo[0m).+These contain approved hook commands plus optional overrides of global settings.+Setting overrides (worktree-path, list, commit, merge) are new; approved-commands is stable.[2m[projects."github.com/user/repo"]+ [2m# Approved hook commands (auto-populated when approving on first run)[2mapproved-commands = ["npm ci", "npm test"]+ [2m+ [2m# Optional overrides (omit to use global settings)+ [2mworktree-path = ".worktrees/{{ branch | sanitize }}"+ [2mlist.full = true+ [2mmerge.squash = falseFor project-specific hooks (post-create, post-start, pre-merge, etc.), use a project config at [2m<repo>/.config/wt.toml[0m. Run [2mwt config create --project[0m to create one, or see [2mwt hook[0m docs.