Skip to content

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

fix(hook): inject `target` symmetrically on switch/create/start (#2295)

Maximilian Roos1fd6eaba2092
diff --git a/docs/content/hook.md b/docs/content/hook.md
index fc5c1f004..1ac0a18ce 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -143,12 +143,13 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope
| Operation | Bare vars | `base` | `target` |
|-----------|-----------|--------|----------|
| switch/create | destination | where you came from | = bare vars |
+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target |
| merge | feature being merged | = bare vars | merge target |
| remove | branch being removed | = bare vars | where you end up |
Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same — the active worktree is gone, so the hook runs in target.
-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:
+Some variables are conditional: `upstream` requires remote tracking; `base` only appears in switch/create hooks; `target_worktree_path` requires the target to have a worktree; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:
```toml
[pre-start]
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index 677168989..fb92e6087 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -134,12 +134,13 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope
| Operation | Bare vars | `base` | `target` |
|-----------|-----------|--------|----------|
| switch/create | destination | where you came from | = bare vars |
+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target |
| merge | feature being merged | = bare vars | merge target |
| remove | branch being removed | = bare vars | where you end up |
Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same — the active worktree is gone, so the hook runs in target.
-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:
+Some variables are conditional: `upstream` requires remote tracking; `base` only appears in switch/create hooks; `target_worktree_path` requires the target to have a worktree; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:
```toml
[pre-start]
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 00c93cb10..6202bfd8c 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1280,12 +1280,13 @@ Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the ope
| Operation | Bare vars | `base` | `target` |
|-----------|-----------|--------|----------|
| switch/create | destination | where you came from | = bare vars |
+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target |
| merge | feature being merged | = bare vars | merge target |
| remove | branch being removed | = bare vars | where you end up |
Pre and post hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`. `cwd` is the worktree root where the hook command runs. It differs from `worktree_path` in three cases: pre-switch, where the hook runs in the source but `worktree_path` is the destination; post-remove, where the active worktree is gone so the hook runs in primary; and post-merge with removal, same — the active worktree is gone, so the hook runs in target.
-Some variables are conditional: `upstream` requires remote tracking; `base`/`target` are only in two-worktree hooks; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:
+Some variables are conditional: `upstream` requires remote tracking; `base` only appears in switch/create hooks; `target_worktree_path` requires the target to have a worktree; `vars` keys may not exist. Undefined variables error — use conditionals or defaults for optional behavior:
```toml
[pre-start]
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index ed37f6645..1f4718be4 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -414,7 +414,15 @@ pub fn handle_switch(
// Build extra vars for base/target context (used by both hooks and --execute).
// "base" is the source worktree the user switched from (all switches),
// or the branch they branched from (creates).
+ // "target" matches the bare vars (the destination) — documented as
+ // "target = bare vars" for switch/create and kept symmetric with pre-switch.
+ let target_path_str = worktrunk::path::to_posix_path(&result.path().to_string_lossy());
+
let mut extra_vars = switch_extra_vars(&result);
+ if let Some(target_branch) = branch_info.branch.as_deref() {
+ extra_vars.push(("target", target_branch));
+ }
+ extra_vars.push(("target_worktree_path", &target_path_str));
// For existing switches, add source worktree as base
if matches!(
result,
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 8f3cef168..8306dedaa 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -908,6 +908,8 @@ pub fn execute_switch(
// Execute post-create commands
if run_hooks {
let ctx = CommandContext::new(repo, config, Some(&branch), &worktree_path, force);
+ let target_wt_posix =
+ worktrunk::path::to_posix_path(&worktree_path.to_string_lossy());
match &method {
CreationMethod::Regular { base_branch, .. } => {
@@ -916,6 +918,8 @@ pub fn execute_switch(
base_worktree_path
.as_ref()
.map(|p| ("base_worktree_path", p.as_str())),
+ Some(("target", branch.as_str())),
+ Some(("target_worktree_path", target_wt_posix.as_str())),
]
.into_iter()
.flatten()
@@ -933,8 +937,12 @@ pub fn execute_switch(
RefType::Pr => ("pr_number", "pr_url"),
RefType::Mr => ("mr_number", "mr_url"),
};
- let extra_vars: Vec<(&str, &str)> =
- vec![(num_key, &num_str), (url_key, ref_url)];
+ let extra_vars: Vec<(&str, &str)> = vec![
+ (num_key, &num_str),
+ (url_key, ref_url),
+ ("target", &branch),
+ ("target_worktree_path", &target_wt_posix),
+ ];
ctx.execute_pre_start_commands(&extra_vars)?;
}
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 93c0d1f1d..cf4548a7d 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -96,16 +96,21 @@ fn hook_extras(hook_type: HookType) -> &'static [&'static str] {
use HookType::*;
match hook_type {
// Switch: source branch (`base`) and destination (`target`).
- // Post-switch has already switched, so only `base` is set — but we
- // accept both here so user templates stay portable between pre/post.
PreSwitch | PostSwitch => &[
"base",
"base_worktree_path",
"target",
"target_worktree_path",
],
- // Create/start: source worktree the new branch was created from.
- PreStart | PostStart => &["base", "base_worktree_path"],
+ // Create/start: source worktree (`base`) and newly-created destination
+ // (`target`). On create, the destination branch equals the bare `branch`
+ // var — `target` is accepted for template portability with switch hooks.
+ PreStart | PostStart => &[
+ "base",
+ "base_worktree_path",
+ "target",
+ "target_worktree_path",
+ ],
// Commit: integration target for the pre-commit squash.
PreCommit | PostCommit => &["target"],
// Merge: where the feature is being merged into.
@@ -1677,10 +1682,10 @@ mod tests {
err.message
);
- // `target` is unavailable in pre-start — catch the typo at validation time.
+ // `base` is unavailable in pre-merge — catch the typo at validation time.
let err = validate_template(
- "{{ target }}",
- ValidationScope::Hook(HookType::PreStart),
+ "{{ base }}",
+ ValidationScope::Hook(HookType::PreMerge),
&test.repo,
"test",
)
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 53dee587f..870535992 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -1312,6 +1312,75 @@ approved-commands = [
);
}
+#[rstest]
+fn test_post_start_target_variable_expands_to_branch(repo: TestRepo) {
+ // `{{ target }}` in post-start should equal the bare `{{ branch }}` —
+ // symmetric with `pre-switch`, which already injects `target`.
+ repo.write_project_config(r#"post-start = "echo '{{ target }}' > target_marker.txt""#);
+ repo.commit("Add post-start with target var");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = ["echo '{{ target }}' > target_marker.txt"]
+"#,
+ );
+
+ snapshot_switch(
+ "post_start_target_variable",
+ &repo,
+ &["--create", "feature"],
+ );
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let marker = worktree_path.join("target_marker.txt");
+ wait_for_file_content(&marker);
+
+ let content = fs::read_to_string(&marker).unwrap();
+ assert_eq!(
+ content.trim(),
+ "feature",
+ "target should resolve to the newly created branch, got: {content}"
+ );
+}
+
+#[rstest]
+fn test_post_switch_target_variable_on_existing_switch(repo: TestRepo) {
+ // `{{ target }}` in post-switch must equal the destination branch for
+ // switches to an existing worktree — not just creates.
+ repo.write_project_config(r#"post-switch = "echo '{{ target }}' > target_marker.txt""#);
+ repo.commit("Add post-switch with target var");
+
+ repo.write_test_approvals(
+ r#"[projects."../origin"]
+approved-commands = ["echo '{{ target }}' > target_marker.txt"]
+"#,
+ );
+
+ // Create the destination worktree first, then switch back to main so the
+ // next invocation exercises the existing-worktree switch path (not create).
+ repo.wt_command()
+ .args(["switch", "--create", "feature", "--no-hooks", "--yes"])
+ .output()
+ .expect("failed to pre-create feature worktree");
+ repo.wt_command()
+ .args(["switch", "main", "--no-hooks", "--yes"])
+ .output()
+ .expect("failed to switch back to main");
+
+ snapshot_switch("post_switch_target_variable_existing", &repo, &["feature"]);
+
+ let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
+ let marker = worktree_path.join("target_marker.txt");
+ wait_for_file_content(&marker);
+
+ let content = fs::read_to_string(&marker).unwrap();
+ assert_eq!(
+ content.trim(),
+ "feature",
+ "target should resolve to the switched-to branch, got: {content}"
+ );
+}
+
#[rstest]
fn test_post_start_mixed_user_pipeline_project_flat(repo: TestRepo) {
// User has a pipeline, project has flat concurrent commands.
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap
index a5a70a064..f95506d2a 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_upstream_template.snap
@@ -50,4 +50,4 @@ exit_code: 1
↳ To see details, run wt config show; to apply updates, run wt config update
✗ Failed to expand project pre-start hook: undefined value @ line 1
  echo 'Upstream: {{ upstream }}' > upstream.txt
-↳ Available variables: base, base_worktree_path, branch, commit, cwd, default_branch, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path
+↳ Available variables: base, base_worktree_path, branch, commit, cwd, default_branch, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, target, target_worktree_path, worktree, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_target_variable.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_target_variable.snap
new file mode 100644
index 000000000..e6a730670
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_target_variable.snap
@@ -0,0 +1,52 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature from main and worktree @ _REPO_.feature
+↳ To customize worktree locations, run wt config create
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-start: project @ _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_switch_target_variable_existing.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_switch_target_variable_existing.snap
new file mode 100644
index 000000000..deb73b32d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_switch_target_variable_existing.snap
@@ -0,0 +1,49 @@
+---
+source: tests/integration_tests/post_start_commands.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Worktree for feature @ _REPO_.feature, but cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
+◎ Running post-switch: project @ _REPO_.feature