Skip to content

fix(alias): carry the shell's cwd into alias and hook bodies - #3724

Merged
max-sixty merged 4 commits into
mainfrom
alias-subdir-preservation
Aug 5, 2026
Merged

max-sixty merged 4 commits into
mainfrom
alias-subdir-preservation

Conversation

@worktrunk-bot

@worktrunk-bot worktrunk-bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Since #939 / #3344, wt switch and wt remove preserve the user's subdirectory position — from monorepo.feature/subproject/ you land in monorepo/subproject/. #3723 reports that this is lost one layer down: with [aliases] finish = "wt remove -y", wt finish drops you at the primary worktree root.

The resolution reads the user's position from the wt process's own cwd (resolve_subdir_in_target, called with std::env::current_dir()). That answers "where is the user standing?" only for a top-level invocation. Alias and hook bodies run with the worktree root as their working directory, so the nested wt strips the source root off a cwd that is the source root, gets an empty relative path, and falls back to the destination root.

Solution

The CD directive file already travels to exactly the children that are allowed to move the user's shell. The shell's directory now travels with it: apply_cd_directive_env sets WORKTRUNK_SHELL_CWD wherever the CD file is re-added (Cmd::stream and the concurrent runner), and scrub_directive_env_vars strips it alongside the other directive vars, so an untrusted child neither keeps nor receives it.

shell_exec::shell_cwd() reads it back, preferring the inherited value over the process cwd — which is what makes nesting compose, since each layer forwards the shell's directory rather than its own. Three sites ask that question and now go through it: wt switch, wt remove (prepare_remove_directory_change), and wt step relocate, whose existing comment already asks to behave identically to the other two.

Nothing about the working directory of alias or hook bodies changes — {{ cwd }} is still the worktree root, per the documented contract. The only change is what a nested wt believes about the user's position.

Testing

Two integration tests in tests/integration_tests/step_alias.rs, both failing before the change with the exact symptom reported:

CD file should preserve the subdirectory (…/repo/apps/gateway), got: "…/repo\n"
  • test_alias_wrapping_remove_preserves_subdir — the reported case ([aliases] finish = "wt remove -y" run from feature/apps/gateway).
  • test_alias_wrapping_switch_preserves_subdir — the same for wt switch inside an alias.

The existing subdirectory-preservation tests in directives.rs (including the fall-back-to-root cases) still pass, as does the full integration suite — apart from test_copy_ignored_preserves_file_executable_permissions, which fails identically on main in this sandbox (umask 0002, expects 0644 gets 0664) and is unrelated.

The open question from the first revision is answered: the new remove test leaves two processes with a cwd inside the worktree being removed (the alias parent in the subdirectory, the nested wt at the root) where the existing test has one, and test (windows) passes on it.

Review follow-ups are in 31d8b3d (pure shell_cwd_from plus its unit test, SHELL_CWD_ENV_VAR added to the scrub-coverage test, corrected startup_cwd() comment) and 2578348 (the fixtures in that unit test derive from temp_dir() instead of a cfg!(windows) literal pair, whose untaken arm was the last codecov/patch miss). One code-coverage run failed on progressive_handler::tests::on_update_pokes_run_preview_only_when_the_visible_pane_changes — unrelated to this change, passing in test (linux) on the same commit and in the coverage run on the parent commit — and passed on re-run.

Closes #3723

Subdirectory preservation resolves the user's position from the wt
process's own cwd, which only answers "where is the user standing?" for a
top-level invocation. Alias and hook bodies run with the worktree root as
their working directory, so a nested `wt switch` / `wt remove` resolved
the user to that root and dropped them there.

Pass the shell's directory to every child that already receives the CD
directive file — the same children that are allowed to move the shell —
and read it back through `shell_cwd()` at the three sites that ask where
the user is (switch, remove, step relocate). Nesting composes, since each
layer forwards the inherited value rather than its own cwd.

