Repository navigation
Conversation
…#279) Phase 1 of #279. A hidden `worktree claude-hook` reads Claude Code's hook input on stdin (64 KiB cap, TTY refused, zod-validated, name checked as a branch and a path segment), creates `<root>.worktrees/<name>` from the configured source with env copy and install on stderr, reopens an existing one, and prints only the worktree's realpath on stdout. WorktreeRemove still exits 2 until Phase 2. Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist, test (4208 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (install-failure message now names `worktree remove <name> -f`; the postCreate refusal names only `worktree config --approve`). Notes in context/notes.md.
Phase 3 of #279. Patterns in a root `.worktreeinclude` join the env-file and `copy` selection for every command that copies: a file is copied when git lists it as untracked, ignored and matching the patterns (git's own matcher, so `!` works; tracked and un-ignored files never are; node_modules stays excluded). Without the file nothing changes. Docs (env-files guide, project configuration, branch page), README and the worktree skill describe it; the Dox eval baseline was regenerated (MRR 0.719 -> 0.716). Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist, test (4216 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (the `**/` difference from Claude Code was described backwards). Notes in context/notes.md.
…lost (#279) Phase 2 of #279. `worktree claude-hook` now handles WorktreeRemove: it matches `worktree_path` by realpath against this repository's listed worktrees under `<root>.worktrees/`, and removes one with `git worktree remove` (never --force) and `git branch -D`, run from the main checkout, only when it has no uncommitted or untracked changes, nothing unmerged ahead, and no blocking agent session other than the caller's. Otherwise it exits 1 naming the reasons and `worktree remove <branch> -f`. A directory already gone exits 0. The predicate `losesNothingOnRemove` sits beside `isSafeToRemove`; cleanup is unchanged. Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist, test (4249 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (the caller's own session was named as "another session"; a second blocking session behind the caller's own was missed). Notes in context/notes.md.
…mand (#279) Phase 4 of #279. `worktree claude-hook` is listed in `worktree --help`. A new docs page, commands/claude-hook, gives the settings JSON for WorktreeCreate and WorktreeRemove with a raised timeout, both contracts and exit codes, how it differs from Claude Code's defaults, when remove refuses, and the Claude Code pages (as of 2026-11-30) it follows. The commands index, FAQ, cleanup page, README and the worktree skill point at it. Every pinned page count moves 29 -> 30; the Dox routes are regenerated and the eval baseline rewritten (refusal.quiet 1, retrieval.mrr 0.716 -> 0.682 from corpus growth). Gate 1: pnpm check, typecheck (root + docs), build, docs:build, worker:bundle-check, docs:audit-dist (on a temporary commit, as verify.md requires for a new page), test (4249 passed), docs:test (1861 passed), test-markers grep, all exit 0. Gate 2: reviewer subagent, FAIL then PASS WITH NOTES after one loopback (Claude's default removal and the cleanup comparison were described wrongly; a page count left at 29; the page title pulled off-topic queries; two empty table headers). Notes in context/notes.md.
There was a problem hiding this comment.
code-reviewer: minor issues
Adds worktree claude-hook for Claude Code's WorktreeCreate and WorktreeRemove hooks. It also adds .worktreeinclude support to the env-file copy, and updates the docs, skill and page counts to match. The create and remove flows are carefully guarded and well tested, but there are three things to check before merging:
- the
.worktreeincludelisting now asks git for every ignored file in the repository; - the "directory already gone" path depends on a
prunableflag that git sets for exactly that case; - the install's output may reach the hook's stdout.
Separately, context/stack.md's Documentation table (line 89) still says commands/ has 9 pages, which this change makes 10.
Reviewed 4f6b4fd for baldurpan · claude-opus-5-5 · 33 files
| const [matching, ignored] = await Promise.all([ | ||
| gitListFiles(gitRootPath, [`--exclude-from=${WORKTREEINCLUDE_FILE}`]), | ||
| gitListFiles(gitRootPath, ["--exclude-standard"]), |
There was a problem hiding this comment.
Risk: .worktreeinclude lists every ignored file in the repository
gitListFiles(gitRootPath, ["--exclude-standard"]) runs git ls-files --others --ignored --exclude-standard with no include pathspec, only the node_modules exclude. It does this for any repository that has a .worktreeinclude. That enumerates every file under every ignored directory (dist/, target/, .venv/, .next/, build caches) just to intersect with what are usually a handful of matches.
On a large repository this is slow. If run uses execFile's default maxBuffer (1 MiB), it throws, so branch, checkout and the hook fail at the copy step after the worktree exists.
A cheaper intersection: take the --exclude-from=.worktreeinclude candidates (already small) and pass them through git check-ignore -z --stdin. Or pass the candidates as literal pathspecs to the --exclude-standard listing. It is worth checking what maxBuffer run sets.
There was a problem hiding this comment.
Right, and the buffer is the sharper half: run passes no maxBuffer, so it is execFile's 1 MiB. Fixed in 5f42eac. The --exclude-from=.worktreeinclude candidates now go through git check-ignore -z --stdin, which also answers for a file inside an ignored directory. The new real-repo test puts about 1.1 MiB of names under an ignored build/. On the old code it fails with RangeError: stdout maxBuffer length exceeded, and it passes now. A second test covers a match inside an ignored .venv/.
There was a problem hiding this comment.
Fixed in 5f42eac. The candidates from --exclude-from=.worktreeinclude now go through git check-ignore -z --stdin, so nothing lists every ignored file. The 1.1 MiB real-repo test pins it.
| // Nothing is left to delete; the record and branch are for `remove` and | ||
| // `cleanup` to clear. | ||
| if (!worktree.pathExists && !worktree.prunable) { |
There was a problem hiding this comment.
Risk: "Directory already gone" exits 0 only when the entry is not prunable
Git marks a linked worktree prunable exactly when its directory no longer exists (the porcelain prunable gitdir file points to non-existent location). So the usual already-gone case is assumed to skip this early return and fall through to describeRisks.
There, ahead is undefined for a missing path, as the test's own fixture shows. The hook then exits 1 with "could not be counted". That contradicts the docs' "A directory that is already gone exits 0". The test for this case leaves prunable unset, so it cannot catch it.
I could not see how gitGetWorktreeList fills prunable, so check that. If it does follow git, return here on !worktree.pathExists alone, as the comment above it describes, and add a test with prunable: true.
There was a problem hiding this comment.
Checked, and it does not follow git. gitGetWorktrees normalizes the flag (src/lib/git.ts:371): const kept = prunable && onDisk, so prunable is set only when the directory is still there without its .git file (#368). A record whose directory is gone comes back with prunable unset and pathExists: false, so it takes this early return. git.test.ts:1716 pins that: "leaves a prunable record whose directory is gone uncounted and safe" feeds a real prunable gitdir file points to non-existent location line and expects prunable to be undefined. So the hook test's fixture is the shape the real list gives. Nothing changed.
There was a problem hiding this comment.
Agreed: with prunable normalized to prunable && onDisk, a record whose directory is gone has prunable unset and takes the early return, so the fixture matches the real list.
| copy: project.status === "loaded" ? project.config.copy : undefined, | ||
| }); | ||
|
|
||
| const installed = await runInstall(projectPath, undefined); |
There was a problem hiding this comment.
Risk: Install output may reach stdout, which the hook says is the path alone
runInstall(projectPath, undefined) is called without whatever keeps branch --json's stdout clean. If the install inherits stdio outside JSON mode, pnpm install's output lands on the hook's stdout before the path. The docs promise "Stdout is the worktree's real path on one line, and nothing else".
The test mocks runInstall, so it cannot catch this. Check how install.ts routes child output, and make the hook send it to stderr. Then add a test that runs a real (trivial) install step and asserts stdout is the path alone.
There was a problem hiding this comment.
It cannot. runInstall runs each step through runStreaming, which spawns with stdio: ["ignore", 2, 2] (src/lib/cli.ts:239), so the child's stdout and stderr are both our fd 2 whatever mode the caller is in. That is also why branch --json needs nothing extra. install.ts's own "Running … in …" line is console.error. Nothing changed.
There was a problem hiding this comment.
Agreed: runStreaming spawns with stdio: ["ignore", 2, 2], so install output cannot reach stdout.
| const projectPath = await gitCreateWorktree(name, source, { fetch: false }); | ||
| await copyEnvFilesFromRootPath(projectPath, { | ||
| report: "stderr", | ||
| copy: project.status === "loaded" ? project.config.copy : undefined, | ||
| }); |
There was a problem hiding this comment.
Suggestion: A copy failure after creation does not name the kept worktree
The exit-code table says that for exit 1 on create, "A worktree that was made is kept and its path named on stderr", and it lists the copy among the causes. Only the install failure does that. If copyEnvFilesFromRootPath throws (for example the ls-files problem above), the error goes through BaseCommand.catch without projectPath or the worktree remove <name> -f hint.
Wrap the copy the way the install is handled.
There was a problem hiding this comment.
Fixed in 5f42eac. The copy is wrapped like the install, so a failure exits 1 naming the kept path and worktree remove <name> -f, and no install runs after it. A test covers it.
There was a problem hiding this comment.
Fixed in 5f42eac. The copy is now wrapped like the install, exiting 1 with the kept path and the worktree remove <name> -f hint, and the new test covers it.
| try { | ||
| await gitNukeWorktreeCmd(worktree, { cwd: root }); | ||
| } catch (error) { | ||
| this.error( | ||
| `Git refused to remove the worktree ${target} at ${worktree.path}: ${toGitReason(error)}. Fix that, or run \`worktree remove ${target} -f\` to discard it.`, | ||
| { exit: 1 }, |
There was a problem hiding this comment.
Suggestion: Branch-delete failure is reported as git refusing to remove the worktree
gitNukeWorktreeCmd runs worktree remove and then branch -D. If the second step fails, the worktree is already gone, but the message says "Git refused to remove the worktree … run worktree remove … -f to discard it". That sends the user after a directory that no longer exists.
Say instead that the worktree was removed and the branch was not, naming git branch -D <branch>.
There was a problem hiding this comment.
Fixed in 5f42eac. When gitNukeWorktreeCmd throws, the hook asks whether the branch is still checked out anywhere. If not, the worktree went and only branch -D failed. The message then says the worktree was removed and names git branch -D <branch>. A failed lookup keeps the old message. The exit-code table in claude-hook.mdx says so too. The test makes branch -D fail and checks that worktree remove … -f is not offered.
There was a problem hiding this comment.
The new message is in place, but see the comment on line 206: the lookup that picks it probably fails when the hook runs inside the worktree it just removed, which falls back to the old message.
There was a problem hiding this comment.
The lookup's cwd is fixed in 471751d; see the thread on line 206.
There was a problem hiding this comment.
Fixed in 471751d. With the lookup now run from the main checkout, a failed branch -D after a successful worktree remove reaches the new "Removed the worktree … git branch -D" message.
The new 'Worktrees Claude Code keeps' section in cleanup.mdx lifts reworded-cleanup-merged-prs from rank 2 to rank 1, and retrieval MRR from 0.682 to 0.7. Regenerated with pnpm --filter docs evals:baseline.
There was a problem hiding this comment.
code-reviewer follow-up: minor issues
Since the last review, findMergedBase first checks whether merging the branch into the base, in both directions, comes back with the base's own tree (merge-tree --write-tree). It falls back to the commit-tree + git cherry patch comparison only when the merge gives no answer (a conflict, or git older than 2.38); a clean merge that differs from the base is a no. The new logic, its failure paths and the tests for the forward-only, reverse-fails, one-sided-driver and revert cases look correct, and the cleanup and skill docs match the code. No new problems in this push; the five earlier comments, on env.ts and claude-hook.ts, sit in files this push did not touch and stay open.
Earlier comments
- Still open: Risk:
.worktreeincludelists every ignored file in the repository - Still open: Risk: "Directory already gone" exits 0 only when the entry is not
prunable - Still open: Risk: Install output may reach stdout, which the hook says is the path alone
- Still open: Suggestion: A copy failure after creation does not name the kept worktree
- Still open: Suggestion: Branch-delete failure is reported as git refusing to remove the worktree
Reviewed 2d474d8 (changes since 4f6b4fd) for baldurpan · claude-opus-5-5 · 5 files
- .worktreeinclude: filter its candidates through git check-ignore instead of listing every ignored file, which overflowed run's 1 MiB buffer on a repository with a large ignored directory - WorktreeCreate: a failed copy names the kept worktree, as the exit-code table says, the same as a failed install - WorktreeRemove: when only the branch delete fails, say the worktree went and name the git branch -D that finishes it - context/stack.md: commands/ has 10 pages
|
On the review body: |
There was a problem hiding this comment.
code-reviewer follow-up: minor issues
Since the last review, .worktreeinclude candidates are filtered through git check-ignore -z --stdin instead of being intersected with a listing of every ignored file. A copy failure in the hook now names the kept worktree, and a failed branch -D after removal gets its own message. The check-ignore change and the copy wrapping are sound and tested against the failure they fix. The branch-delete message probably won't fire in the hook's usual setting, because the checkout lookup appears to run from the directory that was just deleted.
Earlier comments
- Fixed; yours to resolve: Risk:
.worktreeincludelists every ignored file in the repository - Answered; yours to resolve: Risk: "Directory already gone" exits 0 only when the entry is not
prunable - Answered; yours to resolve: Risk: Install output may reach stdout, which the hook says is the path alone
- Fixed; yours to resolve: Suggestion: A copy failure after creation does not name the kept worktree
- Still open: Suggestion: Branch-delete failure is reported as git refusing to remove the worktree
Reviewed 5f42eac (changes since 2d474d8) for baldurpan · claude-opus-5-5 · 6 files
| const branchFreed = | ||
| worktree.branchName !== DETACHED_LABEL && | ||
| (await gitFindBranchCheckout(worktree.branchName).then( |
There was a problem hiding this comment.
Risk: Branch lookup likely runs from the just-deleted worktree, so the new message rarely fires
gitNukeWorktreeCmd is given { cwd: root } because, as the doc comment above says, the hook usually runs inside the worktree it removes. gitFindBranchCheckout(worktree.branchName) gets no cwd, though.
In exactly the case this branch handles, worktree remove succeeded and branch -D failed, so the process's cwd no longer exists. A git child spawned there fails with Unable to read current working directory. The () => false fallback then turns that into the old "Git refused to remove the worktree … run worktree remove … -f" message, which is what T5 was about. The unit test mocks gitFindBranchCheckout, so it cannot see this.
I could not see gitFindBranchCheckout's implementation; if it already pins its cwd to the main checkout, ignore this. Otherwise, give it a cwd option and pass root, or check from root directly. For example, git -C <root> worktree list --porcelain and look for the branch, or test whether worktree.path still exists, which is the more direct signal that the first step went through.
There was a problem hiding this comment.
Right. gitFindBranchCheckout runs git worktree list with no cwd, and gitGetAbsoluteWorktreesPath before it does the same. Fixed in 471751d: the hook now runs git worktree list --porcelain with { cwd: root } itself and looks for branch refs/heads/<name>. I didn't go by whether worktree.path exists: when the .git file is missing, the prune that removes the record leaves the directory where it is, so that signal would be wrong there. The test now asserts the listing runs from the main checkout.
There was a problem hiding this comment.
Fixed in 471751d. The hook now runs git worktree list --porcelain with cwd: root and checks for branch refs/heads/<name>, so the removed worktree as cwd no longer matters. The test asserts the cwd.
There was a problem hiding this comment.
code-reviewer follow-up: looks good
Since the last review, the branch lookup after a failed removal runs git worktree list --porcelain from the main checkout instead of the process's cwd, which may already be deleted. It then looks for the branch's ref line. The test now checks that the listing runs with { cwd: main }, and the refused-removal test feeds a listing that still shows the branch. Both earlier comments are resolved, and I found nothing new.
Earlier comments
- Fixed; yours to resolve: Suggestion: Branch-delete failure is reported as git refusing to remove the worktree
- Fixed; yours to resolve: Risk: Branch lookup likely runs from the just-deleted worktree, so the new message rarely fires
Reviewed 471751d (changes since 5f42eac) for baldurpan · claude-opus-5-5 · 2 files
Closes #279
Adds
worktree claude-hook, the command behind Claude Code'sWorktreeCreateandWorktreeRemovehooks, soclaude --worktree, subagent isolation and background sessions use this tool's worktrees.Phases landed (plan is the body of #279):
WorktreeCreate(67e52b4)WorktreeRemovedeletes only when nothing would be lost (6b6ee00).worktreeincludematches are copied (d435cd9)Release note:
.changeset/hooked-worktrees.md, minor. It ships on the next release pull request, not on this merge.Owner checks filed from the plan's §9, none a defect: #384, #385, #386, #387, #388, #389, #390, #391. Q5 answered (branch stays
name), Q9 waived.