Repository navigation
Run switch --execute as literal argv - #3977
Conversation
worktrunk-bot
left a comment
There was a problem hiding this comment.
-x as literal argv is the right model, and deleting the exec channel from all five wrappers is a genuine simplification. Four things I'd want resolved first.
1. On Windows a bare -x code / -x claude / -x npm no longer resolves. execute_command builds Cmd::new(program), so the spawn goes through std::process::Command, whose Windows resolution appends .exe to an extensionless file name and searches PATH — it never consults PATHEXT (resolve_exe in std's sys/process/windows.rs; the .bat/.cmd branch below it only fires once the extension is already on the resolved path). So every npm/VS Code .cmd shim is unreachable by its bare name: -x code.cmd works, -x code does not. Under the PowerShell wrapper this previously went through Invoke-Expression, which uses PowerShell's own resolution and finds code.cmd. #2860's locked decision reads "argv[0] is resolved only as a PATH binary, identically on every wrapper" — a .cmd shim is on PATH, so this looks more like a gap than an accepted loss — and the -x help text's own example is -x code -- '{{ worktree_path }}'. Whether the answer is PATHEXT-aware resolution or just saying "use -x code.cmd on Windows", neither the help text nor the CHANGELOG breaking-change note mentions it today. I read this off the std source rather than observing it — I can't drive a Windows host from CI.
2. has_execute scans past --, so it fires on unrelated commands. Checked against nu 0.115.1 (the pinned version): wt step for-each -- rg -x foo sets has_execute, so stdout is never captured and the wrapper hands "" to an outer nushell pipeline. Inline suggestion narrows the scan to the args before --; I ran it over the switch/for-each/list shapes and it changes no currently-correct answer.
3. The same predicate misses short-flag clusters. --create is a bool and --execute takes a value, so wt switch -cx claude is a valid clap cluster, but -cx doesn't starts-with "-x" → has_execute is false → the wrapper redirects stdout to the temp file and claude sees a non-TTY stdout. A "short cluster containing x" arm catches it but brings its own false positive (-b with a value containing an x). It may be worth inverting the decision instead — capture stdout only for the commands whose stdout is data, stream by default — so an unrecognized shape fails toward a working terminal rather than a swallowed one.
4. A stale nushell wrapper breaks --execute across the upgrade, silently. The nushell wrapper is a full static file under vendor/autoload/, so it doesn't refresh when the binary does; a pre-cutover wrapper takes the o> $stdout_file path for --execute and produces exactly the symptom in (3), with nothing to tell the user why. wt already holds the signal — a wrapper that still sets WORKTRUNK_DIRECTIVE_EXEC_FILE predates the cutover — and today uses it only to scrub children. #2880 added a one-shot warning for the previous wrapper skew and its CHANGELOG entry called out the nushell reinstall; this entry doesn't.
Everything else read clean: the argv path keeps the child in the parent's process group with stdin inherited (so the TTY assertions in test_wrapper_switch_with_execute are testing the thing that matters), AlreadyDisplayed preserves the child's status without a second error line, propagate_sigpipe is scoped to this one caller, and the old-wrapper-with-new-binary combination is inert for bash/zsh/fish/PowerShell because wt never writes the exec file.
worktrunk-bot
left a comment
There was a problem hiding this comment.
test (windows) and affected tests (windows, advisory) both went red after I posted, on the same single failure — integration_tests::switch::test_switch_execute_verbose_multiline_template, a snapshot this PR rewrote. It's the same Windows-vs-Unix argv divergence as point 1 above, from a different direction, so it's worth stating the mechanism rather than re-accepting the snapshot.
The test now passes one argv element containing an embedded newline (-x echo -- "{% if branch %}branch={{ branch }}\nrepo={{ repo }}{% endif %}"). Unix: one argument, two lines of output. Windows: branch=multiline-test repo=repo on one line.
Windows has no argv array — CreateProcessW takes a single command-line string that the child re-parses. Rust's Quote::Auto (append_arg in std's sys/args/windows.rs) quotes an argument only when it contains a space or a tab, or is empty: arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') || arg_bytes.is_empty(). A newline is neither, so this argument is written to the command line bare, and the child's parser treats the newline as a separator and sees two arguments, which echo rejoins with a space.
So --execute's "arguments after -- are passed verbatim" doesn't hold on Windows for any argument containing a newline (and, by the same predicate, likely for other characters the receiving parser splits on but std doesn't quote). Before this PR the value went to Git Bash / PowerShell as a quoted shell string, which round-tripped it.
Worth deciding whether the fix is force_quotes (Command::raw_arg / always-quote) on the --execute spawn, or scoping the promise in the help text to Unix. Both Windows jobs stop on first failure, so anything after this test is still unverified on Windows.
Happy to push a fix if you'd like one — say which direction and I'll take it.
worktrunk-bot
left a comment
There was a problem hiding this comment.
Windows is green again, but the divergence that failure exposed is still there — the new test just can't observe it. The mock's _default arm ignores its arguments, so on Windows the multiline argument still arrives at multiline-target.exe split in two and the snapshot is byte-identical either way.
One correction to what I said last time: I claimed both Windows jobs stopped on first failure. They didn't — that run reports 4301 tests run: 4300 passed, 1 failed, 37 skipped. That makes it a clean natural experiment, because two tests in that run passed a newline-bearing argument to a child and only one of them broke. test_switch_execute_verbose_multiline_template collapsed to branch=multiline-test repo=repo; test_switch_internal_with_execute — -x sh -- -c "echo 'line1'\necho 'line2'" — passed. The discriminator is std's quote predicate: an argument is quoted only when it contains a space or a tab, or is empty. branch=multiline-test\nrepo=repo has neither, so it went onto the command line bare; the -c payload has spaces, so it went quoted and its newline survived. Same platform, same spawn path, opposite outcomes, exactly along that boundary.
That scopes the gap more tightly than I put it before: a native msvcrt child splits on space and tab only, so it is unaffected. The children that re-split are the Cygwin/MSYS family — which on a Windows dev machine is most of the git-for-windows toolchain, including the sh the help text itself recommends. The -x text promises arguments after -- are "passed verbatim", with no platform caveat.
What this commit changes is that CI can no longer catch it. test_switch_with_execute_uses_literal_argv, the argv-fidelity test with spaces, quotes, empty and non-ASCII arguments, is #[cfg(unix)]; test_switch_internal_with_execute is the only Windows-running case left with a newline in an argument, and it is green by accident — its argument happens to fall on the quoted side of the predicate. Add a space to it and it goes red.
The two directions from before still stand: force-quote (a raw command line) on the --execute spawn, or scope the verbatim promise in the help text to Unix. Say which and I'll push it.
worktrunk-bot
left a comment
There was a problem hiding this comment.
Both of the last round's points check out on this head.
The gate discriminates exactly the case it needs to. Re-reading the five pre-cutover wrappers at the merge base: bash, zsh, fish, and PowerShell all run wt with stdout inherited, and only nushell routes every non-list invocation through o> $stdout_file. So "retired variable set and stdout not a terminal" is true under the old nushell wrapper and false under the other four — no false negative, and the one residual false positive (an old wrapper plus a user's own redirect) is what the "may be" in the message already covers. Both directions are pinned: test_wrapper_switch_with_execute asserts silence through a PTY with the variable set, and test_current_wrapper_wins_retired_variables_and_warns keeps the warning under captured stdout. The unchanged switch_with_execute_* snapshots are themselves the evidence — the variable is set in that test now and they didn't move. The [cvy] comment names the class correctly too: -c is the only switch-local boolean short, -C and -b both take values, -v and -y are the globals.
One thing the commit left behind. The module's # Protocol spec in src/output/global.rs still states the old trigger:
//! retired exec-file variable is recognized only to warn that the live shell
//! still has an old wrapper loaded.
"an old wrapper loaded" is now precisely the condition this commit stopped warning on — four of the five old wrappers load and stay quiet by design. The function docstring immediately above the code was updated; this one wasn't, and it's the module-level spec CLAUDE.md asks to keep current. Something like "recognized only to warn when an old wrapper has redirected --execute output away from the terminal" would match the code. It sits outside the diff hunks so I haven't written it as a suggestion — happy to push it if you'd rather not hand-edit.
Both are review findings against the merge of main. The Shared-tty bullet in `shell_exec.rs` claimed foreground pipeline steps were the only `Cmd` call site pairing `forward_signals()` with `inherit_stdin()`. #3977 added a second: `execute_command` in `output/global.rs`, the `wt switch --execute` launcher. The undercount mattered because the next sentence is the `killpg` caveat — a reader would have concluded a `wt switch -x cargo test` subtree *is* reachable by `killpg`. Name both sites and generalise the caveat to "such a child's" so it covers the `--execute` program too. `sourced_steps_to_foreground`'s doc still said the `source` field drives the per-step trust model, but #3977 left an unconditional `DirectivePassthrough::inherit_from_env()` there, so `source` selects nothing. The same stale clause sits on `PipelineKind` and on `ForegroundStep::directives` in `command_executor.rs`; corrected together so the two files don't contradict each other. Doc comments only — no behavior change.
…nd's list
`AliasEntry`'s docstring still described the per-source EXEC regime as live
behavior ("user steps skip approval and pass EXEC through; project steps
require approval and scrub EXEC"), contradicting the same file's module doc
~300 lines above, which #3977 already updated. The EXEC directive var is
retired: `scrub_directive_env_vars` removes it unconditionally and
`directive_cd_file` re-adds only CD, so both regimes scrub it. The approval
half of the sentence still holds and stays.
`ConcurrentCommand::directives` pointed at "`DirectivePassthrough` for the
trust model (CD passthrough, EXEC scrub)" — the type has one field and no
EXEC dimension, so that no longer resolves to anything.
`PipelineKind`'s doc listed three things the type drives but omitted two:
`log_label` (the `commands.jsonl` trace label) and `is_hook` (whether the
child's inherited `GIT_DIR`/`GIT_WORK_TREE` are scrubbed), both read off
`fg_step.announce` in `run_one_command`. Splitting the list by when each
applies also fixes the rewrap that left `metadata` alone on its own line.
`sourced_steps_to_foreground`'s closing paragraph restated the CD
inheritance the paragraph above it already names by constructor; dropped.
Doc comments only, no behavior change.
Cuts 0.76.0. `cargo semver-checks` fails ten lints, so the bump is minor. ## Changelog filing fix Five entries had been appended to the already-tagged `## 0.75.0` section after v0.75.0 shipped (#3977/#2860, #3949 ×2, #3959, #3945). They describe changes that ship *here*, and GitHub's 0.75.0 release notes — built from the tag — never showed them. They are moved into `## 0.76.0` and rewritten to the length ceiling; `## 0.75.0` is restored byte-identical to `git show v0.75.0:CHANGELOG.md`. The mechanism is systemic: a PR appends under whatever heading is currently top, so every post-release PR lands in the shipped section until the next release opens a new one. ## `--execute` template guidance `#3977` switched `--execute` expansion to `ShellEscapeMode::Literal`, which is correct for an argv model. But the migration that v0.53.0–v0.75.0's deprecation warning *printed* — `-x sh -- -c '<old body>'` — splices a template variable into text `sh` re-parses, so a value with spaces word-splits where the old POSIX-escaped model kept it intact. Worst case is `rm -rf` against unintended paths. `--execute`'s help now documents passing the variable as a separate argument and referencing it positionally. `extending.md` already modelled that form, so no recipe changed. ## Validation - `nightly` on the cut-from tip (`baf161bf6`): all 14 jobs green — [run 33538866753](https://github.com/max-sixty/worktrunk/actions/runs/33538866753) - `wt hook pre-merge --yes`: 4713 passed - Data-loss surface reviewed across the 45-commit diff by four independent finders; adjudication in the release thread. No new destructive path — `#3977` removes one, deleting the EXEC directive file from all five shell wrappers. > _This was written by Claude Code on behalf of max-sixty_
## Problem
`--no-cd` took the `--execute` program back to the invoking directory
along with the shell. `wt switch feature --no-cd -x pwd` printed the
directory you ran it from, so a program that means "act on the new
worktree" — an editor, an agent — had to be handed `{{ worktree_path }}`
explicitly.
Nothing decided that. One `change_directory()` call did two jobs: it
wrote the shell's cd directive and it recorded the program's working
directory in `OutputState::target_dir`, which `execute()` read back.
Skipping the directive therefore also dropped the program's directory.
The behavior first appears in the docs in #3977, which described what
the shared value already did, and #4043 then matched the `Executing
(--execute) @ …` header to it.
In [#4042](#4042) the
reporter wanted exactly this combination — open the worktree in Zed,
leave the terminal where it was — and had to work around it by passing
the path as an argument.
## Solution
The program's directory becomes an argument rather than a leftover of
the directive. `handle_switch_output` computes it once and returns it as
`SwitchDisplayPaths::execute_dir`; `execute()` takes it from the caller;
`OutputState` loses `target_dir`, so the two decisions can't be
re-coupled through global state. `change_directory()` now only moves the
shell.
`--no-cd` writes no directive and leaves the shell where it stands. The
program starts in the worktree the switch selected, with the
subdirectory position `resolve_subdir_in_target` preserves, exactly as
under `--cd`.
Two consequences worth reading in the diff:
- The git-discovery scrub (`GIT_DIR` and friends, #3373) was conditional
on having a target directory, so it didn't run under `--no-cd`. That
directory is now always one wt chose, which is the condition CLAUDE.md
sets for scrubbing, so the scrub is unconditional.
- The header annotates the program's directory whenever the user's shell
won't be there — which now includes `--no-cd`, where it previously read
a bare `Executing (--execute):`. The updated snapshot shows both halves:
`pwd` prints the worktree, and the header names it.
This changes documented behavior of a flag combination rather than any
flag or config key. `--execute` means "run this against the worktree I
just selected", and `--no-cd` is a statement about the shell; the old
behavior made the second silently override the first.
Thanks to @yajo for reporting #4042.
> _This was written by Claude Code on behalf of max-sixty_
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
worktrunk 0.76.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 - **`wt switch --execute` takes a program, not a shell string**: `-x` names one program, with everything after `--` passed as literal argv. Worktrunk spawns it as a child rather than running it in your interactive shell, so shell functions and its `cd` no longer reach you. `-x sh -- -c '…'` recovers shell syntax, not functions. (Breaking: existing `-x` strings, plus `WORKTRUNK_DIRECTIVE_EXEC_FILE` and `WORKTRUNK_SHELL`.) ([#3977](max-sixty/worktrunk#3977), closes [#2860](max-sixty/worktrunk#2860), fixes [#3944](max-sixty/worktrunk#3944), thanks @omgreenfield for testing the migration path) - **Worktrunk decides tracking for the branches it creates**: a new branch gets an upstream only when its name matches the remote branch it starts from, whatever `branch.autoSetupMerge` says: `--create release --base origin/release` tracks, `--create feature --base origin/release` does not. Under `autoSetupMerge = false` this previously exited 128 after creating the worktree. ([#3913](max-sixty/worktrunk#3913), [#3950](max-sixty/worktrunk#3950), fixes [#3937](max-sixty/worktrunk#3937), thanks @mjakl for reporting and diagnosing) - **Retired config keys are no longer read**: `commit.generation.template-file` and `squash-template-file` are gone — put the file's contents in `template` or `squash-template`. There is no migration: the key stays, warns as unknown on every load, and the prompt reverts to the built-in default. Setting both `template` and `template-file` used to fail the load; it now loads `template`. `switch.picker.timeout-ms` likewise warns rather than being stripped. (Breaking.) ([#3949](max-sixty/worktrunk#3949)) - **Project aliases and hooks can use `wt switch --execute`**: their bodies previously refused it. Worktrunk now starts the program itself instead of handing shell text to your shell, and the command-approval gate remains the control on project-defined commands. ([#3977](max-sixty/worktrunk#3977)) - **Established automation and LLM customization interfaces are now stable**: `wt step eval`, `wt step for-each`, `wt step prune`, LLM branch summaries, `wt config state vars`, and `commit.generation.template-append` are no longer marked experimental. ([#3949](max-sixty/worktrunk#3949)) - **`wt step prune` stages removals concurrently again**: only the `git worktree remove` teardowns serialize, so dirty checks, fsmonitor shutdown, and the trash rename overlap. The `prune_e2e/live` benchmark median went from 377 ms to 222 ms. ([#3954](max-sixty/worktrunk#3954)) - **`wt config approvals add` reads as a review rather than a warning**: it opens with a cyan `Review 1 command for repo:` instead of a yellow `▲ … needs approval to execute`. The execution-time gate is unchanged. ([#3953](max-sixty/worktrunk#3953)) ### Fixed - **The `wt switch` picker survives a preview longer than 65,535 lines**: skim keeps the pane's line count in a `u16`, so a larger diff aborted `wt` with exit 101 seconds after it painted — on screen the picker looked like it closed by itself. Panes now cap at 60,000 lines and say so. ([#3959](max-sixty/worktrunk#3959), fixes [#3958](max-sixty/worktrunk#3958), thanks @sandertammesoo for reporting and diagnosing) - **The nushell wrapper propagates exit codes without a POSIX shell**: it reported a failing `wt` by spawning `sh`, so on Windows every failing command printed a ``Command `sh` not found`` trace and exit 1 whatever the real code was. Nushell's wrapper is a static file, so rerun `wt config shell install` to pick this up. ([#3945](max-sixty/worktrunk#3945)) - **The picker no longer shows one detached worktree's diff for another**: previews were keyed by branch name, so every detached row shared the key `(detached)`. Rows now key by canonical identity, which also lets `wt remove feature ~/repo.feature` plan that worktree once instead of failing on the second. ([#3926](max-sixty/worktrunk#3926)) - **`wt switch pr:<n>` gives `pre-switch` hooks the real branch**: `branch` and `target` held the literal `pr:3933`, and `target_worktree_path` was unset even when that branch had a worktree. `pr_number` and `pr_url` are now set for same-repo PRs, not only forks. ([#3941](max-sixty/worktrunk#3941), fixes [#3934](max-sixty/worktrunk#3934), thanks @robsonpeixoto for reporting) - **`wt config shell install` no longer replaces an rc file created while it was checking**: the missing-file path refuses to clobber and fails with a rerun hint. A dangling rc symlink is preserved and rejected rather than overwritten. ([#3929](max-sixty/worktrunk#3929)) - **`wt switch --create X --base pr:<n>` works when the PR branch has no local branch**: the fetch writes only the remote-tracking ref, and git won't expand a bare name to one, so the command failed with `No branch, tag, or commit named …`. The base is now named under its remote. ([#3951](max-sixty/worktrunk#3951)) - **`wt switch --create` streams `git worktree add` instead of stalling**: where a sandbox denied the timed wait's pipe or `sigaction`, the command waited out git's entire run and then reported `Failed to wait for command` for work that had already succeeded. ([#3881](max-sixty/worktrunk#3881)) - **Claude Code activity markers stay on the session's launch worktree**: the plugin's marker hooks pass `-C "$CLAUDE_PROJECT_DIR"`, so a `cd` mid-session no longer marks another repository. A session launched outside a repository gets no marker. ([#3956](max-sixty/worktrunk#3956)) ### Documentation - **`--execute` documents how to get a variable into a shell body**: each position is substituted verbatim, so a variable spliced into `sh -c` text is re-parsed by that shell and splits on spaces. The help now shows passing it as a separate argument and referencing it positionally. ([#3977](max-sixty/worktrunk#3977)) - **The clone-local default-branch override is documented**: `wt config state default-branch set` writes `worktrunk.default-branch` to the clone's local git config — machine-local, never committed, and shared by every linked worktree. `set` warns when the branch isn't checked out locally, and `wt list` skips its comparisons until it is. ([#3947](max-sixty/worktrunk#3947), [#3948](max-sixty/worktrunk#3948), fixes [#3946](max-sixty/worktrunk#3946), thanks @danielo515 for the request) - **The docs site renders code with the CLI's own colors**: terminal examples reproduce each snapshot's exact ANSI roles, while command references and the homepage command comparison get clap and shell syntax color from paired light/dark themes. File excerpts gain a path tab, and code wraps instead of scrolling on mobile. ([#3936](max-sixty/worktrunk#3936), [#3938](max-sixty/worktrunk#3938), [#3939](max-sixty/worktrunk#3939), [#3942](max-sixty/worktrunk#3942)) - **The `pre-start` upstream example uses `--base`**: it showed `wt switch --create feature origin/feature`, which `wt switch` rejects. ([#3955](max-sixty/worktrunk#3955)) ### Internal - **Library API rework** (Breaking library API): `cargo-semver-checks` fails ten lints — `RemoteRefProvider` and its provider structs give way to `ForgeKind` dispatch, the `--execute` rework retires the fish and PowerShell `ShellEscapeMode` escapes and `WORKTRUNK_SHELL_ENV_VAR`, `BranchRef` swaps `full_ref`/`worktree_path` for `id`, and accessors including `Branch::unset_upstream` and `ProjectConfig::ci_platform` are gone. ([#3913](max-sixty/worktrunk#3913), [#3926](max-sixty/worktrunk#3926), [#3949](max-sixty/worktrunk#3949), [#3963](max-sixty/worktrunk#3963), [#3977](max-sixty/worktrunk#3977)) - **Hook pipelines and `wt list` collection lost two indirection layers**: the background pipeline carries `PreparedStep` directly, and 15 marker task types collapse into one exhaustive dispatch. The synthesized-`--force` submodule path keeps its dirty re-check and destructive command under one lock, so prune's narrower locking doesn't widen that window. ([#3964](max-sixty/worktrunk#3964), [#3954](max-sixty/worktrunk#3954)) ## Install worktrunk 0.76.0 ### Install prebuilt binaries via shell script ```sh curl --proto '=https' --tlsv1.2 -LsSf https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-installer.sh | sh && wt config shell install ``` ### Install prebuilt binaries via powershell script ```sh powershell -ExecutionPolicy Bypass -c "irm https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-installer.ps1 | iex"; git-wt config shell install ``` ### Install prebuilt binaries via Homebrew ```sh brew install worktrunk && wt config shell install ``` ## Download worktrunk 0.76.0 | File | Platform | Checksum | |--------|----------|----------| | [worktrunk-aarch64-apple-darwin.tar.xz](https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-aarch64-apple-darwin.tar.xz) | Apple Silicon macOS | [checksum](https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-aarch64-apple-darwin.tar.xz.sha256) | | [worktrunk-x86_64-ap See merge request: Harmonybrew/homebrew-core!18482
Summary
wt switch -xas one program plus arguments that bypass Worktrunk shell parsing; program lookup and argument decoding use native operating-system behavior.wtin the selected worktree, preserving terminal access, signals, and exit status.shdependency. Shell wrappers now carry only the directory change.-cx, stop scanning at--, and warn when a retired exec-file wrapper buffers stdout away from the terminal.Shell syntax remains explicit:
-x sh -- -c 'code . && test -f Cargo.toml'. On Windows, shell shims need their extension (-x code.cmd) or an explicit shell such as-x cmd.exe -- /C code.This completes the argv cutover proposed in #2860 and removes the remaining Nushell-on-Windows problem in #3944. It adds no PATHEXT lookup, custom Windows quoting, or PowerShell launcher path, and still removes 597 lines from
srcandtemplateson net.Validation
cargo run -- hook pre-merge --yesThanks @omgreenfield for testing the migration path in #2860.
Closes #2860
Closes #3944