Closes #3723

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism holds up: resolve_subdir_in_target is reached from exactly three change_directory sites (handle_switch_output, prepare_remove_directory_change, RelocationExecutor::move_worktree) and all three now source their cwd from shell_cwd(), so nothing is left resolving the user's position from the process cwd. Every mismatch case I traced degrades to the existing root fallback rather than to a wrong directory — the inherited value can't strip_prefix a source root it isn't under, and is_dir() still gates the candidate.

Three things worth acting on, inline.

The one that blocks merge is codecov/patch (94.11%, 16/17). The single miss is the fall-through at shell_exec.rs when WORKTRUNK_SHELL_CWD is set but relative — and nothing can currently reach it: no wt ever writes a relative value, and an in-process test can't set it (std::env::set_var is banned by tests/CLAUDE.md). The inline suggestion extracts the pure form so a unit test can drive the branch directly, following the precedent two hundred lines up in the same file — compute_git_env_overrides is factored out of inherited_git_env_overrides for exactly this reason. The matching test:

#[test]
fn test_shell_cwd_from_prefers_absolute_inherited_value() {
    let fallback = PathBuf::from(if cfg!(windows) { r"C:\fallback" } else { "/fallback" });
    let absolute = if cfg!(windows) { r"C:\shell\cwd" } else { "/shell/cwd" };

    // An absolute inherited value wins over the process cwd.
    assert_eq!(
        shell_cwd_from(Some(OsString::from(absolute)), Some(&fallback)),
        Some(PathBuf::from(absolute))
    );
    // A relative one names nothing from a child that runs elsewhere.
    assert_eq!(
        shell_cwd_from(Some(OsString::from("apps/gateway")), Some(&fallback)),
        Some(fallback.clone())
    );
    assert_eq!(shell_cwd_from(None, Some(&fallback)), Some(fallback.clone()));
    assert_eq!(shell_cwd_from(Some(OsString::from("apps/gateway")), None), None);
}

The integration-test alternative — spawning wt switch with WORKTRUNK_SHELL_CWD="." and a process cwd of repo/apps/gateway, asserting the CD file still names feature/apps/gateway — also covers the line, but at a much more expensive boundary for a two-branch predicate.

Smaller: wt_alias_config is the fifth copy of the escape-the-binary-path-into-TOML dance in step_alias.rs (the others sit under test_alias_passes_cd_directive_through, exec-passthrough, exec-blocked, and the user/project shared pair). Now that a helper exists, folding the single-alias sites into it would stop a sixth from appearing.

test (windows) is still running, so the two-processes-inside-the-removed-worktree question the description raises is unanswered as of this review.

Comment thread src/shell_exec.rs Resolved
Comment thread src/shell_exec.rs Resolved
Comment thread src/commands/worktree/switch.rs Resolved
Addresses review feedback on #3724:

- Split the pure `shell_cwd_from` out of `shell_cwd`, mirroring the
  `compute_git_env_overrides` / `inherited_git_env_overrides` split in the
  same file, so the relative-value fall-through is reachable from a unit
  test without mutating process-wide state. That line was the sole
  `codecov/patch` miss.
- Extend the directive-scrub test to enumerate `SHELL_CWD_ENV_VAR` in both
  arrays, and broaden its name now that it covers more than the retired
  variable.
- Correct the `shell_cwd()` comment in switch.rs: `startup_cwd()` reads as
  absent only when the CWD was already gone at process start, not when a
  hook deletes it mid-run.
- Fold the four remaining copies of the escape-the-binary-path-into-TOML
  dance in step_alias.rs into `wt_alias_config`.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Both review-body points, alongside the three inline ones (all applied in 31d8b3d):

