Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: resolve every no-argument default through `@`, which outside a worktree names HEAD's branch (#4521)
Maximilian Roosa4573593db58
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 4abde760e..f42b2d09f 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -755,10 +755,8 @@ pub fn handle_state_get(None => println!(""),},"marker" => {- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "get marker")?,- None => repo.require_current_branch("get marker for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "get marker")?;if format == SwitchFormat::Json {// Read raw config to get both marker and set_atlet config_key = format!("worktrunk.state.{branch_name}.marker");@@ -788,10 +786,8 @@ pub fn handle_state_get(}}"ci-status" => {- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "get ci-status")?,- None => repo.require_current_branch("get ci-status for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "get ci-status")?;// Ask git for both qualified forms in one call so the remote/local// determination and the HEAD SHA come from the same ref. A local@@ -923,10 +919,8 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any);}"marker" => {- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "set marker")?,- None => repo.require_current_branch("set marker for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "set marker")?;// Store as JSON with timestamplet now = epoch_now();@@ -989,10 +983,8 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho}} else {// Clear CI status for specific branch- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "clear ci-status")?,- None => repo.require_current_branch("clear ci-status for current branch")?,- };+ let branch_name = repo+ .require_selected_branch(branch.as_deref().unwrap_or("@"), "clear ci-status")?;if CachedCiStatus::clear_one(&repo, &branch_name)? {eprintln!("{}",@@ -1021,10 +1013,8 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho);}} else {- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "clear marker")?,- None => repo.require_current_branch("clear marker for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "clear marker")?;let config_key = format!("worktrunk.state.{branch_name}.marker");if repo.unset_config(&config_key)? {@@ -1673,10 +1663,8 @@ fn validate_vars_key(key: &str) -> anyhow::Result<()> {pub fn handle_vars_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {validate_vars_key(key)?;let repo = Repository::current()?;- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "get variable")?,- None => repo.require_current_branch("get variable for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "get variable")?;let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");if let Some(value) = repo.config_value(&config_key)? {@@ -1689,10 +1677,8 @@ pub fn handle_vars_get(key: &str, branch: Option<String>) -> anyhow::Result<()>pub fn handle_vars_set(key: &str, value: &str, branch: Option<String>) -> anyhow::Result<()> {validate_vars_key(key)?;let repo = Repository::current()?;- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "set variable")?,- None => repo.require_current_branch("set variable for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "set variable")?;let config_key = format!("worktrunk.state.{branch_name}.vars.{key}");repo.set_config(&config_key, value)?;@@ -1707,10 +1693,8 @@ pub fn handle_vars_set(key: &str, value: &str, branch: Option<String>) -> anyhow/// Handle vars listpub fn handle_vars_list(branch: Option<String>, format: SwitchFormat) -> anyhow::Result<()> {let repo = Repository::current()?;- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "list variables")?,- None => repo.require_current_branch("list variables for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "list variables")?;let entries: Vec<_> = repo.vars_entries(&branch_name).into_iter().collect();@@ -1740,10 +1724,8 @@ pub fn handle_vars_clear(branch: Option<String>,) -> anyhow::Result<()> {let repo = Repository::current()?;- let branch_name = match branch {- Some(b) => repo.require_selected_branch(&b, "clear variable")?,- None => repo.require_current_branch("clear variable for current branch")?,- };+ let branch_name =+ repo.require_selected_branch(branch.as_deref().unwrap_or("@"), "clear variable")?;match (all, key) {(false, None) => {diff --git a/src/commands/context.rs b/src/commands/context.rsindex a85b4bf3a..d99e75ae7 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -1,59 +1,43 @@-use anyhow::Context;use std::path::PathBuf;use worktrunk::config::UserConfig;use worktrunk::git::Repository;use super::command_executor::CommandContext;-/// Shared execution context for command handlers that operate on the current worktree.+/// Shared execution context for command handlers that act on one worktree.///-/// Centralizes the common "repo + branch + config + cwd" setup so individual handlers-/// can focus on their core logic while sharing consistent error messaging.+/// Centralizes the common "repo + branch + config + worktree" setup so individual+/// handlers can focus on their core logic while sharing consistent error messaging.///-/// This helper is used for commands that explicitly act on "where the user is standing"-/// (e.g., `beta` and `merge`) and therefore need all of these pieces together. Commands that-/// inspect multiple worktrees or run without a config/branch requirement (`list`, the picker,-/// some `worktree` helpers) still call `Repository::current()` directly so they can operate in-/// broader contexts without forcing config loads or branch resolution.+/// Used by commands that act on a single worktree — the one named by `--branch`,+/// or `@` without it (`merge`, `step commit`, `step squash`, `hook`). Commands that+/// inspect multiple worktrees or run without a config/branch requirement (`list`, the+/// picker, some `worktree` helpers) still call `Repository::current()` directly so+/// they can operate in broader contexts without forcing config loads or branch+/// resolution.pub struct CommandEnv {pub repo: Repository,- /// Current branch name, if on a branch (None in detached HEAD state).+ /// The selected worktree's branch (None in detached HEAD state).pub branch: Option<String>,pub config: UserConfig,- /// Canonical absolute path to the worktree root (via `git rev-parse --show-toplevel`).+ /// The selected worktree's root.pub worktree_path: PathBuf,}impl CommandEnv {- /// Load the command environment for the current worktree.+ /// Load the command environment for the worktree `selector` names.///- /// Resolves the worktree path from the current directory. The branch is- /// populated when available but not required — commands that need a branch- /// should call `require_branch()` after construction.- pub fn for_action(config: UserConfig) -> anyhow::Result<Self> {- let repo = Repository::current()?;- let current_wt = repo.current_worktree();- let worktree_path = current_wt.root()?;- let branch = current_wt- .branch()- .context("Failed to determine current branch")?;-- Ok(Self {- repo,- branch,- config,- worktree_path,- })- }-- /// Load the command environment for a named worktree.+ /// Commands without a `--branch` pass `"@"`, so "the current worktree" has+ /// one definition, [`Repository::resolve_worktree`]'s: the worktree the+ /// command runs in, or outside every worktree, the one checked out on the+ /// branch HEAD names.///- /// Resolves the worktree from the selector rather than the current- /// directory, and roots `repo` at that worktree — so a command run with- /// `--branch <b>` (e.g. `wt step commit --branch <b>`) and its hooks- /// (`pre-commit` / `post-commit`) operate on, and resolve `.config/wt.toml`- /// from, `<b>`'s worktree rather than the cwd. See the `commands::hooks`- /// module docs for the hook config-resolution rule.+ /// `repo` is rooted at the selected worktree (see+ /// [`Repository::rooted_at`]), so a command run with `--branch <b>`+ /// (e.g. `wt step commit --branch <b>`) and its hooks (`pre-commit` /+ /// `post-commit`) operate on, and resolve `.config/wt.toml` from, `<b>`'s+ /// worktree rather than the cwd. See the `commands::hooks` module docs for+ /// the hook config-resolution rule.////// `branch` carries the resolved branch, not the selector, so a worktree/// named by path expands `{{ branch }}` to the branch checked out there.@@ -62,33 +46,7 @@ impl CommandEnv {let (worktree_path, branch) = repo.require_worktree(selector)?;Ok(Self {- repo: Repository::at(&worktree_path)?,- branch,- config,- worktree_path,- })- }-- /// Load the command environment, taking [`UserConfig`] from the repository's- /// own cached load rather than from the caller.- ///- /// The branch is resolved exactly as [`Self::for_action`] resolves it —- /// `None` in detached HEAD, and required only by a later- /// [`Self::require_branch`] call. The config source is the whole- /// difference: use this where the caller has no `UserConfig` in hand and- /// the repository has already loaded one.- pub fn for_action_loading_config() -> anyhow::Result<Self> {- let repo = Repository::current()?;- let current_wt = repo.current_worktree();- let worktree_path = current_wt.root()?;- // Propagate git errors (broken repo, missing git) but allow None for detached HEAD- let branch = current_wt- .branch()- .context("Failed to determine current branch")?;- let config = repo.user_config().clone();-- Ok(Self {- repo,+ repo: repo.rooted_at(&worktree_path)?,branch,config,worktree_path,diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 588b1c12f..9c4167d68 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -219,9 +219,9 @@ pub fn run_hook(shorthand_vars,forwarded_args,} = cli;- // Derive context from the current environment; `config` isn't in hand here,- // so let the repository supply its cached load.- let env = CommandEnv::for_action_loading_config()?;+ // `config` isn't in hand here, so let the repository supply its cached load.+ let config = Repository::current()?.user_config().clone();+ let env = CommandEnv::for_selector(config, "@")?;let repo = &env.repo;let ctx = env.context(yes);@@ -365,8 +365,15 @@ pub fn handle_hook_show() -> anyhow::Result<()> {use crate::help_pager::show_help_in_pager;- let repo = Repository::current().context("Failed to show hooks")?;- let config: &UserConfig = repo.user_config();+ let config = Repository::current()+ .context("Failed to show hooks")?+ .user_config()+ .clone();+ // Show the hooks `wt hook` would run: the project config of the worktree+ // `@` names.+ let env = CommandEnv::for_selector(config, "@")?;+ let repo = &env.repo;+ let config = &env.config;// Preserve the loader's typed source diagnosis through command context.let project_config: Option<&ProjectConfig> = repo.project_config()?;let approvals = Approvals::load().context("Failed to load approvals")?;@@ -379,16 +386,10 @@ pub fn handle_hook_show(.map(crate::cli::parse_hook_type).transpose()?;- // Build context for template expansion (only used if --expanded).- // Need to keep CommandEnv alive for the lifetime of ctx. Detached HEAD is+ // Context for template expansion, only under --expanded. Detached HEAD is// fine: `{{ branch }}` is unset there, and `--expanded` renders the// guarded form the way any other unset variable renders.- let env = if expanded {- Some(CommandEnv::for_action_loading_config()?)- } else {- None- };- let ctx = env.as_ref().map(|e| e.context(false));+ let ctx = expanded.then(|| env.context(false));if format == crate::cli::SwitchFormat::Json {return emit_hook_show_json(@@ -417,7 +418,7 @@ pub fn handle_hook_show(// Render project hooksrender_project_hooks(&mut output,- &repo,+ repo,project_config,&approvals,project_id.as_ref(),diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 1ddebafa1..b9b322d1c 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -163,13 +163,11 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {}let invoking_repo = Repository::current()?;- let env = match opts.branch {- Some(selector) => CommandEnv::for_selector(config, selector)?,- None => CommandEnv::for_action(config)?,- };+ let env = CommandEnv::for_selector(config, opts.branch.unwrap_or("@"))?;// Compare actual worktree identity, not whether a selector was supplied:// --branch @ and a path naming the current worktree retain normal cleanup.- // A bare invocation has no current worktree and cannot require a cd.+ // Outside every worktree (a bare repo's directory), `@` names HEAD's+ // branch's worktree, which the invoking shell isn't in, so no cd follows.let source_is_current = invoking_repo.current_worktree().root()? == env.worktree_path;let result = merge_in(opts, &env, source_is_current);if source_is_current {diff --git a/src/commands/remove.rs b/src/commands/remove.rsindex 8bf60b30b..f9ef49d2c 100644--- a/src/commands/remove.rs+++ b/src/commands/remove.rs@@ -448,42 +448,59 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>}};- let branches = args.branches;-- if branches.is_empty() {- // Single worktree removal: validate FIRST, then approve, then execute- let current_path = repo- .current_worktree()- .root()- .context("Failed to remove worktree")?;- let result = repo- .prepare_worktree_removal(- RemoveTarget::WorktreePath(current_path.clone()),- BranchDeletionMode::from_flags(!delete_branch, args.force_delete),- args.force,- ¤t_path,- None,- None,- )- .context("Failed to remove worktree")?;-- // Early exit for benchmarking time-to-first-output- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return Ok(());- }+ // No argument means `@`, resolved like any other selector.+ let branches = if args.branches.is_empty() {+ vec!["@".to_string()]+ } else {+ args.branches+ };- // "Approve at the Gate": approval happens AFTER validation passes- let plan = approve_remove(- result.removed_worktree_path().as_slice(),- result.destination_path().as_slice(),- yes,- )?;+ // Validate ALL first, then approve, then execute+ let plans = validate_remove_targets(+ &repo,+ &config,+ branches,+ !delete_branch,+ args.force_delete,+ args.force,+ );++ if !plans.has_valid_plans() {+ anyhow::bail!("");+ }- maybe_reap_result(&result, args.reap);+ // Early exit for benchmarking time-to-first-output+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ return Ok(());+ }- let mut announcer = HookAnnouncer::new(&repo, false);+ // Approve hooks (only if we have valid plans): `pre-remove` /+ // `post-remove` anchored at each removed worktree and+ // `post-switch` at each destination, all selected from the+ // invoking worktree's config — see `approve_remove` above.+ // (`destination_targets` is mostly the primary worktree+ // repeated; the helper dedups destinations by path.)+ let all_plans = || {+ plans+ .others+ .iter()+ .chain(&plans.branch_only)+ .chain(plans.current.iter())+ };+ let removed_targets: Vec<&Path> =+ all_plans().filter_map(|r| r.removed_worktree_path()).collect();+ let destination_targets: Vec<&Path> =+ all_plans().filter_map(|r| r.destination_path()).collect();+ let plan = approve_remove(&removed_targets, &destination_targets, yes)?;++ // Execute all validated plans: others first, branch-only next, current last+ let show_branch =+ plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;+ let run = |result: &RemovalPlan| -> anyhow::Result<BranchFate> {+ maybe_reap_result(result, args.reap);+ let mut announcer = HookAnnouncer::new(&repo, show_branch);let fate = handle_remove_output(- &result,+ result,removal_execution(args.foreground),ForegroundStdin::Inherit,&plan,@@ -491,105 +508,41 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>&mut announcer,)?;announcer.flush()?;- if json_mode {- let json = serde_json::json!([result.to_json(fate)]);- print_json(&json)?;- }- // Fire-and-forget repo-wide internal cleanup (stale trash +- // orphaned fsmonitor daemons) — runs after primary output so- // it never delays the user-visible progress/success message.- super::process::run_internal_sweep(&repo);- Ok(())- } else {- // Multi-worktree removal: validate ALL first, then approve, then execute- let plans = validate_remove_targets(- &repo,- &config,- branches,- !delete_branch,- args.force_delete,- args.force,- );-- if !plans.has_valid_plans() {- anyhow::bail!("");- }-- // Early exit for benchmarking time-to-first-output- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return Ok(());- }-- // Approve hooks (only if we have valid plans): `pre-remove` /- // `post-remove` anchored at each removed worktree and- // `post-switch` at each destination, all selected from the- // invoking worktree's config — see `approve_remove` above.- // (`destination_targets` is mostly the primary worktree- // repeated; the helper dedups destinations by path.)- let all_plans = || {- plans- .others- .iter()- .chain(&plans.branch_only)- .chain(plans.current.iter())- };- let removed_targets: Vec<&Path> =- all_plans().filter_map(|r| r.removed_worktree_path()).collect();- let destination_targets: Vec<&Path> =- all_plans().filter_map(|r| r.destination_path()).collect();- let plan = approve_remove(&removed_targets, &destination_targets, yes)?;-- // Execute all validated plans: others first, branch-only next, current last- let show_branch =- plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;- let run = |result: &RemovalPlan| -> anyhow::Result<BranchFate> {- maybe_reap_result(result, args.reap);- let mut announcer = HookAnnouncer::new(&repo, show_branch);- let fate = handle_remove_output(- result,- removal_execution(args.foreground),- ForegroundStdin::Inherit,- &plan,- false,- &mut announcer,- )?;- announcer.flush()?;- Ok(fate)- };- let mut failed = !plans.errors.is_empty();- let mut json_items = Vec::new();- for result in all_plans() {- match run(result) {- Ok(fate) => {- if json_mode {- json_items.push(result.to_json(fate));- }+ Ok(fate)+ };+ let mut failed = !plans.errors.is_empty();+ let mut json_items = Vec::new();+ for result in all_plans() {+ match run(result) {+ Ok(fate) => {+ if json_mode {+ json_items.push(result.to_json(fate));}- Err(e) => {- if let Some(signal) = e.interrupt_signal() {- return Err(WorktrunkError::Interrupted { signal, hint: None }.into());- }- crate::print_command_error(&e);- failed = true;+ }+ Err(e) => {+ if let Some(signal) = e.interrupt_signal() {+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());}+ crate::print_command_error(&e);+ failed = true;}}+ }- if json_mode {- print_json(&json_items)?;- }-- // Fire-and-forget repo-wide internal cleanup (stale trash +- // orphaned fsmonitor daemons) — runs after primary output so- // it never delays the user-visible progress/success messages.- super::process::run_internal_sweep(&repo);+ if json_mode {+ print_json(&json_items)?;+ }- if failed {- anyhow::bail!("");- }+ // Fire-and-forget repo-wide internal cleanup (stale trash ++ // orphaned fsmonitor daemons) — runs after primary output so+ // it never delays the user-visible progress/success messages.+ super::process::run_internal_sweep(&repo);- Ok(())+ if failed {+ anyhow::bail!("");}++ Ok(())})}diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex 3e1effb4a..62af63075 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -35,7 +35,7 @@ pub fn step_commit(// One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = resolve_env(config, branch.as_deref())?;+ let env = CommandEnv::for_selector(config, branch.as_deref().unwrap_or("@"))?;let ctx = env.context(yes);// CLI flag overrides config value@@ -62,16 +62,6 @@ pub fn step_commit(Ok(Some(outcome))}-/// Resolve the environment `wt step commit` acts in: the worktree named by-/// `--branch`, or the invoking one. `for_selector` re-roots `repo` at that-/// worktree, so the commit, its hooks, and its project config all follow.-fn resolve_env(config: UserConfig, branch: Option<&str>) -> anyhow::Result<CommandEnv> {- match branch {- Some(b) => CommandEnv::for_selector(config, b),- None => CommandEnv::for_action(config),- }-}-/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.////// Both modes skip hooks and the commit itself. `--show-prompt` outputs only the@@ -88,7 +78,8 @@ fn preview_commit(dry_run: bool,yes: bool,) -> anyhow::Result<()> {- let env = resolve_env(UserConfig::load().context("Failed to load config")?, branch)?;+ let config = UserConfig::load().context("Failed to load config")?;+ let env = CommandEnv::for_selector(config, branch.unwrap_or("@"))?;let commit_config = env.resolved().commit_generation.clone();let wt = env.repo.worktree_at(&env.worktree_path);diff --git a/src/commands/step/copy_ignored.rs b/src/commands/step/copy_ignored.rsindex b04f73d41..36f3941af 100644--- a/src/commands/step/copy_ignored.rs+++ b/src/commands/step/copy_ignored.rs@@ -84,10 +84,7 @@ pub fn step_copy_ignored(}};- let dest_path = match to {- Some(selector) => repo.require_worktree(selector)?.0,- None => repo.current_worktree().root()?,- };+ let dest_path = repo.require_worktree(to.unwrap_or("@"))?.0;if source_path == dest_path {if json_mode {diff --git a/src/commands/step/diff.rs b/src/commands/step/diff.rsindex fe8ede1fb..c837e9483 100644--- a/src/commands/step/diff.rs+++ b/src/commands/step/diff.rs@@ -17,19 +17,17 @@ use worktrunk::git::Repository;/// a stale local `main` would count every upstream commit the branch picked up/// as the branch's own.///-/// `branch` selects which worktree to diff: when `Some`, the repo is rooted at-/// that branch's worktree so the diff (and its target resolution) operate there-/// rather than on the current directory. The branch must have a checked-out-/// worktree.+/// `branch` selects which worktree to diff, `@` when `None`; the repo is+/// rooted at that worktree so the diff (and its target resolution) operate+/// there. The branch must have a checked-out worktree.pub fn step_diff(branch: Option<&str>,target: Option<&str>,extra_args: &[String],) -> anyhow::Result<()> {- let repo = match branch {- Some(b) => Repository::at(Repository::current()?.require_worktree(b)?.0)?,- None => Repository::current()?,- };+ let repo = Repository::current()?;+ let (path, _) = repo.require_worktree(branch.unwrap_or("@"))?;+ let repo = repo.rooted_at(&path)?;let wt = repo.current_worktree();let integration_target = repo.require_target_ref(target)?;diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex c1feffba5..afb664c84 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -4,7 +4,7 @@ use anyhow::Context;use color_print::cformat;use worktrunk::HookType;use worktrunk::config::UserConfig;-use worktrunk::git::{Repository, WorkingTree};+use worktrunk::git::WorkingTree;use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, println, progress_message,success_message, suggest_command,@@ -80,7 +80,7 @@ pub fn handle_squash(// One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = CommandEnv::for_action(config)?;+ let env = CommandEnv::for_selector(config, "@")?;handle_squash_in(&env,target,@@ -506,10 +506,9 @@ fn preview_squash(dry_run: bool,yes: bool,) -> anyhow::Result<()> {- let repo = Repository::current()?;- let config = UserConfig::load().context("Failed to load config")?;- let project_id = repo.project_identifier().ok();- let commit_config = config.commit_generation(project_id.as_ref());+ let env = CommandEnv::for_selector(UserConfig::load().context("Failed to load config")?, "@")?;+ let repo = &env.repo;+ let commit_config = env.config.commit_generation(env.project_id().as_ref());let integration_target = repo.require_target_ref(target)?;// #3519: preview against the same upstream-aware span the real squash uses.@@ -537,7 +536,6 @@ fn preview_squash(.and_then(|n| n.to_str()).unwrap_or("repo");- let env = CommandEnv::for_action(config)?;let ctx = env.context(yes);let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;diff --git a/src/git/error.rs b/src/git/error.rsindex 18bd939bc..270599329 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -512,10 +512,6 @@ pub enum GitError {// Worktree errorsInteractivePickerRequiresTerminal,- NotInWorktree {- /// The action that requires being in a worktree- action: Option<String>,- },/// A registered worktree git calls prunable, or whose directory is gone./// Built with [`GitError::worktree_missing`].WorktreeMissing {@@ -873,10 +869,6 @@ impl GitError {GitError::InteractivePickerRequiresTerminal => {"Interactive picker requires an interactive terminal".to_string()}- GitError::NotInWorktree { action } => match action {- Some(action) => format!("Cannot {action}: not in a worktree"),- None => "Not in a worktree".to_string(),- },GitError::WorktreeMissing { branch, .. } => {cformat!("Worktree for <bold>{branch}</> is stale; its directory or .git is gone")@@ -1240,17 +1232,6 @@ impl GitError {)))}- GitError::NotInWorktree { .. } => {- let title = self.title();- write!(- f,- "{}\n{}",- error_message(&title),- hint_message(cformat!(- "Run from inside a worktree, or specify a branch name"- ))- )- }GitError::WorktreeMissing { repairable_at, .. } => {let title = self.title();@@ -2672,23 +2653,6 @@ mod tests {");}- #[test]- fn snapshot_not_in_worktree() {- let err = GitError::NotInWorktree {- action: Some("resolve @".into()),- };- assert_snapshot!(err.render(), @"- [31m✗[39m [31mCannot resolve @: not in a worktree[39m- [2m↳[22m [2mRun from inside a worktree, or specify a branch name[22m- ");-- let err = GitError::NotInWorktree { action: None };- assert_snapshot!(err.render(), @"- [31m✗[39m [31mNot in a worktree[39m- [2m↳[22m [2mRun from inside a worktree, or specify a branch name[22m- ");- }-#[test]fn snapshot_worktree_path_occupied() {let err = GitError::WorktreePathOccupied {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 860bc8457..24a439fd9 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1491,19 +1491,6 @@ impl Repository {}}- /// Get the current branch name, or error if in detached HEAD state.- ///- /// `action` describes what requires being on a branch (e.g., "merge").- pub fn require_current_branch(&self, action: &str) -> anyhow::Result<String> {- self.current_worktree().branch()?.ok_or_else(|| {- GitError::DetachedHead {- action: Some(action.into()),- worktree: None,- }- .into()- })- }-// =========================================================================// Core repository properties// =========================================================================diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex 4f42b4b9f..0efc6ec44 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -477,7 +477,8 @@ impl Repository {/// or one of several checkouts of the same branch.////// Resolution order:- /// 1. `@` — the current worktree, matched by path so detached HEAD resolves+ /// 1. `@` — the current worktree, matched by path so detached HEAD+ /// resolves; outside any worktree, the branch HEAD names, as below/// 2. `-` — the worktree `wt switch` last left, by the path it recorded/// (see [`switch_previous_worktree`](Self::switch_previous_worktree))/// 3. `-` / `^` — the previous / default branch, then as a branch below@@ -506,23 +507,30 @@ impl Repository {// `expand_selector` would apply has nothing to return.let name = normalize_selector(name);if name == "@" {- // If worktree_root fails (e.g., in bare repo directory), give a clear error- let path = self- .current_worktree()- .root()- .map_err(|_| GitError::NotInWorktree {- action: Some("resolve @".into()),- })?;- // Compare canonical identities so alternate path spellings (for- // example macOS `/var` and `/private/var`) select one inventory- // entry without changing Git's registered path.+ // `root()` falls back to the cwd itself outside a work tree, so+ // only a registered worktree at that path counts. Compare+ // canonical identities so alternate path spellings (for example+ // macOS `/var` and `/private/var`) select one inventory entry+ // without changing Git's registered path.+ let current = self.current_worktree();+ let path = current.root()?;let current_id = WorktreeId::new(&path);- let branch = self+ if let Some(wt) = self.list_worktrees()?.iter().find(|wt| wt.id() == current_id)- .and_then(|wt| wt.branch.clone());- return Ok(ResolvedWorktree::worktree(path, branch));+ {+ return Ok(ResolvedWorktree::worktree(path, wt.branch.clone()));+ }+ // Inside a work tree git no longer has registered at this path (a+ // worktree moved without `git worktree repair`), `@` still means+ // this directory, which holds no worktree wt can act on.+ if current.prewarm_info()?.is_inside {+ return Ok(ResolvedWorktree::NoWorktreeAtPath { path });+ }+ // Outside every work tree — a bare repo's directory, or a `.git`+ // directory — `@` falls through to the branch HEAD names, as+ // `expand_selector` reads it.}if name == "-"&& let Some((path, branch)) = self.switch_previous_worktree()?@@ -574,9 +582,9 @@ impl Repository {////// [`resolve_worktree`](Self::resolve_worktree) for the arguments that want/// a branch rather than a worktree — the `--branch` of the `wt config- /// state` commands, which key state by branch name. A branch with no- /// worktree is a fine answer to those; a worktree named by path that has no- /// branch is not.+ /// state` commands, which key state by branch name, defaulting to `@`. A+ /// branch with no worktree is a fine answer to those; a worktree named by+ /// path that has no branch is not.pub fn require_selected_branch(&self, name: &str, action: &str) -> anyhow::Result<String> {match self.resolve_worktree(name)? {ResolvedWorktree::Worktree {@@ -589,6 +597,15 @@ impl Repository {ResolvedWorktree::NoWorktreeAtPath { path } => {Err(GitError::WorktreeNotFoundAtPath { path }.into())}+ // Name the detached worktree only when it isn't the one the+ // command runs in, as `GitError::DetachedHead` asks.+ ResolvedWorktree::Worktree {+ path, branch: None, ..+ } if self.is_current_worktree(&path)? => Err(GitError::DetachedHead {+ action: Some(action.to_string()),+ worktree: None,+ }+ .into()),ResolvedWorktree::Worktree {path, branch: None, ..} => Err(GitError::DetachedHead {@@ -602,6 +619,25 @@ impl Repository {}}+ /// Whether `path` is the worktree this repository was discovered in.+ fn is_current_worktree(&self, path: &Path) -> anyhow::Result<bool> {+ Ok(WorktreeId::new(self.current_worktree().root()?) == WorktreeId::new(path))+ }++ /// This repository, rooted at the worktree at `path`.+ ///+ /// Keeps `self`, discovered from the cwd and with the caches it has+ /// already filled, when `path` is the worktree it was discovered in, so a+ /// command acting on `@` there runs exactly as it would from the cwd.+ /// Otherwise discovers the repository at `path`.+ pub fn rooted_at(self, path: &Path) -> anyhow::Result<Self> {+ if self.is_current_worktree(path)? {+ Ok(self)+ } else {+ Self::at(path)+ }+ }+/// The worktree a selector names — its path, and its branch (`None` when/// detached) — erroring when it names none.///diff --git a/src/main.rs b/src/main.rsindex 30acbe106..3c8763606 100644--- a/src/main.rs+++ b/src/main.rs@@ -313,7 +313,7 @@ fn handle_step_command(} => {let repo = Repository::current()?;let result = if no_ff {- let current_branch = repo.require_current_branch("step push --no-ff")?;+ let current_branch = repo.require_selected_branch("@", "step push --no-ff")?;handle_no_ff_merge(&repo, target.as_deref(), None, ¤t_branch)?} else {handle_push(&repo, target.as_deref(), PushKind::Standalone, None)?diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex 3c557330d..e26579721 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -722,6 +722,133 @@ fn test_bare_repo_commands_from_bare_directory() {});}+/// The bare repository's own directory is no worktree, so `@` there names the+/// branch HEAD points at. `wt switch @` lands in that branch's worktree, and+/// `wt step copy-ignored`, whose destination defaults to `@`, copies nothing+/// into the bare repository.+#[test]+fn test_bare_repo_at_from_bare_directory_names_head_branch() {+ let test = BareRepoTest::new();+ let main_worktree = test.create_worktree("main", "main");+ test.commit_in(&main_worktree, "Initial commit");+ fs::write(main_worktree.join(".gitignore"), "secret\n").unwrap();+ fs::write(main_worktree.join("secret"), "s\n").unwrap();++ let output = test+ .wt_command()+ .args(["switch", "@", "--no-cd", "--yes", "--format=json"])+ .current_dir(test.bare_repo_path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["branch"], "main");+ assert_eq!(Path::new(json["path"].as_str().unwrap()), main_worktree);++ let output = test+ .wt_command()+ .args(["step", "copy-ignored"])+ .current_dir(test.bare_repo_path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(!test.bare_repo_path().join("secret").exists());+}++/// From a bare repo's directory, `wt remove` with no argument means `@`, the+/// worktree of the branch HEAD names. With HEAD on the default branch, both+/// spellings refuse the same way, and that worktree stays.+#[test]+fn test_bare_repo_remove_from_bare_directory_targets_head_branch() {+ let test = BareRepoTest::new();+ let main_worktree = test.create_worktree("main", "main");+ test.commit_in(&main_worktree, "Initial commit");+ test.create_worktree("feature", "feature");++ let remove = |args: &[&str]| {+ test.wt_command()+ .arg("remove")+ .args(args)+ .args(["--yes", "--foreground"])+ .current_dir(test.bare_repo_path())+ .output()+ .unwrap()+ };+ let no_arg = remove(&[]);+ let at = remove(&["@"]);++ assert!(!no_arg.status.success());+ assert_eq!(no_arg.status.code(), at.status.code());+ assert_eq!(no_arg.stderr, at.stderr);+ assert!(main_worktree.exists());+ insta::assert_snapshot!(String::from_utf8_lossy(&no_arg.stderr), @"+ ✗ Cannot remove the default branch main+ ↳ To force-delete, run wt remove -D main+ ");+}++/// From a bare repo's directory, commands without a selector act on the+/// worktree of the branch HEAD names, here `feature` rather than the primary+/// `main`: `wt hook show` lists that worktree's project hooks, and `wt step+/// squash --show-prompt` previews that worktree's changes.+#[test]+fn test_bare_repo_previews_from_bare_directory_use_head_branch() {+ let test = BareRepoTest::new();+ let main_worktree = test.create_worktree("main", "main");+ test.commit_in(&main_worktree, "Initial commit");+ let feature_worktree = test.create_worktree("feature", "feature");+ test.commit_in(&feature_worktree, "feature-line");+ test.run_git_in(+ test.bare_repo_path(),+ &["symbolic-ref", "HEAD", "refs/heads/feature"],+ );+ test.run_git_in(+ test.bare_repo_path(),+ &["config", "worktrunk.default-branch", "main"],+ );+ for (worktree, hook) in [+ (&main_worktree, "main-hook"),+ (&feature_worktree, "feature-hook"),+ ] {+ fs::create_dir_all(worktree.join(".config")).unwrap();+ fs::write(+ worktree.join(".config/wt.toml"),+ format!("pre-commit = \"echo {hook}\"\n"),+ )+ .unwrap();+ }++ let run = |args: &[&str]| {+ let output = test+ .wt_command()+ .args(args)+ .current_dir(test.bare_repo_path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8(output.stdout).unwrap()+ };++ let hooks = run(&["hook", "show", "--format=json"]);+ assert!(hooks.contains("feature-hook"), "{hooks}");+ assert!(!hooks.contains("main-hook"), "{hooks}");++ let prompt = run(&["step", "squash", "main", "--show-prompt"]);+ assert!(prompt.contains("+feature-line"), "{prompt}");+}+/// Full merge workflow in a bare repo: create main + feature worktrees, merge/// feature into main, and confirm the merge landed.///diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 9414ff0fa..b9d3dd8aa 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -2577,6 +2577,24 @@ fn test_vars_set_and_get(repo: TestRepo) {assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "staging");}+/// Without `--branch`, state commands act on `@`. In a detached worktree that+/// refuses without naming the worktree, since it's the one the user is in.+#[rstest]+fn test_vars_set_in_detached_worktree(mut repo: TestRepo) {+ let worktree = repo.add_worktree("feature");+ repo.detach_head_in_worktree("feature");++ let output = wt_state_cmd(&repo, "vars", "set", &["env=staging"])+ .current_dir(&worktree)+ .output()+ .unwrap();+ assert!(!output.status.success());+ assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"+ [31m✗[39m [31mCannot set variable: not on a branch (detached HEAD)[39m+ [2m↳[22m [2mTo switch to a branch, run [4mgit switch <branch>[24m[22m+ ");+}+#[rstest]fn test_vars_set_json_value(repo: TestRepo) {let json = r#"{"port":3000,"debug":true}"#;diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 67fbc652f..25eff6d66 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -6244,3 +6244,58 @@ approved-commands = [{hook:?}]assert!(!parent.join("PWNED").exists());let _ = fs::remove_file(staged_path);}++/// WORKTRUNK_FIRST_OUTPUT exits after validation, before approval and removal.+/// Used by time-to-first-output benchmarks.+#[rstest]+fn test_remove_first_output_exits_cleanly(mut repo: TestRepo) {+ let worktree = repo.add_worktree("feature-bench");++ let output = repo+ .wt_command()+ .args(["remove", "--yes"])+ .current_dir(&worktree)+ .env("WORKTRUNK_FIRST_OUTPUT", "1")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "WORKTRUNK_FIRST_OUTPUT should exit 0: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(output.stderr.is_empty());+ assert!(worktree.exists());+}++/// `wt remove` with no argument, run from a worktree moved without+/// `git worktree repair`, refuses: `@` names the directory the user stands+/// in, not the branch's registration at its old path, which removing would+/// prune and leave this checkout with a dangling `.git` file.+#[rstest]+fn test_remove_no_argument_in_moved_worktree_refuses(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature");+ let moved = worktree_path.with_file_name("moved-feature");+ fs::rename(&worktree_path, &moved).unwrap();++ let mut cmd = repo.wt_command();+ cmd.args(["remove", "--foreground", "--yes"])+ .current_dir(&moved);+ let output = cmd.output().unwrap();+ assert!(+ !output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );++ let status = std::process::Command::new("git")+ .args(["status", "--porcelain"])+ .current_dir(&moved)+ .output()+ .unwrap();+ assert!(+ status.status.success(),+ "{}",+ String::from_utf8_lossy(&status.stderr)+ );+}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 5ed8cd860..51e837521 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -8617,6 +8617,15 @@ fn test_switch_at_names_the_current_worktree(mut repo: TestRepo, #[case] detacheassert_eq!(path.file_name(), current.file_name());}+/// Outside every worktree, here the main worktree's `.git` directory, `@`+/// names the branch HEAD points at: the switch lands in the main worktree+/// rather than treating the `.git` directory as a detached worktree.+#[rstest]+fn test_switch_at_outside_a_worktree_names_the_head_branch(repo: TestRepo) {+ let path = switch_json_path(&repo, &repo.root_path().join(".git"), &["@"]);+ assert_eq!(path, repo.root_path());+}+/// Run `wt switch <args>` from `dir` with `--format=json` and return the/// path it lands in.fn switch_json_path(repo: &TestRepo, dir: &std::path::Path, args: &[&str]) -> std::path::PathBuf {