Repository navigation
docs(hook): say that post-* hooks from the two sources run concurrently - #4020
Conversation
A hook batch splits into one detached pipeline per source so a user-hook failure can't abort project hooks. The parent spawned all of them at once, so user and project pipelines ran concurrently in the same worktree, against one git state. Two `git pull`s there append to each other's `FETCH_HEAD` and both die with `Cannot rebase onto multiple branches` — reproducible 20/20 with two concurrent pulls in a scratch clone. A `post-merge` that pulls and pushes is a common enough shape that this left `wt merge` printing success with the target still unpushed, its only trace a line in `.git/wt/logs/<branch>/*/post-merge/*.log`. The parent now spawns only the first pipeline, handing it the whole queue on stdin; each runner spawns the next when it finishes, whatever its own outcome. Each spec keeps its own process and its own `runner.log`, so the failure isolation is unchanged, and the order `wt hook --help` documents under "Project vs user hooks" — project hooks after user hooks — now holds for background hooks too. Only pipelines sharing a worktree are queued; distinct worktrees still start in parallel. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01YXhA2XGssc6fGyTkC7oBtz
The payload was a list the runner popped from, so both ends needed a guard against an empty one that neither could produce. A head plus the rest says the same thing in the type. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01YXhA2XGssc6fGyTkC7oBtz
worktrunk-bot
left a comment
There was a problem hiding this comment.
Chaining the batch reintroduces the failure it fixes, in two shapes I reproduced against main. Both are about the queue being wider than the collision it guards: a batch is not one worktree, and pipelines behind the head are not short-lived.
1. wt merge now silently drops post-merge when a post-commit hook exists. wt merge uses one announcer for post-commit, post-remove, post-switch and post-merge (let mut announcer = HookAnnouncer::new(repo, false) in src/commands/merge.rs, with the comment "One announcer for the whole command's background hooks"). post-commit is registered from CommitOptions::commit with env.context(yes), whose worktree_path is the invoking worktree; the other three are rooted at destination_path. finish_after_merge removes the feature worktree before announcer.flush(). So the chain's head is a spec whose worktree_path no longer exists, Repository::at fails ahead of run_spec, the ? returns, and the tail is never handed on.
2. A long-lived hook in an earlier pipeline starves every later one. post-start is documented for exactly that: "Runs once when a new worktree is created, in the background: dev servers, long builds, file watchers, copying caches", and tips & patterns recommends server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}", which runs for the worktree's lifetime. wt switch --create registers post-switch and post-start into one announcer, and each splits user/project, so a user-config dev server now blocks the project pipeline forever.
Reproduction — main vs this branch, same scratch repos
Built wt from 0a78f99 and from base 7d08f67 (the two source files reverted, everything else identical).
(1) Scratch repo, feature worktree with an uncommitted change, user config with [post-commit] mark and [post-merge] mark each writing a marker file, then wt merge main --yes:
base: post-merge.txt # post-merge ran
PR: (no files) # nothing ran
The only trace on this branch is .git/wt/logs/feature/user/post-commit/runner.log:
✗ failed to open repository for pipeline
fatal: not a git repository (or any of the parent directories): .git
On base the post-commit pipeline fails the same way — its worktree is gone either way — but it fails alone, because the parent had already spawned post-merge. That is the isolation the chain removes.
(2) Project config [post-start] build = "echo … > marker", user config [post-start] server = "sleep 300", then wt switch --create feature --yes:
base: project.txt # project post-start ran alongside the sleep
PR: (no files) # blocked behind the sleep
CI is green on this because the existing coverage for the shape in (1) is announce-only — test_merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge and its --squash sibling snapshot the combined Running … line, not whether the hooks ran. The new test_project_post_merge_runs_after_user_pipeline passes --no-remove and configures no post-commit, so it doesn't reach either shape.
I don't think the fix is a patch to the hand-off. The premise the chain rests on — "A batch covers one worktree, since a post-* hook runs where the command leaves the user, so chaining the batch and excluding per worktree are the same thing" — is false for wt merge, and even where it holds, "same worktree" isn't "must not overlap": two dev servers in one worktree are the documented pattern. What actually collides is two hooks driving the same git state in the same worktree, which is a narrower set than a batch. Scoping the exclusion to that — chaining only pipelines that share a worktree_path, and only for the hook types where a git-state collision is real — would close the post-merge race without serializing post-start.
Also worth noting: codecov/patch is currently failing on this PR.
Both ends of the chain were checking for an empty queue: the parent before spawning, where a batch can never be empty, and the runner before handing on. One guard inside `spawn_pipeline_queue` covers both, and the case it guards is the ordinary one — a single-source batch reaches it with nothing left to hand on. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01YXhA2XGssc6fGyTkC7oBtz
"Execution order: project after user" held for `pre-*`, which run as one blocking pipeline, and not for `post-*`, where each source is its own detached pipeline. Nothing but the table said otherwise, so a hook that depended on the order looked supported. Sequencing them instead was the other way to close the gap, and it breaks two things: `post-start` is documented for dev servers, so a user hook that never exits would block the project's, and a batch spans the invoking and destination worktrees, so a chain drops every hook behind a head whose worktree the command already removed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01YXhA2XGssc6fGyTkC7oBtz
worktrunk-bot
left a comment
There was a problem hiding this comment.
The reversal answers the design objection from the previous review — the two shapes I reproduced there (wt merge dropping post-merge behind a removed-worktree head, and a long-lived post-start starving the pipeline behind it) are both gone with the code reverted, and recording the constraint in CLAUDE.md is the right way to stop it being re-derived. I re-verified the behavioural claims against the code and they hold: prepare_and_check orders user steps before project steps and every pre-* call site passes FailureStrategy::FailFast, so "user commands first, and a failure there skips the project's" is exact; run_hooks_background's spawn loop is what makes the post-* half true; and the post-commit anchor claim checks out (merge.rs builds one announcer, while handlers.rs roots both remove_ctx and switch_ctx at ctx.main_path).
Two accuracy nits in the new prose, both inline.
Applying the src/cli/mod.rs suggestion leaves the three generated mirrors stale — cargo test --test integration test_docs_are_in_sync regenerates them.
The multi-worktree case is `wt merge`'s batch, not every batch, and "no order across sources" is a `post-*` statement sitting one line below the `pre-*` order it appeared to contradict. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01YXhA2XGssc6fGyTkC7oBtz
… its worktree (#4026) `wt merge` prints `◎ Running post-commit: …` and then spawns that pipeline into a path the removal has already emptied, so a `post-commit` hook can't be relied on to do what it says. Nothing reports this, and two doc lines promised the behavior that doesn't happen. `post-commit` is the only hook in the merge's background batch anchored on the feature worktree — `post-merge`, `post-switch` and `post-remove` all anchor on the destination. `HookAnnouncer` flushes every pending pipeline once at the end of the command, which is after `finish_after_merge` has removed that worktree. What the runner then finds depends on where the worktree lived, because the fast removal path renames it into `.git/wt/trash/` and leaves an empty placeholder at the original path (`changed_directory: true`, so the shell's `$PWD` stays valid), torn down a second later by the detached `sleep 1 && rmdir`. `run_pipeline` calls `Repository::at` on that placeholder, and git discovery walks up from it: - **Worktree outside the repo** (the default `../{{ repo }}.{{ branch }}`): no git ancestor, so the runner logs `failed to open repository for pipeline` to `.git/wt/logs/<branch>/<source>/post-commit/runner.log`, which nothing reads back. The hook doesn't run. - **Worktree nested inside the repo** (`worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"`, one of the config page's own examples): discovery resolves to the **primary** worktree, `Repository::at` succeeds, and the steps do run — with their cwd set to the placeholder `rmdir` unlinks a moment later, and any `git` inside them resolving against the primary worktree. It's a regression, not a hook that never worked: #1679 added `post-commit` and it fired for five weeks, until #2457 collapsed the merge's two or three `◎ Running …` lines into one. That was a cosmetic change, and deferring the spawn to a single end-of-command flush moved it past the removal. Documented rather than fixed, deliberately. The commit `post-commit` would fire on is squashed and rebased before the merge lands; `pre-remove` already covers work that must finish in the feature worktree, blocking removal until it does; and spawning at commit time only narrows the window, since `git worktree remove` succeeds against a live cwd. `post-commit` still runs properly wherever the worktree survives — `--no-remove`, merging on the target branch, merging from the primary worktree — and on `wt step commit` / `wt step squash`. So this adds the explanation at the `HookAnnouncer` construction in `handle_merge`, and corrects what the docs claimed: - The merge pipeline's step 1 said "Post-commit hooks run in background" flatly. - The hook page said "During `wt merge`, hooks run in this order: pre-commit → post-commit → pre-merge → pre-remove → post-remove + post-merge" — wrong twice, since the `post-*` hooks don't run in sequence either (#4020 corrected that one row above). It now gives the blocking order, says the `post-*` hooks start together in the worktree each is anchored on, and points at `pre-remove` or `--no-remove`. - `test_merge_squash_combines_post_commit_…` said the merge "fires post-commit"; it announces it. Both it and its auto-commit sibling now say the announce line is all they pin. No behavior change. <details> <summary>Reproduction</summary> A scratch repo with a `post-commit` hook, a feature worktree with one commit and one uncommitted file, then `wt merge main --yes`. Every case prints `◎ Running post-commit: mark (user)`: | Layout | Flags | Outcome | |--------|-------|---------| | external (`../{{ repo }}.{{ branch }}`) | default (squash) | hook doesn't run | | external | `--no-squash` | hook doesn't run | | external | `--no-remove` | runs correctly | | nested (`{{ repo_path }}/.worktrees/{{ branch }}`) | default (squash) | runs in the doomed placeholder | The external removing cases leave this in `.git/wt/logs/feat/user/post-commit/runner.log`: ``` ✗ failed to open repository for pipeline fatal: not a git repository (or any of the parent directories): .git ``` The nested case leaves an empty `runner.log` and the hook's own output shows where it landed — `pwd` is the removed worktree's path, while `git rev-parse --show-toplevel` from inside it answers with the primary worktree: ``` cwd=/…/repo/.worktrees/feat toplevel=/private/…/repo ``` The commit itself is made in every case — `Changes to dirty.txt` reaches `main`. </details> > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
worktrunk 0.77.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 list` sizes and aligns its columns to the terminal width**: one long branch name no longer sizes the Branch column for every row — it caps at 32 characters and elides, so a narrow terminal keeps its other columns instead of degenerating into a branch list. `Remote⇅` stops holding blank space open in a repo with no remote, and alignment now follows the value type. `--format=json` still carries the whole name. ([#3998](max-sixty/worktrunk#3998)) - **`wt list` names what it hid and marks detached worktrees**: the summary reads `hidden: Path, Commit` instead of counting columns, a detached worktree shows `⊘` rather than borrowing `⚑`, and a prunable row leaves its cells blank instead of showing loading dots that never resolve. ([#3998](max-sixty/worktrunk#3998)) - **`wt list --format=json` gains a `marker` field and stops reporting `detached` twice**: the branch marker set by `wt config state marker` is now readable without parsing it out of `symbols`, and `state` no longer reports a detached worktree as `branch_worktree_mismatch` — the sibling `detached` boolean carries it. ([#3998](max-sixty/worktrunk#3998)) - **`wt list --format=json` now defaults to schema 2**: callers get the envelope with repository metadata and orthogonal per-item facts without configuring `[list] json-schema`. `wt list statusline --format=json` follows the same key. Set `json-schema = 1` to retain the original bare-array format. (Breaking.) ([#4038](max-sixty/worktrunk#4038)) - **`wt config show` fails on a broken config**: it exits 1 on an unreadable or invalid config, an invalid `[list] columns`, or an invalid `approvals.toml`. Unknown keys and deprecations stay warnings and still exit 0. A new `APPROVALS` section counts project commands awaiting approval. (Breaking: it always exited 0 before.) ([#3999](max-sixty/worktrunk#3999)) - **Config migration output names its destination**: `wt config update --output <path>` writes the migration artifact to that file instead of applying it in place, and `--output=-` writes it to stdout. Output mode includes project config when run from a linked worktree. (Breaking: `--print` was removed.) ([#4021](max-sixty/worktrunk#4021)) - **Pi joins the agent integrations**: `wt config plugins pi install` writes an activity hook to `~/.omp/agent/hooks/pre/worktrunk.ts`, so Pi sessions show 🤖/💬 markers in `wt list` like Claude Code, Codex, OpenCode, and Gemini. `$PI_CONFIG_DIR`, `$PI_CODING_AGENT_DIR`, and named `$OMP_PROFILE`/`$PI_PROFILE` profiles are honored. [Docs](https://worktrunk.dev/claude-code/) ([#3594](max-sixty/worktrunk#3594), thanks @adity982, and @ortonomy for the request) - **`wt config plugins codex install` installs the plugin too**: it previously registered the marketplace and left you to run `/plugins` in Codex yourself. Uninstall follows for both Codex and Claude Code, removing the plugin and then the marketplace, so the two commands are inverses. (Breaking: Codex uninstall previously left an installed plugin alone; Claude uninstall now also removes the marketplace.) ([#4019](max-sixty/worktrunk#4019)) - **`wt step copy-ignored` says whether it reflinked or copied**: the summary now reads `(reflinked, no extra disk)`, `(full copy)`, or a partial count, so the same `29.5 GB` line distinguishes a free copy from one that actually wrote the bytes. `--format=json` gains `reflinked` and `written`; a `--dry-run` plan no longer reports `files`/`bytes`. ([#4025](max-sixty/worktrunk#4025)) - **`wt config update` removes keys its destination cannot hold**: migrating `[select]` or `[commit-generation]` drops keys the new section has no field for, reporting each one. Otherwise the key landed at a path the user never typed and warned on every command, with no way to clear it. ([#3994](max-sixty/worktrunk#3994)) ### Fixed - **A failed `wt switch pr:<n>` against a fork no longer deletes a branch it didn't create**: the rollback force-deleted the branch on any setup error, including the one case where the branch wasn't its own — a `pre-switch` hook or a concurrent session claiming the name in the window after the forge answered. Branch and worktree are now created in one `git worktree add -b`, which writes nothing when the name is taken. ([#3984](max-sixty/worktrunk#3984)) - **Codex on Windows: the activity hooks no longer fail on every event**: each hook led with a bare `bash`, which `cmd.exe` resolves to the WSL launcher rather than Git Bash, so every event raised a `Hook failed` banner. Hooks now run `wt.sh` through a shim that finds Git Bash by path. ([#4008](max-sixty/worktrunk#4008), fixes [#4007](max-sixty/worktrunk#4007), thanks @McNultyyy for reporting and diagnosing) - **Templates leave `branch` unset in a detached worktree**: aliases and hooks rendered `{{ branch }}` as the literal `HEAD`, which git resolves, so an unguarded template ran against the wrong ref — the reported case ended in `git push origin --delete HEAD`, which git refused. `base` and `target` follow. (Breaking: an unguarded `{{ branch }}` now errors.) ([#4010](max-sixty/worktrunk#4010), fixes [#4009](max-sixty/worktrunk#4009)) - **The OpenCode plugin loads under OpenCode 2**: OpenCode 2's loader dropped the old bare-function export silently, so activity markers stopped appearing. The plugin now exports one object carrying both the v2 `setup` and v1 `server` entry points, and spawns `wt` through `node:child_process` rather than the Bun shell. Re-run `wt config plugins opencode install` to pick it up; the one file covers OpenCode 2 and OpenCode 1.16 or later. ([#4018](max-sixty/worktrunk#4018), thanks @pragmaticivan for the request) - **`wt step commit --branch` builds its prompt from the worktree being committed**: prompt-building git plumbing ran in the invoking worktree, so with nothing staged there the generated message described none of the changes it committed. `wt step relocate --commit` had the same bug, and `--dry-run`/`--show-prompt` now preview the worktree `--branch` names. ([#3996](max-sixty/worktrunk#3996)) - **LLM commit messages keep diffs for quoted paths**: a file whose name git quotes in the `diff --git` header — any non-ASCII name under the default `core.quotePath` — had its whole diff section dropped from the prompt once the diff exceeded the 100 KB budget. ([#4041](max-sixty/worktrunk#4041)) - **An unparsable user config is reported, not a panic**: `wt config show --format=json` and `--full`, plus `wt step prune`, `relocate`, `eval`, and `for-each`, panicked on a debug build and printed a bare `✗ Command failed` on a release one. They now report `✗ Failed to load config` with the parser's caret diagram. ([#4002](max-sixty/worktrunk#4002)) - **`wt switch --execute` names the directory the program actually starts in**: the `Executing (--execute) @ …` header rendered the worktree the background hooks run in, not the program's own directory — which differs under `--no-cd` or a switch from a subdirectory. The path is omitted when the shell already stands there. ([#4043](max-sixty/worktrunk#4043), fixes [#4042](max-sixty/worktrunk#4042), thanks @yajo for reporting) - **`wt config plugins claude|codex uninstall` is safe to re-run**: removing an already-absent marketplace reported a failure, and a Claude uninstall that removed the plugin and then failed left the marketplace with no way to clear it. Both now finish a half-done uninstall and succeed when there is nothing left to remove. ([#4033](max-sixty/worktrunk#4033), [#4034](max-sixty/worktrunk#4034)) - **`wt config state marker` set and clear no-op outside a git repository**: they exited 1 with a git error, so an agent plugin running outside a repository printed one every turn (the hook's `|| true` kept the session going). ([#3981](max-sixty/worktrunk#3981), thanks @mahirhir) - **`wt list` produces output in a bare repo with no worktrees**: it printed nothing at all and exited 0. It now reports `○ No worktrees` with a hint, `--branches` lists the branches, and `--format json` emits the envelope with an empty `items`. ([#3992](max-sixty/worktrunk#3992)) - **`wt list` warns when it can't parse the project config** rather than ignoring it silently; the listing still succeeds. ([#3993](max-sixty/worktrunk#3993)) - **Relayed command output no longer prints ahead of the delayed-stream progress line**, and delayed-stream output routes through anstream so color is stripped consistently when redirected. ([#4037](max-sixty/worktrunk#4037), [#3995](max-sixty/worktrunk#3995)) - **A hook filter that matches nothing names the unconfigured source**, rather than reporting no match without saying which source was empty. ([#3997](max-sixty/worktrunk#3997)) ### Documentation - **`wt hook` says that `post-*` hooks from the two sources run concurrently**, so dependent commands belong in one source; `wt merge` records that `post-commit` can't run when the merge removes the worktree it anchors on. ([#4020](max-sixty/worktrunk#4020), [#4026](max-sixty/worktrunk#4026)) - **`wt step` help pages describe what the commands actually do**: `wt step prune` says it removes br See merge request: Harmonybrew/homebrew-core!18763
wt hook --helpsaid project hooks run "after user hooks". That holds forpre-*, which run as one blocking pipeline, and not forpost-*, where each source gets its own detached pipeline and both start at once. Nothing else in the docs said so, so a hook written against the stated order looked supported when it wasn't — twopost-mergehooks that each rungit pullin the merge destination append to one another'sFETCH_HEAD, both die withfatal: Cannot rebase onto multiple branches, andwt mergereports success with the target unpushed.This corrects the table and adds a paragraph saying what each kind actually does, including that commands which depend on each other belong in one source.
Why the docs moved rather than the code
Sequencing the pipelines was the other way to close the gap, and this branch tried it first. Two things break:
post-startis documented for dev servers andwt step tether. With a userpost-startofsleep 300standing in for one, the project'spost-startmarker lands within 6s onmainand never lands when the pipelines are chained.A batch also spans two worktrees:
post-commitanchors on the invoking worktree,post-remove/post-switch/post-mergeon the destination. The invoking worktree is removed before the hooks run, so chaining drops everything behind that head. Onwt merge main --no-squashwith a dirty worktree and all four hooks configured,mainruns post-remove, post-switch and post-merge; the chained version ran only post-switch.The race the sequencing was aimed at is real but narrower than the cure: it needs two hooks touching one worktree's git state, which the docs now tell users to avoid by keeping dependent commands in one source.
CLAUDE.mdrecords the constraint so the fix isn't re-attempted.