wt_alias_config duplication. Folded — the four remaining copies of the escape-the-binary-path-into-TOML dance (test_alias_passes_cd_directive_through, exec-passthrough, exec-blocked, and both halves of the user/project shared pair) now call the helper, so wt_str.replace('\\', r"\\") appears once in the file instead of five times. The helper's doc said "user-config alias"; it now says either source, since exec-blocked and the project half of shared pass it to write_project_config.

The two-processes-in-the-removed-worktree question. Answered: test (windows) passed on the parent commit in 10m53s, so the new remove test doesn't need narrowing. Windows is re-running against this push.

Locally cargo test --test integration step_alias is 81/81 and cargo clippy --all-targets --all-features is clean. Watching codecov/patch on the new head — the single miss it flagged was shell_exec.rs's relative-value fall-through, which the new unit test drives directly.

The `cfg!(windows)` literal pair left whichever arm the coverage run
didn't take as an uncovered patch line — the last two `codecov/patch`
misses. `temp_dir()` is absolute on every platform, so the same two
paths work without a platform branch (`/shell/cwd` isn't absolute on
Windows, which is why the literals were split in the first place).

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

codecov/patch is green on this head, so the blocker from my review on 42b57b5 is closed, and test (linux|macos|windows) all pass here — which also answers the two-processes-in-the-removed-worktree question on this head rather than only on the parent.

Deriving both fixtures from temp_dir() is the right shape for the last two misses: neither path is touched, so the predicate only ever sees the is_absolute() distinction it actually branches on, and the added assert!(absolute.is_absolute(), …) keeps a relative TMPDIR from quietly turning the first assertion into a second copy of the fall-through case. No further findings.

Recording this as a comment rather than an approval only because GitHub rejects self-approval.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

All checks green on 2578348, codecov/patch included.

One note for the run history: code-coverage went red on its first attempt and passed on attempt 2 of the same commit, on picker::progressive_handler's on_update_pokes_run_preview_only_when_the_visible_pane_changes — unrelated to this PR, which touches nothing under src/commands/picker/. test (linux) runs the same unit test and passed on that SHA in the same cycle. Filed as #3725 rather than folded in here; it didn't reproduce in 700 local iterations, so the issue records the evidence and the leading hypothesis rather than a fix.

Comment thread src/shell_exec.rs Resolved
Comment thread docs/content/config.md Resolved
@max-sixty
max-sixty merged commit d4538f2 into main Aug 5, 2026
42 checks passed
@max-sixty
max-sixty deleted the alias-subdir-preservation branch August 5, 2026 16:29
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.72.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre>## Release Notes

### Improved

