Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Release v0.72.0 (#3759)
Maximilian Roosf57fac365b22
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3edb33b40..081d29a4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,79 @@# Changelog+## 0.72.0++### Improved++- **`wt merge` and `wt step push` leave the target worktree's uncommitted changes in place**: Both commands used to move a dirty target worktree's changes aside with an autostash (`git stash push -u`) and restore them after the push, because the fast-forward's `receive.denyCurrentBranch=updateInstead` refuses any dirty worktree at all. That design entered `refs/stash` — a repo-global namespace any process can mutate — and restored staged changes as unstaged. Both strategies now advance the target through one path: a compare-and-swap `update-ref`, then `update-index --refresh` plus `read-tree -m -u` in the target worktree (git's documented lenient `push-to-checkout` policy), with a CAS rollback if the sync can't apply, so branch and worktree move together or not at all. Uncommitted changes at paths the push doesn't touch never move — unstaged edits stay unstaged, staged entries stay staged, untracked files stay put, and `refs/stash` is never involved. The upfront check that names a conflicting file also reads `--porcelain -uall` now, so an untracked file *inside* an untracked directory is caught and named rather than slipping past a collapsed `dir/` entry. (Breaking: the fast-forward path no longer runs a `git push`, so `pre-push` and the receive-side hooks — `pre-receive`, `update`, `post-receive`, `post-update`, and any `push-to-checkout` — no longer fire. A `git merge` run in the target wouldn't run them either, which is the line the module spec draws, and the new sync reimplements the lenient policy `push-to-checkout` documents rather than invoking the hook. Separately, a sync that can't apply now fails the command with the ref rolled back, where `--no-ff` previously warned and left the worktree stale behind its own branch.) ([#3703](https://github.com/max-sixty/worktrunk/pull/3703), [#3684](https://github.com/max-sixty/worktrunk/pull/3684), [#3693](https://github.com/max-sixty/worktrunk/pull/3693), thanks @gubasso for reporting the stash race that started this)++- **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, so `github.attacker.example` carried the exact label and classified fine, while the rule shut out the self-hoster with a hyphenated name. `github-enterprise.acme.com`, `mygithub.com`, `gitlab-internal.company.com`, and the `github-personal` SSH alias classify again, so CI status, `wt switch --prs`, and `repo.provider` work with no config. The cost is a host that merely sounds like a forge getting a forge CLI run at it, which surfaces as that CLI's error rather than as silence. Azure DevOps keeps suffix matching on `dev.azure.com` / `visualstudio.com` — those are service domains rather than a brand in the host — and userinfo still resolves to the network host, so `https://[email protected]/…` is `attacker.example`. The `github-personal` diagnostic 0.71.0 added is gone with the rule it explained. ([#3673](https://github.com/max-sixty/worktrunk/pull/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 every repository on that host, nested groups and all. Every matching entry applies, least- to most-specific, so a narrower key wins where two set the same field and leaves the rest alone. The table also gained `forge.platform` and `forge.hostname`, which previously lived only in each repository's committed `.config/wt.toml` — so a self-hosted host carrying none of the three brand names needs one user-config entry rather than a block in every repo. A repository's own `[forge]` still wins field by field. `approved-commands` matches by the same rules, but only a hand-written key is ever a pattern: `wt config approvals add` records under the exact project identifier, and `clear` empties only the exact entry. [Docs](https://worktrunk.dev/config/#user-project-specific-settings) ([#3701](https://github.com/max-sixty/worktrunk/pull/3701), thanks @chrishas35 for the request and @witt-bit for the workspace-scoped case it partly serves)++- **`wt list --format=json` schema 2 has a published JSON Schema**: The contract is at [worktrunk.dev/schema/list-v2.json](https://worktrunk.dev/schema/list-v2.json), and `wt list --print-schema` prints the same document. Four fields that were bare strings — `checks.status`, `display.state`, `default_branch.integration.reason`, and `worktree.operation` — are now enumerated vocabularies, so a new variant is a compile error rather than a value silently missing from the published schema. The emitted JSON is unchanged. ([#3747](https://github.com/max-sixty/worktrunk/pull/3747))++- **Approval state and branch-removal outcomes are machine-readable**: `wt config approvals list --format=json` reports which of three states a non-interactive run would hit — `no_commands`, `approved`, `approval_required` — so an orchestrator can learn that a run would stop for approval without running the operation or passing `--yes`. A separate `stale` list carries approvals whose command template has changed since, which `--yes` would otherwise silently re-approve; it co-occurs with all three states, so it isn't a fourth. Separately, removal's `branch_deleted` boolean collapsed five internal outcomes into two values, reporting a lost CAS race and an explicit `--no-delete-branch` as the same `false`, and a deferred deletion as `true` on intent alone. `branch_outcome` names them: `deleted`, `deferred`, `not_attempted`, `retained_unmerged`, `retained_checked_out`, `retained_raced`, `retained_failed`. (Breaking: `branch_deleted` is replaced, not supplemented, on `wt remove --format=json` and `wt step prune --format=json`'s live path.) ([#3710](https://github.com/max-sixty/worktrunk/pull/3710), thanks @NathanaelRea for the requests)++- **A detached worktree is named by its commit, not `-`**: The Branch cell hardcoded `-` for a worktree with no branch, which reads as missing data rather than as a state — and it was the odd one out, since the skeleton row, the statusline, and the picker all reached for `(detached)`. The cell now carries the row's abbreviated HEAD in dim yellow, and the picker filters and the statusline name the worktree the same way. Detached worktrees aren't exotic here: Codex creates one per session. ([#3675](https://github.com/max-sixty/worktrunk/pull/3675))++- **Every commit hash worktrunk prints follows `core.abbrev`**: The `wt list` table sliced `head[..8]` while `--format=json`'s `short_sha` carried git's `%h`, so one commit read `1b9f1d96` in the table and `1b9f1d9` in JSON. `wt switch --prs`'s `log` tab and `wt config state`'s CI cache table sliced to 8 too. All of them now ask git how wide it abbreviates in this repo, cached once per process, so `core.abbrev = 12` no longer truncates mid-hash and the default 7 stops reserving a column nothing fills. Where the commit-details batch fails, the Commit cell is now empty rather than a slice of a SHA git refused. ([#3676](https://github.com/max-sixty/worktrunk/pull/3676), [#3677](https://github.com/max-sixty/worktrunk/pull/3677))++### Fixed++- **`wt merge` and `wt step push` refuse a target worktree parked mid-operation**: The target sync is a two-tree merge, which refuses an unmerged index but not a stopped cherry-pick or rebase whose conflict has already been staged. A target paused between steps could therefore have the push range written into it, and the user's `--continue` would commit the synced tree as the step's result. The old fast-forward path got this check for free from `receive.denyCurrentBranch=updateInstead`, which refused any unclean target outright; both strategies now ask directly, and the refusal names the worktree holding the operation. ([#3759](https://github.com/max-sixty/worktrunk/pull/3759))++- **An alias or hook wrapping `wt switch` or `wt remove` keeps your subdirectory**: `wt switch` and `wt remove` land you in the destination's matching subdirectory, but the resolution read the user's position from the `wt` process's own cwd — which 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 with `[aliases] finish = "wt remove -y"`, `wt finish` from `feature/apps/gateway` dropped you at the primary worktree root. The shell's directory now travels with the CD directive file, to exactly the children allowed to move the user's shell, and each layer forwards it so nesting composes. Nothing about the working directory of alias or hook bodies changes; `{{ cwd }}` is still the worktree root. Fixes [#3723](https://github.com/max-sixty/worktrunk/issues/3723). ([#3724](https://github.com/max-sixty/worktrunk/pull/3724), thanks @vivienm for reporting)++- **An `rm` alias no longer breaks the shell wrappers' cleanup**: zsh, bash, and nushell all expand aliases when the wrapper's function is parsed, so a user's `alias rm='rm -v'` defined before the wrapper was installed baked itself into the cleanup. On zsh and bash that printed two lines of `removed '/tmp/…'` noise per `wt` invocation. On nushell it was worse: nushell raises on a non-zero external exit, so an `rm` alias that failed aborted the wrapper before it returned — the command's stdout was silently discarded and three temp files leaked. All three now bypass alias resolution (`command rm`, and `^rm` on nushell, whose builtin is kept on Windows where there is no external `rm`), with the nushell cleanup wrapped in `try` so it can never abort the wrapper again. ([#3714](https://github.com/max-sixty/worktrunk/pull/3714), thanks @Ar4l), ([#3732](https://github.com/max-sixty/worktrunk/pull/3732))++- **A failing `--execute` body no longer strands the nushell wrapper's temp files**: The wrapper's `--execute` call wasn't wrapped in `try`, so a body exiting non-zero unwound the whole function — cleanup never ran, all three `mktemp` files leaked, and the stdout the function still owed was discarded. The existing test passed because the unwind happened to carry the exit code out to the shell, not because the wrapper handled it. ([#3734](https://github.com/max-sixty/worktrunk/pull/3734))++- **Piped output no longer panics when the consumer stops reading**: `wt list | head -3` and `wt list statusline | head -1` exited 101 with `failed printing to stdout: Broken pipe`, and so did `wt config state get --format=json | head -3`. std's `print!`/`println!` panic on a `BrokenPipe` while anstream's drop it, so which behavior a surface got was decided by which macro its file happened to import — `wt config show --format=json | head -3` had always exited cleanly. Every stdout surface now exits cleanly instead: the thirty-six `--format=json` call sites through one `print_json`, the human-read ones — the `wt list` table, `--version`, `--help-md`, `--help-description`, and `wt config update --print` — through anstream, and the two whose escapes are data rather than presentation — `wt list statusline` and the `--help-page` document — through a verbatim printer that drops a `BrokenPipe` without stripping their ANSI. ([#3746](https://github.com/max-sixty/worktrunk/pull/3746), [#3766](https://github.com/max-sixty/worktrunk/pull/3766))++- **`wt list` no longer colors a pipe**: `--help` documents `NO_COLOR` and `CLICOLOR_FORCE` ("Force colored output even when not a TTY"), which only means something if color is off when stdout isn't a terminal. The table wrote its escapes through std's macros, so neither variable reached it and a pipe got ANSI unconditionally. Piped output is now plain by default, with `CLICOLOR_FORCE=1` to keep color. `NO_COLOR` reaches the buffered table — the piped case, plus `--no-progressive` on a terminal — while the default progressive terminal rendering bakes each row's escapes in and is unchanged. ([#3766](https://github.com/max-sixty/worktrunk/pull/3766))++- **`--print-schema` and the doc-generation help flags name the right command**: `--print-schema`, `--help-page`, and `--help-description` each scanned `argv` for the subcommand, recognizing the binary by a `/wt` suffix or a `target/` path component. Neither matches `wt.exe` under a backslash path, so on every Windows install all three read the binary's own path as the command: `--print-schema` exited 2, and the other two exited 0 with empty output. The scan also took the value of a preceding global as the command, so on any platform `wt -C <path> list --print-schema` answered `No JSON schema for '<path>'`. All three now take the name clap already parsed, and `--print-schema` prints through the same `print_json` as the `--format=json` surfaces, so a closed consumer no longer panics. ([#3762](https://github.com/max-sixty/worktrunk/pull/3762))++- **A CI check that hasn't finished no longer reads as passed**: Each forge's status parser was missing values its API documents, and in every case a non-terminal state read as terminal — so a row settled on a verdict before CI had one. On GitHub, a check parked on a deployment-protection rule or a required reviewer (`WAITING`, `REQUESTED`) didn't count as running, so `wt list --full` showed a green cell for a PR blocked on an approval gate that had run nothing; `EXPECTED` was matched against the wrong field, and a run that failed to start (`STARTUP_FAILURE`) counted neither way. On GitLab, `canceling` and `waiting_for_callback` rendered the same empty cell as a branch with no pipeline at all. On Azure DevOps, an in-flight `cancelling` reported red before anything had finished, `postponed` rendered empty, and a terminal `partiallySucceeded` build rendered as no CI. GitHub's, GitLab's, and Azure DevOps's documented enums are now fully covered. ([#3741](https://github.com/max-sixty/worktrunk/pull/3741), [#3740](https://github.com/max-sixty/worktrunk/pull/3740))++- **A Gitea API error is reported as one, not as a parse failure**: `tea api` copies the response body to stdout and exits 0 whatever the HTTP status, so both Gitea call sites guessed the outcome from the body's shape. Gitea blanks a 500's message for non-admin tokens, so that body fell through to the data path — `wt list` logged `Failed to parse tea api pulls JSON` once per branch, and `wt switch pr:<n>` failed with `This may indicate a Gitea API change`, both blaming an API change for an API error. `tea api --include` writes the status line to stderr, so the status is available after all: a body Gitea never wrote (a reverse proxy's HTML page) is now an error rather than a resource, and retriability is the status code rather than a search for `429` in Gitea's prose. A blanked 500 shows the error indicator where it used to paint the same blank cell as a healthy branch with no CI. ([#3713](https://github.com/max-sixty/worktrunk/pull/3713), [#3600](https://github.com/max-sixty/worktrunk/pull/3600))++- **`wt` installed under a dotted name generates shell integration for that name**: `binary_name` derived the command from `argv[0]` with `file_stem`, which cuts at the last dot wherever it is, on every platform — so `wt config shell init bash` under `wt.old` emitted a wrapper for `wt`, a command the user may not have. It now strips only the executable suffix, case-insensitively. A non-UTF8 `argv[0]` is rejected with `Invalid shell integration command name` rather than quietly generating integration for a different command. ([#3719](https://github.com/max-sixty/worktrunk/pull/3719))++- **A multibyte shell name no longer panics**: `extract_filename_from_path` compared a name's last four bytes against `.exe` by slicing at `len() - 4` with no char-boundary check, so `SHELL=/bin/日本語 wt config show` panicked. On macOS every process name on the machine goes through this function during shell detection, so one CJK-named process crashed any command that detects the shell. ([#3727](https://github.com/max-sixty/worktrunk/pull/3727))++- **Concurrent `wt step prune` removals no longer race the worktree registry**: `git worktree remove` enumerates every entry under `.git/worktrees/` and reads each sibling's `commondir` while resolving its target, so two overlapping removals could have one read a sibling in the window after another worker began tearing it down. Registry-mutating removals now serialize behind a second lock; a plain branch deletion's checkout probe only reads the registry, so those still run concurrently. ([#3692](https://github.com/max-sixty/worktrunk/pull/3692))++- **The Claude plugin's worktree-remove hook resolves against the worktree path**: The hook anchored at `CLAUDE_PROJECT_DIR`, which can only ever name one directory — but the `claude agents` view spans every repository you have run a background session in, and is typically launched from a parent that merely contains them. Both the anchor and its `.` fallback then landed outside any repository, `wt remove` died with `not a git repository`, and the session became undeletable. The hook now passes the worktree path to `-C`: a linked worktree's `.git` file points at its owning repository, so discovery resolves wherever the worktree lives on disk. The hook's own guard narrowed in the same release: it skipped only a path that was gone, so a skeleton directory left by an interrupted create or remove passed the check and reached `wt remove`, which then read the path as a branch name and exited non-zero. Claude Code reads that as a failed removal and keeps the session row, and since prune ignores a directory that was never a worktree, nothing healed it. The guard now requires a `.git` entry. ([#3754](https://github.com/max-sixty/worktrunk/pull/3754), thanks @judewang), ([#3767](https://github.com/max-sixty/worktrunk/pull/3767), thanks @judewang for reporting)++- **The `wt switch` first-run offer previews the legacy files it removes**: Accepting "Install shell integration?" could delete a deprecated worktrunk-managed wrapper — a fish `conf.d/wt.fish` superseded by `functions/wt.fish`, or a stranded nushell autoload copy — which the confirmation prompt never named, reporting it only after the fact. The offer's preview now lists the same removals `wt config shell install` previews. What gets removed is unchanged; only what the prompt discloses. ([#3656](https://github.com/max-sixty/worktrunk/pull/3656))++- **`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". It now reads the same structural scope the gutter sigil already did. ([#3687](https://github.com/max-sixty/worktrunk/pull/3687))++- **`wt step relocate`'s human summary counts template-error branches as skipped**: `--format=json` folded them into its `skipped` set; the human tally counted only validation and executor skips, so it undercounted by the number of branches whose `worktree-path` template failed to expand. ([#3688](https://github.com/max-sixty/worktrunk/pull/3688))++- **`wt config create --project` writes a resolvable link**: The comment it writes into `.config/wt.toml` — and that `wt config create --help` prints — carried a raw `](@/config.md#…)` Zola target. The link-conversion regex stopped at the first `]`, which here closed a nested `` `[projects]` `` code span. Both the config transform and the skill mirrors now share one rule for brackets in link text, and an unconvertible link fails the sync test naming the line rather than reaching a user's config. ([#3731](https://github.com/max-sixty/worktrunk/pull/3731))++### 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, rather than only on the policy page. The policy page leaves the docs navigation in the same change — unlisted, still published at `/code-signing/`. ([#3709](https://github.com/max-sixty/worktrunk/pull/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, so the web docs rendered it as a plain code fence. ([#3706](https://github.com/max-sixty/worktrunk/pull/3706))++### Internal++- **Library API rework** (Breaking library API): `cargo-semver-checks` fails five lints — struct `worktrunk::git::LegacyForgeAlias` and method `Repository::legacy_forge_alias` removed with the forge-classification revert, `Repository::forge_platform_override` removed in favor of one shared resolver, `worktrunk::git::stage_worktree_removal` gained two parameters, `UserProjectOverrides` gained a `forge` field, and the `real-repo-benches` feature was removed. ([#3673](https://github.com/max-sixty/worktrunk/pull/3673), [#3694](https://github.com/max-sixty/worktrunk/pull/3694), [#3701](https://github.com/max-sixty/worktrunk/pull/3701), [#3721](https://github.com/max-sixty/worktrunk/pull/3721))++- **One function owns the pre-removal gate**: The dirty-worktree gate, the fsmonitor stop, and the rename into trash were assembled inline by both removal paths, so the default background path never read the module spec written for them. `stage_worktree_removal` now owns all three steps and both paths call it. No behavior change; the gate is now pinned on the default path as well as `--foreground`. ([#3694](https://github.com/max-sixty/worktrunk/pull/3694))++- **`-vv` traces report a normal run's fork count**: `prewarm_at` fast-pathed on a cache key that `-vv`'s own logging setup populated before prewarm ran, so `-vv` skipped the git-config and user-config preloads entirely and every trace overstated a normal run's config forks. Each prewarm thread now gates on the cache it populates. Repositories using `extensions.worktreeConfig` also gained the preload, which they had never received, saving a fork per invocation. ([#3705](https://github.com/max-sixty/worktrunk/pull/3705))++- **The test mock stub is the `wt` binary itself**: `cargo test --test integration` neither built nor rebuilt the separate `mock-stub` helper package, so a fresh tree panicked and a warm one could run a stale stub. `wt` is now linked under each mock's name and dispatches to the ported playback, which cargo rebuilds whenever the integration tests build. The helper package, its dummy test, the `default-members` entry, and nextest's experimental setup script are gone. `wt-perf timeline` also builds `wt` first and takes the artifact path from cargo, rather than measuring whatever stale sibling binary it found. ([#3712](https://github.com/max-sixty/worktrunk/pull/3712))++- **Benchmarks are organized by repository shape**: Groups now select semantic `FixtureRecipe`s and share table-driven cases, keeping separate fixtures only for a controlled contrast, a destructive precondition, or disproportionate setup cost. The real-repository list benchmarks share one pinned `rust-lang/rust` fixture, and the scheduled workflow converts Criterion estimates with `jq` instead of a one-off Python script. ([#3721](https://github.com/max-sixty/worktrunk/pull/3721))++- **`az` and `tea` spans group under `network` in `wt-perf timeline`**: The trace exporter's `network` bucket recognized only `gh` and `glab`, so the other two forge CLIs rendered uncategorized. ([#3689](https://github.com/max-sixty/worktrunk/pull/3689))+## 0.71.0### Improveddiff --git a/Cargo.lock b/Cargo.lockindex 4f8e1a28b..7809bc144 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4810,7 +4810,7 @@ dependencies = [[[package]]name = "worktrunk"-version = "0.71.0"+version = "0.72.0"dependencies = ["ansi-str","ansi-to-html",diff --git a/Cargo.toml b/Cargo.tomlindex 33e8bf095..479cd09c5 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -49,7 +49,7 @@ filterset = "test(/readme_sync/)"[package]name = "worktrunk"-version = "0.71.0"+version = "0.72.0"edition = "2024"rust-version = "1.96"build = "build.rs"diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex 7d5e37896..133928772 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -129,13 +129,32 @@ impl MergeContext {// sync in `advance_target` — git dies trying to cd into it. Refusing// upfront gives a clear answer, and names the `git worktree prune`// that clears the registration.- if let Some(path) = &target_worktree_path- && !path.exists()- {- return Err(GitError::WorktreeMissing {- branch: target_branch,+ if let Some(path) = &target_worktree_path {+ if !path.exists() {+ return Err(GitError::WorktreeMissing {+ branch: target_branch,+ }+ .into());+ }++ // The target gets the same gate the source got above, for a+ // reason the source's comment doesn't cover: `advance_target`+ // syncs the target worktree with `read-tree -m -u`, which refuses+ // an unmerged index but not an open operation whose index is+ // momentarily clean. A target paused mid-rebase or mid-cherry-pick+ // between steps would have its files moved under it, and its+ // `--continue` would then commit the synced tree as the step's+ // result. The fast-forward's former+ // `receive.denyCurrentBranch=updateInstead` refused any unclean+ // target outright, so the plumbing used to supply this; asking+ // directly keeps the guarantee now that the sync is ours.+ if repo.worktree_at(path).operation_in_progress()?.is_some() {+ return Err(GitError::OperationInProgress {+ action: "push".to_string(),+ branch: Some(target_branch),+ }+ .into());}- .into());}// Snapshot target SHA early for TOCTOU safety (used by both strategiesdiff --git a/src/git/error.rs b/src/git/error.rsindex 2958ab1c8..7a95e27f5 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -385,16 +385,22 @@ pub enum GitError {DetachedHead {action: Option<String>,},- /// The worktree is partway through a git operation, so a command that+ /// A worktree is partway through a git operation, so a command that/// rewrites or moves commits (`wt merge`, `wt step rebase`,/// `wt step squash`, `wt step push`) refuses to start.////// Carries no operation and offers no remedy: `git status` names which/// operation is open and how to finish it, so restating either here only- /// adds a line that can drift from what git accepts.+ /// adds a line that can drift from what git accepts. `branch` is what+ /// tells the user *where* to run it — the push's target worktree is not+ /// the one they are standing in, and an unqualified refusal there sends+ /// them to inspect the wrong tree.OperationInProgress {/// The action the user asked for ("merge", "rebase").action: String,+ /// Branch whose worktree holds the open operation, when that isn't the+ /// worktree the command ran in.+ branch: Option<String>,},/// The index still holds unresolved conflicts, so a command that stages on/// the user's behalf (`wt step commit`, `wt step squash`) refuses to run.@@ -657,10 +663,20 @@ impl GitError {None => "Not on a branch (detached HEAD)".to_string(),},- GitError::OperationInProgress { action } => {+ GitError::OperationInProgress {+ action,+ branch: None,+ } => {cformat!("Cannot {action}: a git operation is already in progress")}+ GitError::OperationInProgress {+ action,+ branch: Some(branch),+ } => cformat!(+ "Cannot {action}: a git operation is already in progress in the <bold>{branch}</> worktree"+ ),+GitError::UnmergedPaths { action, files } => {format!("Cannot {action}: {}",diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex f9e32f9a1..e760d3ed5 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1601,6 +1601,7 @@ impl Repository {match self.operation_in_progress()? {Some(_) => Err(crate::git::GitError::OperationInProgress {action: action.to_string(),+ branch: None,}.into()),None => Ok(()),diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex 42b4b42e2..c908e97a0 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -198,6 +198,7 @@ fn git_state_errors_render() {"rebase in progress",GitError::OperationInProgress {action: "rebase".into(),+ branch: None,}.render(),),@@ -205,6 +206,15 @@ fn git_state_errors_render() {"merge in progress",GitError::OperationInProgress {action: "merge".into(),+ branch: None,+ }+ .render(),+ ),+ (+ "operation in progress in the target worktree",+ GitError::OperationInProgress {+ action: "push".into(),+ branch: Some("main".into()),}.render(),),diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rsindex e2b4f7fc1..bcf976bd1 100644--- a/tests/integration_tests/push.rs+++ b/tests/integration_tests/push.rs@@ -424,6 +424,99 @@ fn test_push_dirty_target_overlap_in_untracked_dir(mut repo: TestRepo) {);}+/// A target worktree parked mid-operation refuses the push, whether the+/// operation left HEAD on the branch or detached it.+///+/// `advance_target`'s `read-tree -m -u` refuses an unmerged index, but a+/// stopped operation whose conflict has been staged has a merged one — so+/// without the upfront gate the sync writes the push range into a worktree+/// partway through, and the user's `--continue` commits the synced tree as the+/// operation's result. The conflict is staged at a path the push range never+/// touches, so `ensure_no_target_conflicts` passes and only the operation gate+/// can catch this.+///+/// Both shapes are pinned because they reach the gate differently. A stopped+/// cherry-pick keeps HEAD on the branch, so `worktree_for_branch` finds the+/// worktree directly; a rebase detaches HEAD, and `git worktree list+/// --porcelain` reports that worktree with no branch at all — the lookup+/// succeeds only because `finalize_worktree` backfills the branch from+/// `rebase-merge/head-name`. Were that backfill to stop covering the rebase+/// case, `target_worktree_path` would go `None`, the gate would be skipped, and+/// `advance_target` would return right after its compare-and-swap: the ref+/// moves, the worktree is never synced, and `git rebase --continue` then resets+/// the branch to the rebase result with the pushed commits off it. The+/// fast-forward path this replaced got that refusal from git itself, so the+/// rebase arm is the one place the guarantee rests on a helper of ours.+#[rstest]+#[case::cherry_pick("cherry-pick", ".git/CHERRY_PICK_HEAD")]+#[case::rebase("rebase", ".git/rebase-merge")]+fn test_push_refuses_target_mid_operation(+ mut repo: TestRepo,+ #[case] operation: &str,+ #[case] state_marker: &str,+) {+ let root = repo.root_path().to_path_buf();++ // A side commit that conflicts with main at `conflict.txt`.+ repo.run_git(&["checkout", "-b", "side"]);+ std::fs::write(root.join("conflict.txt"), "side\n").unwrap();+ repo.run_git(&["add", "conflict.txt"]);+ repo.run_git(&["commit", "-m", "Side conflict"]);+ repo.run_git(&["checkout", "main"]);+ std::fs::write(root.join("conflict.txt"), "main\n").unwrap();+ repo.run_git(&["add", "conflict.txt"]);+ repo.run_git(&["commit", "-m", "Main conflict"]);++ // feature descends from main and touches only `feature.txt`.+ let feature_wt = repo.add_feature();++ // Stop the operation in main's worktree, then stage its resolution: the+ // operation stays open while the index goes clean.+ let _ = repo.git_command().args([operation, "side"]).run();+ repo.run_git(&["checkout", "--ours", "conflict.txt"]);+ repo.run_git(&["add", "conflict.txt"]);+ assert!(+ root.join(state_marker).exists(),+ "the fixture must leave a {operation} open in the target worktree"+ );+ // The rebase arm proves nothing about the backfill unless its worktree is+ // really detached, so assert the shape rather than assuming it.+ let head_detached = repo.git_output(&["rev-parse", "--abbrev-ref", "HEAD"]) == "HEAD";+ assert_eq!(+ head_detached,+ operation == "rebase",+ "unexpected HEAD shape after stopping a {operation} in the target worktree"+ );++ let target_before = repo.git_output(&["rev-parse", "main"]);+ let output = repo+ .wt_command()+ .args(["step", "push", "main"])+ .current_dir(&feature_wt)+ .output()+ .expect("failed to run push");++ assert!(+ !output.status.success(),+ "a target worktree mid-operation must refuse the push: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("already in progress") && stderr.contains("main"),+ "the refusal must name the target worktree holding the operation: {stderr}"+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ target_before,+ "the ref must not move"+ );+ assert!(+ !root.join("feature.txt").exists(),+ "the worktree sync must not have run"+ );+}+/// A fast-forward whose target-worktree sync fails is rolled back whole.////// A locked index in the target worktree stands in for a sync failure in thediff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snapindex 27fff03d4..fc78e2dea 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snap@@ -20,6 +20,10 @@ expression: render_cases(cases)[31m✗[39m [31mCannot merge: a git operation is already in progress[39m+## operation in progress in the target worktree++[31m✗[39m [31mCannot push: a git operation is already in progress in the [1mmain[22m worktree[39m+## uncommitted changes[31m✗[39m [31mCannot remove worktree: working tree has uncommitted changes[39m