- **A host carrying a forge's name anywhere resolves to that forge again**: 0.71.0 required `github`, `gitlab`, or `gitea` as a whole dot-separated label, which read as an ownership check but wasn't one — an attacker controls their own DNS — while shutting out self-hosters with hyphenated names. `github-enterprise.acme.com`, `mygithub.com`, and the `github-personal` SSH alias classify again, so CI status, `wt switch --prs`, and `repo.provider` work with no config. ([#3673](max-sixty/worktrunk#3673))

- **One `[projects."…"]` entry can cover every repository on a host, and can set the forge**: A key containing `*` matches any run of characters, `/` included, so `[projects."git.company.example/*"]` covers a whole host; every matching entry applies, least- to most-specific. The table also gained `forge.platform` and `forge.hostname`, so a self-hosted host needs one entry here rather than a block in every repo. [Docs](https://worktrunk.dev/config/#user-project-specific-settings) ([#3701](max-sixty/worktrunk#3701), thanks @chrishas35 for the request and @witt-bit for the workspace-scoped case it partly serves)

- **`wt merge` and `wt step push` leave the target worktree's uncommitted changes in place**: The autostash that held a dirty target's changes restored them as unstaged; both now advance the target with a compare-and-swap `update-ref` and `read-tree -m -u`, which leaves uncommitted work untouched. (Breaking: the fast-forward path no longer runs `git push`, so `pre-push` and the receive-side hooks no longer fire, and a failed sync errors with the ref rolled back.) ([#3703](max-sixty/worktrunk#3703), [#3684](max-sixty/worktrunk#3684), [#3693](max-sixty/worktrunk#3693), thanks @gubasso for reporting)

- **Approval state and branch-removal outcomes are machine-readable**: `wt config approvals list --format=json` reports whether a non-interactive run would stop for approval. `wt remove` and `wt step prune` replace `branch_deleted` with `branch_outcome`: `deleted`, `deferred`, `not_attempted`, `retained_unmerged`, `retained_checked_out`, `retained_raced`, `retained_failed`. (Breaking.) ([#3710](max-sixty/worktrunk#3710), thanks @NathanaelRea for the requests)

- **Every commit hash worktrunk prints follows `core.abbrev`**: The `wt list` table, `wt switch --prs`'s `log` tab, and `wt config state`'s CI cache table sliced to 8 characters while `--format=json` carried git's `%h`. All now ask git how wide it abbreviates in this repo. ([#3676](max-sixty/worktrunk#3676), [#3677](max-sixty/worktrunk#3677))

- **`wt list --format=json` schema 2 has a published JSON Schema**: [worktrunk.dev/schema/list-v2.json](https://worktrunk.dev/schema/list-v2.json) holds the contract, and `wt list --print-schema` prints the same document. Four fields that were bare strings are now enumerated vocabularies; the emitted JSON is unchanged. ([#3747](max-sixty/worktrunk#3747))

- **A detached worktree is named by its commit, not `-`**: The Branch cell hardcoded `-`, which reads as missing data rather than a state; it now carries the row's abbreviated HEAD, and the picker and statusline name the worktree the same way. ([#3675](max-sixty/worktrunk#3675))

### Fixed

- **Piped output is plain and no longer panics**: `wt list | head -3` exited 101 with `failed printing to stdout: Broken pipe`, and `wt list` wrote ANSI to a pipe unconditionally. Every stdout surface now exits cleanly, and the human-read ones are plain when piped unless `CLICOLOR_FORCE=1`. ([#3746](max-sixty/worktrunk#3746), [#3766](max-sixty/worktrunk#3766))

- **A CI check that hasn't finished no longer reads as passed**: Each forge's status parser missed documented values, so a GitHub PR parked on an approval gate showed green, and GitLab's `canceling` and Azure DevOps's `postponed` read as no CI at all. ([#3741](max-sixty/worktrunk#3741), [#3740](max-sixty/worktrunk#3740))

- **The shell wrappers survive an `rm` alias and a failing `--execute`**: Aliases bake into the wrapper at parse time, so `alias rm='rm -v'` reached its cleanup — noise on zsh and bash, and on nushell an abort that leaked three temp files, as a failing `--execute` body also did. ([#3714](max-sixty/worktrunk#3714), thanks @Ar4l), ([#3732](max-sixty/worktrunk#3732), [#3734](max-sixty/worktrunk#3734))

- **An alias or hook wrapping `wt switch` or `wt remove` keeps your subdirectory**: The user's position came from the `wt` process's cwd, which inside an alias body is the worktree root, so an aliased `wt remove` from `feature/apps/gateway` landed at the primary worktree's root. Fixes [#3723](max-sixty/worktrunk#3723). ([#3724](max-sixty/worktrunk#3724), thanks @vivienm for reporting)

- **`wt merge` and `wt step push` refuse a target worktree parked mid-operation**: The two-tree sync refuses an unmerged index but not a stopped cherry-pick or rebase whose conflict was already staged, so the push range could land in a paused target and be committed by `--continue`. ([#3759](max-sixty/worktrunk#3759))

- **The Claude plugin's worktree-remove hook resolves against the worktree path**: The hook anchored at `CLAUDE_PROJECT_DIR`, which the `claude agents` view routinely leaves outside any repository, so `wt remove` died with `not a git repository` and the session became undeletable. Its guard now also requires a `.git` entry. ([#3754](max-sixty/worktrunk#3754), [#3767](max-sixty/worktrunk#3767), thanks @judewang for the fix and the report)

- **A Gitea API error is reported as one, not as a parse failure**: `tea api` exits 0 whatever the HTTP status, so both call sites guessed from the body's shape and blamed an API change for an API error. `--include` surfaces the status instead. ([#3713](max-sixty/worktrunk#3713), [#3600](max-sixty/worktrunk#3600))

- **`--print-schema` and the doc-generation help flags name the right command**: All three found the subcommand by scanning `argv` for a `/wt` suffix, which never matches `wt.exe` under a backslash path, so on Windows they read the binary's own path as the command. ([#3762](max-sixty/worktrunk#3762))

- **A multibyte shell name no longer panics**: `extract_filename_from_path` sliced at `len() - 4` to test for `.exe` with no char-boundary check: `SHELL=/bin/日本語 wt config show` panicked, and on macOS every process name goes through it during shell detection. ([#3727](max-sixty/worktrunk#3727))

- **`wt` installed under a dotted name generates shell integration for that name**: `binary_name` used `file_stem`, which cuts at the last dot, so `wt config shell init bash` under `wt.old` emitted a wrapper for `wt`. It now strips only the executable suffix. ([#3719](max-sixty/worktrunk#3719))

- **Concurrent `wt step prune` removals no longer race the worktree registry**: `git worktree remove` reads every sibling under `.git/worktrees/`, so two overlapping removals could have one read a sibling mid-teardown. Registry-mutating removals now serialize behind a second lock. ([#3692](max-sixty/worktrunk#3692))

- **The `wt switch` first-run offer previews the legacy files it removes**: Accepting "Install shell integration?" could delete a deprecated worktrunk-managed wrapper the prompt never named. What gets removed is unchanged. ([#3656](max-sixty/worktrunk#3656))

- **`wt config create --project` writes a resolvable link**: The comment it writes into `.config/wt.toml` carried a raw Zola target, because the link-conversion regex stopped at the first `]` — here the one closing a nested code span. ([#3731](max-sixty/worktrunk#3731))

- **`wt list --branches` counts a local branch containing `/` as local**: The summary tally classified branch-only rows by `branch.contains('/')`, so a local `feature/login` counted under "N remote branches". ([#3687](max-sixty/worktrunk#3687))

- **`wt step relocate`'s human summary counts template-error branches as skipped**: `--format=json` already folded them into `skipped`; the human tally undercounted by the number of branches whose `worktree-path` template failed to expand. ([#3688](max-sixty/worktrunk#3688))

### Documentation

- **SignPath attribution appears with the artifacts it describes**: The code-signing notice and a route to the policy now sit in the install section's Windows block on the README and the docs landing page, as SignPath Foundation's OSS program requires. ([#3709](max-sixty/worktrunk#3709))

- **`wt step copy-ignored`'s `--require-include` example renders as a terminal block**: It was the only `console` block in the command's long help missing the `$ ` prefix. ([#3706](max-sixty/worktrunk#3706))

### Internal

- **Library API rework** (Breaking library API): `cargo-semver-checks` fails five lints — `LegacyForgeAlias` and `Repository::legacy_forge_alias` removed with the forge-classification revert, `Repository::forge_platform_override` removed for one shared resolver, `stage_worktree_removal` gained two parameters, `UserProjectOverrides` gained a `forge` field, and the `real-repo-benches` feature was removed. ([#3673](max-sixty/worktrunk#3673), [#3694](htt

See merge request: Harmonybrew/homebrew-core!16275

This branch was previously deployed

1 inactive deployment
tend — bc8a01cc Deployed Aug 3, 2026 by worktrunk-bot via review #3694
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

automated-fix Automated CI fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wt remove / wt switch invoked from an alias lose subdirectory preservation

2 participants