modified
--- a/worktrees.md +++ b/worktrees.md @@ -86,7 +86,7 @@ ## Isolate subagents with worktrees -Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or make the isolation permanent for a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to its frontmatter. This subagent in `.claude/agents/` always runs in its own worktree: +Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or add `isolation: worktree` to the frontmatter of a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>). This subagent in `.claude/agents/` sets the field: --- name: refactorer @@ -171,21 +171,14 @@ ### Reuse a worktree name -If a worktree with the name you pass to `--worktree` already exists, Claude Code opens it instead of creating a new one. If Claude Code stops with an error containing `belongs to a different repository` or `is a leftover worktree`, see The worktree directory `belongs to a different repository`. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: +If a worktree with the name you pass to `--worktree` already exists, Claude Code opens it instead of creating a new one. If Claude Code stops with an error containing `belongs to a different repository` or `is a leftover worktree`, see The worktree directory `belongs to a different repository`. Claude Code reopens the worktree at its old tip or resets it to the repository’s default branch. A reset needs the default `"fresh"` base and all of these conditions: * The [sandbox](</docs/en/sandboxing#filesystem-isolation>) isn’t restricting file writes in your session, and neither the worktree’s nor the main checkout’s `.claude` settings files enable the sandbox. - * The worktree has no uncommitted changes or untracked files. + * The worktree has no uncommitted changes or untracked files that git reports. Gitignored files don’t count. * It is still on the branch Claude Code created for it. - * It has no commits of its own, or its pull request or merge request was merged and its remote branch deleted. - -Claude Code detects the merged case from git state alone: the remote branch the worktree pushed to no longer exists, and every commit in the worktree is already on the default branch. In every other case, Claude Code reopens the worktree at its old tip: - - * The worktree or session fails any of the conditions. - * Claude Code can’t verify the worktree’s state. - * `worktree.baseRef` is `"head"`. - * The name is a pull request or merge request reference. - -If you use the sandbox with the `"fresh"` base, run `git fetch origin`, then pass a new name to `--worktree` to start from the latest default branch. + * It has no commits of its own, or its work was merged: its remote branch is deleted and its non-merge commits are already on the default branch. + +Claude Code skips the reset in other cases too, such as when it can’t verify the worktree’s state or the name is a pull request or merge request reference. If you use the sandbox with the `"fresh"` base, run `git fetch origin`, then pass a new name to `--worktree` to start from the latest default branch. ### Replace worktree creation with a hook
modified
--- a/worktrees.md +++ b/worktrees.md @@ -44,7 +44,7 @@ ## Clean up worktrees -When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. These rules apply to worktrees Claude created with git. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. +When you exit an interactive session in a worktree Claude created with git, Claude checks for work: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. Your gitignored files, such as `.env`, don’t count, so you can lose them at exit. Copy out files you need before exiting. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>). * **Claude Code finds another session in the worktree** : the worktree and branch stay even if you choose removal. Follow the `Worktree kept at` message * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later @@ -60,7 +60,7 @@ ### Resume without `--worktree` -When you resume a session that ended isolated in its worktree without exiting it, Claude Code returns the session there and keeps it isolated. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: +When you resume a session that ended isolated in its worktree and that you didn’t exit, Claude Code returns the session to that worktree and keeps it isolated. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: * **Launch directory** : resume with `--resume` from the main checkout or another directory of the repository. Claude Code re-enters a worktree it created with git under `.claude/worktrees/` even when you launch from inside it. When you launch from inside any other worktree, Claude Code re-enters it only if it can vouch for it from there: a worktree that is its own repository, one without git metadata, or a launch from a subdirectory of a worktree you created with `git worktree add` declines, so launch those from the main checkout. * **`--continue`** : Claude Code picks the most recent session recorded under the directory you launch from. @@ -97,15 +97,20 @@ Apply the requested refactor across every affected file, then run the tests and report the results. -When a subagent finishes, Claude Code keeps the worktree if git shows changed files, untracked files, or new commits there. Otherwise, Claude Code can remove the worktree right away. A kept worktree stays on disk until the periodic sweep can remove it without losing work. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. +If your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created the subagent’s worktree, see [WorktreeRemove](</docs/en/hooks#worktreeremove>). Otherwise, Claude Code checks the worktree with git when the subagent finishes: + + * **Changed files, untracked files, or new commits** : the worktree stays until it qualifies for the periodic sweep. + * **A clean`git status` and no new commits**: Claude Code can remove the worktree right away. + +Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. ### Clean up subagent and background-session worktrees Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in cases such as these: - * The worktree still holds work: changed or untracked files, or unpushed commits. + * The worktree still holds work: changed or untracked files, or unpushed commits. Your gitignored files don’t count, so copy out any you need. * A checked-out submodule in the worktree holds changed or untracked files, or Claude Code can’t inspect the worktree’s submodules. This check requires Claude Code v2.1.274 or later. - * One of the four cases that also block worktree creation applies: Claude Code can’t determine which filter drivers the repository config defines, or finds a setting there it can’t switch off. + * One of the git config errors that block worktree creation applies. * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree with `git worktree add` outside `.claude/worktrees/`. @@ -119,7 +124,7 @@ ### Choose the base branch -New worktrees branch from the repository’s default branch, so most sessions don’t need this setting. Set `worktree.baseRef` in [settings](</docs/en/settings-reference#worktree>) to branch from your current work instead. The setting accepts two values: +New worktrees branch from the repository’s default branch. Set `worktree.baseRef` in [settings](</docs/en/settings-reference#worktree>) to branch from your current work instead. The setting accepts two values: * `"fresh"` (default): branch from the repository’s default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote. * `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. @@ -261,7 +266,7 @@ ### Git LFS files are pointer files in a worktree Claude Code created -If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In four rare cases, Claude Code creates no worktree at all: it can’t tell which filter drivers the repository’s config defines, or it finds a setting there it can’t switch off. Match the error to its fix: +If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. If worktree creation fails with one of these errors, match the error to its fix: * **`Could not read the repository git config to neutralize filter drivers`** : Claude Code couldn’t read the repository’s `.git/config`, for example because of its permissions. Fix that and retry. * **`The repository git config defines a filter driver whose name cannot be neutralized (contains "=" or a newline)`** : rename or remove that filter driver in `.git/config` and retry.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -97,7 +97,7 @@ Apply the requested refactor across every affected file, then run the tests and report the results. -Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. +When a subagent finishes, Claude Code keeps the worktree if git shows changed files, untracked files, or new commits there. Otherwise, Claude Code can remove the worktree right away. A kept worktree stays on disk until the periodic sweep can remove it without losing work. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. ### Clean up subagent and background-session worktrees @@ -111,7 +111,7 @@ #### Worktree locks and manual removal -While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. +Claude Code takes a `git worktree lock` on the worktree it creates for an agent, so that concurrent cleanup can’t remove it during the agent’s first run, before any [resume](</docs/en/sub-agents#resume-subagents>). The worktree Claude Code created for a backgrounded session has the same lock while the session runs, so the sweep keeps the worktree and `git worktree remove` refuses it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. ## Customize worktree creation
modified
--- a/worktrees.md +++ b/worktrees.md @@ -48,13 +48,17 @@ * **Claude Code finds another session in the worktree** : the worktree and branch stay even if you choose removal. Follow the `Worktree kept at` message * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later - * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch. To return later, run the `claude --worktree <name> --resume` command that Claude Code prints on exit. Removing deletes the worktree directory and its branch, along with all the work in them + * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them * **Another branch is checked out** : if the worktree is on a branch other than its own that has commits past the worktree’s starting commit, Claude prompts you to keep or remove the worktree. Either answer keeps that other branch and its commits. Removing deletes the worktree directory and the worktree’s own branch, the one Claude created with it * **The worktree’s state can’t be verified** : when Claude Code can’t count the worktree’s changes or can’t inspect its submodule checkouts, it prompts you rather than removing the worktree automatically. The prompt names what it couldn’t check Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link. ## Resume a worktree session + +To return to a worktree you kept, run `claude --worktree <name> --resume <session-id>` from the main checkout, using the session ID printed on exit. For `<name>`, type the folder name under `.claude/worktrees/` with `/` in place of any `+`. + +### Resume without `--worktree` When you resume a session that ended isolated in its worktree without exiting it, Claude Code returns the session there and keeps it isolated. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: @@ -64,6 +68,8 @@ * **Deleted worktree** : if the worktree directory no longer exists, Claude Code resumes the session in the directory you launched Claude from. It tells you the worktree is gone and clears the session’s worktree binding. Before v2.1.212, a non-interactive resume stayed in the starting directory and `ExitWorktree` reported that there was no active worktree session to exit. + +### Transcript location When Claude enters or exits a worktree that Claude Code created with git, the transcript follows. Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. @@ -101,9 +107,7 @@ * A checked-out submodule in the worktree holds changed or untracked files, or Claude Code can’t inspect the worktree’s submodules. This check requires Claude Code v2.1.274 or later. * One of the four cases that also block worktree creation applies: Claude Code can’t determine which filter drivers the repository config defines, or finds a setting there it can’t switch off. * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. - * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. - -Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. + * You created the worktree with `git worktree add` outside `.claude/worktrees/`. #### Worktree locks and manual removal @@ -140,11 +144,11 @@ claude --worktree "#1234" -Claude Code reads only the number from the URL. It always fetches from your repository’s `origin` remote, and picks the fetch path by `origin`’s host: +Claude Code ignores the host and repository in a URL you pass, and picks the fetch path by `origin`’s host: * **github.com** : fetches `pull/<number>/head` * **gitlab.com** : fetches `merge-requests/<number>/head` - * **GitHub Enterprise, self-managed GitLab, or any other host** : tries `pull/<number>/head` first, then `merge-requests/<number>/head` + * **GitHub Enterprise, self-managed GitLab, or any other host** : uses `pull/` for a pull request URL, `merge-requests/` for a merge request URL, and whichever exists for a `#` number. If both exist at different commits, follow the `Cannot use PR/MR #<number>` message. This fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails instead and Claude Code exits with an `Error creating worktree: Failed to fetch PR/MR #<number>` message. A key that `ssh-agent` holds still works, so load your key there and run `git fetch` once by hand to record a new host before you start.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -95,7 +95,7 @@ ### Clean up subagent and background-session worktrees -Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in these cases: +Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in cases such as these: * The worktree still holds work: changed or untracked files, or unpushed commits. * A checked-out submodule in the worktree holds changed or untracked files, or Claude Code can’t inspect the worktree’s submodules. This check requires Claude Code v2.1.274 or later. @@ -187,7 +187,7 @@ A worktree gets its own files and branch, but it shares the following with the main checkout: * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory. With the [sandbox](</docs/en/sandboxing#filesystem-isolation>) enabled, commands such as `git commit` work in a session at the worktree’s root, which is where `--worktree` starts one. By default, they [fail with an `index.lock` error if you run `claude` in a subdirectory of the worktree](</docs/en/sandboxing#git-index-lock>). - * **Plugins** : plugins installed at [project scope](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. + * **Plugins** : plugins installed at [project scope](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) from the main checkout also load in worktrees of the same repository. * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`. The rule applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. See [where approvals are saved](</docs/en/permissions#permission-system>). * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -9,7 +9,7 @@ ## Start Claude in a worktree -Pass `--worktree` or `-w` with a name to create an isolated worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<name>/` at your repository root, on a new branch named `worktree-<name>`: +Pass `--worktree` or `-w` with a name to create a worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<name>/` at your repository root, on a new branch named `worktree-<name>`: claude --worktree feature-auth @@ -46,6 +46,7 @@ When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. These rules apply to worktrees Claude created with git. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. + * **Claude Code finds another session in the worktree** : the worktree and branch stay even if you choose removal. Follow the `Worktree kept at` message * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch. To return later, run the `claude --worktree <name> --resume` command that Claude Code prints on exit. Removing deletes the worktree directory and its branch, along with all the work in them * **Another branch is checked out** : if the worktree is on a branch other than its own that has commits past the worktree’s starting commit, Claude prompts you to keep or remove the worktree. Either answer keeps that other branch and its commits. Removing deletes the worktree directory and the worktree’s own branch, the one Claude created with it @@ -55,9 +56,10 @@ ## Resume a worktree session -When you resume a session that ended inside a worktree without exiting it, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. `--continue` picks the most recent session recorded under the directory you launch from. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: +When you resume a session that ended isolated in its worktree without exiting it, Claude Code returns the session there and keeps it isolated. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: * **Launch directory** : resume with `--resume` from the main checkout or another directory of the repository. Claude Code re-enters a worktree it created with git under `.claude/worktrees/` even when you launch from inside it. When you launch from inside any other worktree, Claude Code re-enters it only if it can vouch for it from there: a worktree that is its own repository, one without git metadata, or a launch from a subdirectory of a worktree you created with `git worktree add` declines, so launch those from the main checkout. + * **`--continue`** : Claude Code picks the most recent session recorded under the directory you launch from. * **`--fork-session`** : the forked session starts in the directory you launched Claude from, and Claude Code leaves the original session’s worktree untouched. * **Deleted worktree** : if the worktree directory no longer exists, Claude Code resumes the session in the directory you launched Claude from. It tells you the worktree is gone and clears the session’s worktree binding. @@ -67,7 +69,7 @@ ## How Claude Code enforces isolation -While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Claude Code applies four checks: +While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. A session becomes isolated when you start it with `--worktree` but not `--tmux`, or Claude moves it with `EnterWorktree`. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or started in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Claude Code applies four checks: * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. To change a file in the main checkout, edit it yourself or start an interactive session there. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -67,7 +67,7 @@ ## How Claude Code enforces isolation -While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies four checks: +While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Claude Code applies four checks: * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. To change a file in the main checkout, edit it yourself or start an interactive session there. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -286,7 +286,7 @@ * **Says`it cannot be resumed or re-entered`**: nothing in this session vouches for the worktree from where you launched. Recreate it; the directory and its work remain on disk for manual recovery, and when the worktree has a parent checkout, resuming from there also works. * **Says`it contains the protected checkout`**: the refused directory is a parent of your main checkout, such as your home directory. Don’t delete it. Change the worktree path, such as the path your `WorktreeCreate` hook returns or the `EnterWorktree` target, so the worktree doesn’t contain the checkout. * **Says`the protected checkout <path> has a .git entry that could not be examined` or `has git metadata that could not be resolved`**: the problem is the main checkout’s git metadata, not the worktree’s. Don’t delete the worktree, and ignore the message’s trailing advice to recreate it, which doesn’t apply to these two endings. Repair the main checkout, for example a permissions problem or a git `dubious ownership` refusal on its `.git`, and retry. Before v2.1.302, with git 2.56 or later, the `could not be resolved` ending also appeared when the `<path>` after `the protected checkout` held a stray `.git` file. Stray here means the path on that file’s `gitdir:` line doesn’t lead to a valid git repository. To recover, [update Claude Code](</docs/en/setup#update-claude-code>) and retry. When that `gitdir:` path no longer exists, you can also delete the `.git` file and retry. - * **Says`its recorded path has a network spelling`**: Claude Code never resumes into a worktree at a network path. Recreate the worktree at a local path. + * **Says`its recorded path`**: if you can’t open a folder on that path, restore your access to it. Otherwise recreate the worktree at a local path. Claude Code doesn’t resume into a worktree at a network path. * **Any other ending** : the message names the problem and its fix, such as removing a `core.worktree` redirect or recreating the worktree; follow it. Before deleting a directory whose message says its git identity could not be verified, address the named cause first, for example a symbolic link in the worktree’s path or git itself failing to run, since the directory may be healthy. When you do recreate, salvage any changes you need from the old directory first; it stays on disk. ### The session resumes outside its worktree
modified
--- a/worktrees.md +++ b/worktrees.md @@ -144,7 +144,7 @@ * **gitlab.com** : fetches `merge-requests/<number>/head` * **GitHub Enterprise, self-managed GitLab, or any other host** : tries `pull/<number>/head` first, then `merge-requests/<number>/head` -This fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails instead and Claude Code exits with an `Error creating worktree: Failed to fetch PR/MR #<number>` message. A key that `ssh-agent` holds still works, so load your key there and run `git fetch` once by hand to record a new host before you start. Before v2.1.233, Claude Code accepted only `#<number>` and GitHub-style pull request URLs for `--worktree`, and always fetched `pull/<number>/head`. +This fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails instead and Claude Code exits with an `Error creating worktree: Failed to fetch PR/MR #<number>` message. A key that `ssh-agent` holds still works, so load your key there and run `git fetch` once by hand to record a new host before you start. ### Copy gitignored files into worktrees
modified
--- a/worktrees.md +++ b/worktrees.md @@ -162,16 +162,19 @@ If a worktree with the name you pass to `--worktree` already exists, Claude Code opens it instead of creating a new one. If Claude Code stops with an error containing `belongs to a different repository` or `is a leftover worktree`, see The worktree directory `belongs to a different repository`. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: - * It has no uncommitted changes or untracked files. + * The [sandbox](</docs/en/sandboxing#filesystem-isolation>) isn’t restricting file writes in your session, and neither the worktree’s nor the main checkout’s `.claude` settings files enable the sandbox. + * The worktree has no uncommitted changes or untracked files. * It is still on the branch Claude Code created for it. * It has no commits of its own, or its pull request or merge request was merged and its remote branch deleted. Claude Code detects the merged case from git state alone: the remote branch the worktree pushed to no longer exists, and every commit in the worktree is already on the default branch. In every other case, Claude Code reopens the worktree at its old tip: - * The worktree fails any of the conditions. + * The worktree or session fails any of the conditions. * Claude Code can’t verify the worktree’s state. * `worktree.baseRef` is `"head"`. * The name is a pull request or merge request reference. + +If you use the sandbox with the `"fresh"` base, run `git fetch origin`, then pass a new name to `--worktree` to start from the latest default branch. ### Replace worktree creation with a hook
modified
Show diff (352 lines)
--- a/worktrees.md +++ b/worktrees.md @@ -7,11 +7,7 @@ Worktrees are one of several ways to run Claude in parallel. They isolate file edits. [Subagents](</docs/en/sub-agents>) split work up inside one session, and [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions in your worktrees. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. -## - -​ - -Start Claude in a worktree +## Start Claude in a worktree Pass `--worktree` or `-w` with a name to create an isolated worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<name>/` at your repository root, on a new branch named `worktree-<name>`: @@ -21,19 +17,11 @@ Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. -### - -​ - -Set up the worktree environment +### Set up the worktree environment A worktree is a fresh checkout, so initialize your development environment there: ask Claude to install dependencies, or run your project’s setup yourself in the worktree directory under `.claude/worktrees/`. To carry gitignored files such as `.env` into every new worktree automatically, add a `.worktreeinclude` file. -### - -​ - -Ask Claude to create a worktree +### Ask Claude to create a worktree You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference#enterworktree-tool-behavior>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first. The move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. @@ -42,11 +30,7 @@ * **`${CLAUDE_PROJECT_DIR}` stays put**: it still points at the project root where the session started, so a hook command such as `${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh` still runs the script in the main checkout. * **`cwd` follows Claude**: the `cwd` field in the hook’s [input JSON](</docs/en/hooks#common-input-fields>) is the worktree root, and it moves again when Claude runs `cd`. Read it when a hook needs the worktree path. -#### - -​ - -Claude has no `EnterWorktree` tool +#### Claude has no `EnterWorktree` tool If you ask Claude to work in a worktree and it has no `EnterWorktree` or `ExitWorktree` tool, check whether [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on. Once the key is on, Claude Code removes both worktree tools or refuses calls to them. You can keep working in worktrees while the key is on: @@ -58,11 +42,7 @@ To get the tools back, run `/status` in the session to list the [setting sources it loaded](</docs/en/settings#check-what-loaded>), and remove the key from every file that sets it. Then restart Claude Code. If managed settings set the key, ask your administrator whether the policy should change. -## - -​ - -Clean up worktrees +## Clean up worktrees When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. These rules apply to worktrees Claude created with git. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. @@ -73,11 +53,7 @@ Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link. -## - -​ - -Resume a worktree session +## Resume a worktree session When you resume a session that ended inside a worktree without exiting it, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. `--continue` picks the most recent session recorded under the directory you launch from. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: @@ -89,11 +65,7 @@ When Claude enters or exits a worktree that Claude Code created with git, the transcript follows. Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. -## - -​ - -How Claude Code enforces isolation +## How Claude Code enforces isolation While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies four checks: @@ -104,11 +76,7 @@ These checks read the path an edit targets, the directory a command runs in, and the text of the command. None of them tracks which files a shell command writes, so a command that writes into the main checkout without running git there, such as `cp` or a shell redirect, isn’t refused by them. Claude Code treats that command like any other shell command under your [permissions](</docs/en/permissions>) and [sandboxing](</docs/en/sandboxing>) settings. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). -## - -​ - -Isolate subagents with worktrees +## Isolate subagents with worktrees Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or make the isolation permanent for a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to its frontmatter. This subagent in `.claude/agents/` always runs in its own worktree: @@ -123,11 +91,7 @@ Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. -### - -​ - -Clean up subagent and background-session worktrees +### Clean up subagent and background-session worktrees Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in these cases: @@ -139,27 +103,15 @@ Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. -#### - -​ - -Worktree locks and manual removal +#### Worktree locks and manual removal While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. -## - -​ - -Customize worktree creation +## Customize worktree creation Claude Code’s defaults for creating worktrees cover most sessions: it creates them under `.claude/worktrees/`, branches them from your repository’s default branch, and checks out only tracked files. The options in this section change those defaults. -### - -​ - -Choose the base branch +### Choose the base branch New worktrees branch from the repository’s default branch, so most sessions don’t need this setting. Set `worktree.baseRef` in [settings](</docs/en/settings-reference#worktree>) to branch from your current work instead. The setting accepts two values: @@ -180,11 +132,7 @@ } } -### - -​ - -Branch from a pull request +### Branch from a pull request To branch from a specific pull request or merge request, pass `--worktree` the number prefixed with `#`, a GitHub pull request URL, or a GitLab merge request URL such as `https://gitlab.com/group/repo/-/merge_requests/123`. Claude Code fetches that change’s head commit from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`. Quote the argument so your shell doesn’t treat `#` as the start of a comment: @@ -198,11 +146,7 @@ This fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails instead and Claude Code exits with an `Error creating worktree: Failed to fetch PR/MR #<number>` message. A key that `ssh-agent` holds still works, so load your key there and run `git fetch` once by hand to record a new host before you start. Before v2.1.233, Claude Code accepted only `#<number>` and GitHub-style pull request URLs for `--worktree`, and always fetched `pull/<number>/head`. -### - -​ - -Copy gitignored files into worktrees +### Copy gitignored files into worktrees A worktree is a fresh checkout, so untracked files like `.env` or `.env.local` from your main repository are not present. To copy them automatically when Claude creates a worktree, add a `.worktreeinclude` file to your project root. The file uses `.gitignore` syntax. Only files that match a pattern and are also gitignored are copied, so tracked files are never duplicated. If you write a pattern that starts with `**/` and the files you want are inside a directory that is gitignored as a whole, Claude Code copies them only when that directory itself matches the pattern, or when the first name after the `**/` is one of the names in the directory’s path. For example, if you write `**/.claude/skills/*.md`, that first name is `.claude`, so Claude Code copies the matching files out of an ignored `.claude/` directory. To copy files out of an ignored directory that a `**/` pattern doesn’t reach, name the directory in the pattern instead: write `vendor/**/config.json` rather than `**/config.json`. Before v2.1.239, Claude Code copied files out of a wholly ignored directory for a `**/` pattern only when the directory itself matched the pattern. This `.worktreeinclude` copies two env files and a secrets config into each new worktree: @@ -214,11 +158,7 @@ This applies to every worktree Claude Code creates with git: `--worktree` worktrees, subagent worktrees, and parallel sessions in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). With a `WorktreeCreate` hook, copy the files inside the hook script. -### - -​ - -Reuse a worktree name +### Reuse a worktree name If a worktree with the name you pass to `--worktree` already exists, Claude Code opens it instead of creating a new one. If Claude Code stops with an error containing `belongs to a different repository` or `is a leftover worktree`, see The worktree directory `belongs to a different repository`. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: @@ -233,19 +173,11 @@ * `worktree.baseRef` is `"head"`. * The name is a pull request or merge request reference. -### - -​ - -Replace worktree creation with a hook +### Replace worktree creation with a hook Configure a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) to replace the default `git worktree` logic entirely, including placing worktrees somewhere other than `.claude/worktrees/`. For a complete example, see Non-git version control. -## - -​ - -What worktrees share with the main checkout +## What worktrees share with the main checkout A worktree gets its own files and branch, but it shares the following with the main checkout: @@ -256,11 +188,7 @@ All of these apply whether you create the worktree with `--worktree` or with `git worktree add`. In a worktree session you start from the [desktop app](</docs/en/desktop#run-a-session-in-its-own-worktree>), Claude Code reads project configuration such as settings, hooks, skills, agents, commands, and [`.mcp.json`](</docs/en/mcp#project-scope>) servers from the main checkout’s root. Hook commands run in that root, and `${CLAUDE_PROJECT_DIR}` points at it. To reach the files Claude is working on, read the worktree’s path from the hook’s [`cwd` input field](</docs/en/hooks#common-input-fields>). `CLAUDE.md` files and `.claude/rules/` still load from the worktree. -## - -​ - -Manage worktrees manually +## Manage worktrees manually Create worktrees with Git directly when you need to check out a specific existing branch or place the worktree outside the repository. Create a worktree on a new branch: @@ -285,11 +213,7 @@ See the [Git worktree documentation](<https://git-scm.com/docs/git-worktree>) for the full command reference. -## - -​ - -Non-git version control +## Non-git version control Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#where-settings-live>): @@ -310,43 +234,23 @@ Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](</docs/en/hooks#worktreecreate>) for the input schema and a removal example. A `WorktreeCreate` hook also lets you run [`/batch`](</docs/en/commands#all-commands>) outside a git repository. Each `/batch` subagent then publishes its change with your project’s version-control commands and, when it can’t open a pull request, reports what it published instead. Running `/batch` outside a git repository requires Claude Code v2.1.281 or later. -## - -​ - -Troubleshooting +## Troubleshooting Claude Code reports the errors below when it creates a worktree, enters one at startup, or returns a resumed session to one. -### - -​ - -Claude Code can’t enter the worktree at startup +### Claude Code can’t enter the worktree at startup When Claude Code can’t enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) prints something other than the directory it created, or when the directory was deleted after it was set up. -### - -​ - -Worktree creation fails on a symlinked path +### Worktree creation fails on a symlinked path Claude Code refuses to create a worktree when `.claude`, `.claude/worktrees`, or the worktree directory itself is a symlink, and the error names the symlinked path. Remove the symlink and retry. Before v2.1.212, if the repository already contained a committed symlink at one of those paths, worktree creation followed it and could create files outside the repository. -### - -​ - -A worktree Claude Code created has the original content of replaced objects +### A worktree Claude Code created has the original content of replaced objects If your repository uses [`git replace`](<https://git-scm.com/docs/git-replace>), the files in a worktree that Claude Code creates hold the original objects’ content rather than the replacements your `refs/replace/` entries name. Claude Code runs the git commands that check out the worktree’s files with `GIT_NO_REPLACE_OBJECTS=1`, ignoring any value you exported for that variable. To get the replaced content, create the worktree yourself with `git worktree add` and start Claude Code inside it. -### - -​ - -Git LFS files are pointer files in a worktree Claude Code created +### Git LFS files are pointer files in a worktree Claude Code created If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In four rare cases, Claude Code creates no worktree at all: it can’t tell which filter drivers the repository’s config defines, or it finds a setting there it can’t switch off. Match the error to its fix: @@ -355,19 +259,11 @@ * **`The repository git config has a conditional include (includeIf)`** : move the settings the `includeIf` in `.git/config` pulls in directly into that file, remove the `includeIf`, and retry. An `includeIf` in your global git config doesn’t trigger this. * **`Git was not run: the repository's own git config sets<key>`**: the message names a key that points Git LFS at a program to run, such as `lfs.customtransfer.<name>.path` or `lfs.standalonetransferagent`. If that setting is yours, move it to your global git config. If you don’t recognize it, remove it from the repository’s git config, since a tool or checkout you don’t trust may have written it. Retry once the key is gone from the repository’s config. -### - -​ - -Worktree creation fails in a partial clone +### Worktree creation fails in a partial clone An error containing `This repository is a partial clone` means Claude Code couldn’t fetch every git object the worktree’s starting commit needs. Take the step in the message’s sentence ending in `try again`. Then retry from the shell where you took it: run `claude --worktree`, or start `claude` there and ask again. -### - -​ - -`Can only use --worktree in a git repository` +### `Can only use --worktree in a git repository` This error means you passed `--worktree` in a directory that isn’t a git checkout, and no `WorktreeCreate` hook is active. @@ -375,19 +271,11 @@ * In a checkout of another version control system, set up the hook the message suggests. * To work in the directory directly, start Claude without `--worktree`. -### - -​ - -The worktree directory `belongs to a different repository` +### The worktree directory `belongs to a different repository` The errors `belongs to a different repository` and `is a leftover worktree` both mean git ties the directory for the worktree name you passed to another location. This can happen after you copy or move a project. Pass a different worktree name. If the directory has no work to keep and you didn’t copy or move a project, you can remove it and retry the same name. After a copy or move, that retry can fail with `is already checked out elsewhere in this repository`, so use a different name. -### - -​ - -Claude Code refuses to use a worktree +### Claude Code refuses to use a worktree An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. A directory with no git metadata at all, such as one your `WorktreeCreate` hook creates, passes the check only when no git repository contains it. If the hook creates the directory inside a repository, git resolves it to that repository’s checkout and Claude Code refuses it with the `git resolves its working tree to` message, so have the hook create its directories outside any repository. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages: @@ -398,11 +286,7 @@ * **Says`its recorded path has a network spelling`**: Claude Code never resumes into a worktree at a network path. Recreate the worktree at a local path. * **Any other ending** : the message names the problem and its fix, such as removing a `core.worktree` redirect or recreating the worktree; follow it. Before deleting a directory whose message says its git identity could not be verified, address the named cause first, for example a symbolic link in the worktree’s path or git itself failing to run, since the directory may be healthy. When you do recreate, salvage any changes you need from the old directory first; it stays on disk. -### - -​ - -The session resumes outside its worktree +### The session resumes outside its worktree When you resume a session interactively and Claude Code can’t return it to its worktree, Claude Code says so with one of the messages below. When Claude Code clears the worktree binding, it records the clear in the session transcript. If you [suppress transcript writes](</docs/en/sessions#where-transcripts-are-stored>), the message says instead that the binding could not be cleared and that Claude Code will re-check the worktree on a later resume. @@ -422,11 +306,7 @@ The refusal ending embedded in each error is shared with the interactive notices, so it still matches its entry under Claude Code refuses to use a worktree. In the stream-json result, [`startup_failure_reason`](</docs/en/agent-sdk/typescript#startup_failure_reason>) is `worktree_unverified` for the `could not verify worktree` error and `worktree_resume_refused` for the `cannot resume into worktree` and `The worktree binding is kept` errors. An application can branch on it instead of matching the error text. Before v2.1.274, the result carried no `startup_failure_reason` field. -## - -​ - -See also +## See also Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts, passing findings between them, and switching between the sessions you create:
modified
--- a/worktrees.md +++ b/worktrees.md @@ -249,7 +249,7 @@ A worktree gets its own files and branch, but it shares the following with the main checkout: - * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. + * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory. With the [sandbox](</docs/en/sandboxing#filesystem-isolation>) enabled, commands such as `git commit` work in a session at the worktree’s root, which is where `--worktree` starts one. By default, they [fail with an `index.lock` error if you run `claude` in a subdirectory of the worktree](</docs/en/sandboxing#git-index-lock>). * **Plugins** : plugins installed at [project scope](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`. The rule applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. See [where approvals are saved](</docs/en/permissions#permission-system>). * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -35,12 +35,28 @@ Ask Claude to create a worktree -You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first. The move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. +You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference#enterworktree-tool-behavior>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first. The move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. **Hook paths don’t follow the worktree.** After Claude enters a worktree, Claude Code keeps `${CLAUDE_PROJECT_DIR}` in your [hooks](</docs/en/hooks#reference-scripts-by-path>) where it was and passes the worktree path to them a different way: * **`${CLAUDE_PROJECT_DIR}` stays put**: it still points at the project root where the session started, so a hook command such as `${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh` still runs the script in the main checkout. * **`cwd` follows Claude**: the `cwd` field in the hook’s [input JSON](</docs/en/hooks#common-input-fields>) is the worktree root, and it moves again when Claude runs `cd`. Read it when a hook needs the worktree path. + +#### + +​ + +Claude has no `EnterWorktree` tool + +If you ask Claude to work in a worktree and it has no `EnterWorktree` or `ExitWorktree` tool, check whether [`permissions.blockWritesOutsideWorkingDirectories`](</docs/en/settings-reference#permissions-blockwritesoutsideworkingdirectories>) is on. Once the key is on, Claude Code removes both worktree tools or refuses calls to them. You can keep working in worktrees while the key is on: + + * **Interactive sessions** : start the session in a worktree with `claude --worktree`. + * **[Background sessions](</docs/en/agent-view#how-file-edits-are-isolated>)** : Claude Code refuses a background session’s edits in your main checkout until the session calls `EnterWorktree`, which it doesn’t have. Any of these lets the session edit: + * Start it with `claude --bg --worktree` + * Set [`worktree.bgIsolation`](</docs/en/settings-reference#worktree-bgisolation>) to `"none"` + * Have Claude edit in a worktree made with `git worktree add` under the directory the session started in + +To get the tools back, run `/status` in the session to list the [setting sources it loaded](</docs/en/settings#check-what-loaded>), and remove the key from every file that sets it. Then restart Claude Code. If managed settings set the key, ask your administrator whether the policy should change. ## @@ -63,7 +79,7 @@ Resume a worktree session -When you resume a session that ended inside a worktree without exiting it, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. `--continue` picks the most recent session recorded under the directory you launch from. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](</docs/en/tools-reference>) tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: +When you resume a session that ended inside a worktree without exiting it, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. `--continue` picks the most recent session recorded under the directory you launch from. Back inside the worktree, Claude can leave with the [`ExitWorktree`](</docs/en/tools-reference>) tool when the session has that tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: * **Launch directory** : resume with `--resume` from the main checkout or another directory of the repository. Claude Code re-enters a worktree it created with git under `.claude/worktrees/` even when you launch from inside it. When you launch from inside any other worktree, Claude Code re-enters it only if it can vouch for it from there: a worktree that is its own repository, one without git metadata, or a launch from a subdirectory of a worktree you created with `git worktree add` declines, so launch those from the main checkout. * **`--fork-session`** : the forked session starts in the directory you launched Claude from, and Claude Code leaves the original session’s worktree untouched. @@ -81,7 +97,7 @@ While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies four checks: - * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. + * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. To change a file in the main checkout, edit it yourself or start an interactive session there. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. * **Command shape** : Claude Code blocks a Bash or Monitor command when it can’t verify from the command text that any git the command runs stays inside the worktree. That happens, for example, when the command name is computed at runtime, when the syntax can’t be parsed, or when an expansion such as `${!name}` or `${ command; }` could run a command the text doesn’t spell out. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -204,7 +204,7 @@ Reuse a worktree name -Passing `--worktree` a name whose directory already exists opens that existing worktree instead of creating a new one. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: +If a worktree with the name you pass to `--worktree` already exists, Claude Code opens it instead of creating a new one. If Claude Code stops with an error containing `belongs to a different repository` or `is a leftover worktree`, see The worktree directory `belongs to a different repository`. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: * It has no uncommitted changes or untracked files. * It is still on the branch Claude Code created for it. @@ -351,6 +351,26 @@ ​ +`Can only use --worktree in a git repository` + +This error means you passed `--worktree` in a directory that isn’t a git checkout, and no `WorktreeCreate` hook is active. + + * In a folder with no version control, run `git init` there, create a first commit, then retry. + * In a checkout of another version control system, set up the hook the message suggests. + * To work in the directory directly, start Claude without `--worktree`. + +### + +​ + +The worktree directory `belongs to a different repository` + +The errors `belongs to a different repository` and `is a leftover worktree` both mean git ties the directory for the worktree name you passed to another location. This can happen after you copy or move a project. Pass a different worktree name. If the directory has no work to keep and you didn’t copy or move a project, you can remove it and retry the same name. After a copy or move, that retry can fail with `is already checked out elsewhere in this repository`, so use a different name. + +### + +​ + Claude Code refuses to use a worktree An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. A directory with no git metadata at all, such as one your `WorktreeCreate` hook creates, passes the check only when no git repository contains it. If the hook creates the directory inside a repository, git resolves it to that repository’s checkout and Claude Code refuses it with the `git resolves its working tree to` message, so have the hook create its directories outside any repository. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages:
modified
--- a/worktrees.md +++ b/worktrees.md @@ -35,7 +35,7 @@ Ask Claude to create a worktree -You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first, because the move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. +You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first. The move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. **Hook paths don’t follow the worktree.** After Claude enters a worktree, Claude Code keeps `${CLAUDE_PROJECT_DIR}` in your [hooks](</docs/en/hooks#reference-scripts-by-path>) where it was and passes the worktree path to them a different way: @@ -55,7 +55,7 @@ * **Another branch is checked out** : if the worktree is on a branch other than its own that has commits past the worktree’s starting commit, Claude prompts you to keep or remove the worktree. Either answer keeps that other branch and its commits. Removing deletes the worktree directory and the worktree’s own branch, the one Claude created with it * **The worktree’s state can’t be verified** : when Claude Code can’t count the worktree’s changes or can’t inspect its submodule checkouts, it prompts you rather than removing the worktree automatically. The prompt names what it couldn’t check -Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. +Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link. ## @@ -71,7 +71,7 @@ Before v2.1.212, a non-interactive resume stayed in the starting directory and `ExitWorktree` reported that there was no active worktree session to exit. -When Claude enters or exits a worktree that Claude Code created with git, the transcript follows: Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. Requires Claude Code v2.1.198 or later. +When Claude enters or exits a worktree that Claude Code created with git, the transcript follows. Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. ## @@ -121,7 +121,15 @@ * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. -Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. +Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. + +#### + +​ + +Worktree locks and manual removal + +While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. ## @@ -142,7 +150,13 @@ * `"fresh"` (default): branch from the repository’s default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote. * `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. -You can’t set `worktree.baseRef` to a branch name. To start a worktree from a specific existing branch, create it with git directly. For a `"fresh"` base, Claude Code keeps `origin/HEAD` current: when the repository hasn’t been fetched in the last 24 hours, it fetches the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. The fetch never waits for input in your terminal, so it also counts as failed when git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. Before v2.1.208, a fresh worktree used whatever `origin/HEAD` was already cached locally. This example makes every new worktree branch from your current work: +You can’t set `worktree.baseRef` to a branch name. To start a worktree from a specific existing branch, create it with git directly. For a `"fresh"` base, Claude Code keeps `origin/HEAD` current: + + * When the repository hasn’t been fetched in the last 24 hours, it fetches the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. + * The fetch never waits for input in your terminal. It also counts as failed when git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host. + * If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. + +This example makes every new worktree branch from your current work: { "worktree": { @@ -203,8 +217,6 @@ * `worktree.baseRef` is `"head"`. * The name is a pull request or merge request reference. -Before v2.1.208, when you reused a name, Claude Code always reopened the old worktree at its old tip. - ### ​ @@ -222,8 +234,8 @@ A worktree gets its own files and branch, but it shares the following with the main checkout: * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. - * **Plugins** : plugins installed at [project scope](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. - * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). + * **Plugins** : plugins installed at [project scope](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. + * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`. The rule applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. See [where approvals are saved](</docs/en/permissions#permission-system>). * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later. All of these apply whether you create the worktree with `--worktree` or with `git worktree add`. In a worktree session you start from the [desktop app](</docs/en/desktop#run-a-session-in-its-own-worktree>), Claude Code reads project configuration such as settings, hooks, skills, agents, commands, and [`.mcp.json`](</docs/en/mcp#project-scope>) servers from the main checkout’s root. Hook commands run in that root, and `${CLAUDE_PROJECT_DIR}` points at it. To reach the files Claude is working on, read the worktree’s path from the hook’s [`cwd` input field](</docs/en/hooks#common-input-fields>). `CLAUDE.md` files and `.claude/rules/` still load from the worktree. @@ -310,6 +322,14 @@ ​ +A worktree Claude Code created has the original content of replaced objects + +If your repository uses [`git replace`](<https://git-scm.com/docs/git-replace>), the files in a worktree that Claude Code creates hold the original objects’ content rather than the replacements your `refs/replace/` entries name. Claude Code runs the git commands that check out the worktree’s files with `GIT_NO_REPLACE_OBJECTS=1`, ignoring any value you exported for that variable. To get the replaced content, create the worktree yourself with `git worktree add` and start Claude Code inside it. + +### + +​ + Git LFS files are pointer files in a worktree Claude Code created If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In four rare cases, Claude Code creates no worktree at all: it can’t tell which filter drivers the repository’s config defines, or it finds a setting there it can’t switch off. Match the error to its fix:
modified
--- a/worktrees.md +++ b/worktrees.md @@ -323,6 +323,14 @@ ​ +Worktree creation fails in a partial clone + +An error containing `This repository is a partial clone` means Claude Code couldn’t fetch every git object the worktree’s starting commit needs. Take the step in the message’s sentence ending in `try again`. Then retry from the shell where you took it: run `claude --worktree`, or start `claude` there and ask again. + +### + +​ + Claude Code refuses to use a worktree An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. A directory with no git metadata at all, such as one your `WorktreeCreate` hook creates, passes the check only when no git repository contains it. If the hook creates the directory inside a repository, git resolves it to that repository’s checkout and Claude Code refuses it with the `git resolves its working tree to` message, so have the hook create its directories outside any repository. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages:
modified
--- a/worktrees.md +++ b/worktrees.md @@ -52,6 +52,7 @@ * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch. To return later, run the `claude --worktree <name> --resume` command that Claude Code prints on exit. Removing deletes the worktree directory and its branch, along with all the work in them + * **Another branch is checked out** : if the worktree is on a branch other than its own that has commits past the worktree’s starting commit, Claude prompts you to keep or remove the worktree. Either answer keeps that other branch and its commits. Removing deletes the worktree directory and the worktree’s own branch, the one Claude created with it * **The worktree’s state can’t be verified** : when Claude Code can’t count the worktree’s changes or can’t inspect its submodule checkouts, it prompts you rather than removing the worktree automatically. The prompt names what it couldn’t check Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -329,7 +329,7 @@ * **Says`launch from the parent checkout` or `Run the resume from the project checkout`**: you launched Claude Code from inside the worktree. Launch from the main checkout instead; the worktree needs no recreation. * **Says`it cannot be resumed or re-entered`**: nothing in this session vouches for the worktree from where you launched. Recreate it; the directory and its work remain on disk for manual recovery, and when the worktree has a parent checkout, resuming from there also works. * **Says`it contains the protected checkout`**: the refused directory is a parent of your main checkout, such as your home directory. Don’t delete it. Change the worktree path, such as the path your `WorktreeCreate` hook returns or the `EnterWorktree` target, so the worktree doesn’t contain the checkout. - * **Says`the protected checkout <path> has a .git entry that could not be examined` or `has git metadata that could not be resolved`**: the problem is the main checkout’s git metadata, not the worktree’s. Don’t delete the worktree, and ignore the message’s trailing advice to recreate it, which doesn’t apply to these two endings. Repair the main checkout, for example a permissions problem or a git `dubious ownership` refusal on its `.git`, and retry. + * **Says`the protected checkout <path> has a .git entry that could not be examined` or `has git metadata that could not be resolved`**: the problem is the main checkout’s git metadata, not the worktree’s. Don’t delete the worktree, and ignore the message’s trailing advice to recreate it, which doesn’t apply to these two endings. Repair the main checkout, for example a permissions problem or a git `dubious ownership` refusal on its `.git`, and retry. Before v2.1.302, with git 2.56 or later, the `could not be resolved` ending also appeared when the `<path>` after `the protected checkout` held a stray `.git` file. Stray here means the path on that file’s `gitdir:` line doesn’t lead to a valid git repository. To recover, [update Claude Code](</docs/en/setup#update-claude-code>) and retry. When that `gitdir:` path no longer exists, you can also delete the `.git` file and retry. * **Says`its recorded path has a network spelling`**: Claude Code never resumes into a worktree at a network path. Recreate the worktree at a local path. * **Any other ending** : the message names the problem and its fix, such as removing a `core.worktree` redirect or recreating the worktree; follow it. Before deleting a directory whose message says its git identity could not be verified, address the named cause first, for example a symbolic link in the worktree’s path or git itself failing to run, since the directory may be healthy. When you do recreate, salvage any changes you need from the old directory first; it stays on disk.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -1,6 +1,9 @@ A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree gives it a separate copy of the files to edit, so one session can build a feature while a second fixes a bug. -Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), select the **worktree** option when you start a session to give it its own worktree. +If you use another version control system or the desktop app, follow the instructions for your setup: + + * **Other version control systems** : worktrees require a git repository; configure hooks to replace the git logic + * **Desktop app** : see [Run a session in its own worktree](</docs/en/desktop#run-a-session-in-its-own-worktree>) Worktrees are one of several ways to run Claude in parallel. They isolate file edits. [Subagents](</docs/en/sub-agents>) split work up inside one session, and [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions in your worktrees. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. @@ -222,7 +225,7 @@ * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later. -All of these apply whether you create the worktree with `--worktree` or with `git worktree add`. In a worktree session that you start from the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), Claude Code reads project configuration such as settings, hooks, skills, agents, commands, and [`.mcp.json`](</docs/en/mcp#project-scope>) servers from the main checkout’s root rather than from the worktree. Hook commands run in that root, and `${CLAUDE_PROJECT_DIR}` points at it. To reach the files Claude is working on, read the worktree’s path from the hook’s [`cwd` input field](</docs/en/hooks#common-input-fields>). `CLAUDE.md` files and `.claude/rules/` still load from the worktree. +All of these apply whether you create the worktree with `--worktree` or with `git worktree add`. In a worktree session you start from the [desktop app](</docs/en/desktop#run-a-session-in-its-own-worktree>), Claude Code reads project configuration such as settings, hooks, skills, agents, commands, and [`.mcp.json`](</docs/en/mcp#project-scope>) servers from the main checkout’s root. Hook commands run in that root, and `${CLAUDE_PROJECT_DIR}` points at it. To reach the files Claude is working on, read the worktree’s path from the hook’s [`cwd` input field](</docs/en/hooks#common-input-fields>). `CLAUDE.md` files and `.claude/rules/` still load from the worktree. ## @@ -366,4 +369,4 @@ * [Cross-session messaging](</docs/en/cross-session-messaging>): let the sessions in your worktrees pass findings to each other * [Agent teams](</docs/en/agent-teams>): coordinate multiple Claude sessions automatically * [Manage sessions](</docs/en/sessions>): name, resume, and switch between conversations - * [Desktop parallel sessions](</docs/en/desktop#work-in-parallel-with-sessions>): worktree-backed sessions in the desktop app + * [Run a Desktop session in its own worktree](</docs/en/desktop#run-a-session-in-its-own-worktree>): worktree-backed sessions in the desktop app
modified
--- a/worktrees.md +++ b/worktrees.md @@ -101,7 +101,7 @@ Apply the requested refactor across every affected file, then run the tests and report the results. -Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. +Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. ###
modified
--- a/worktrees.md +++ b/worktrees.md @@ -222,7 +222,7 @@ * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later. -All of these apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). +All of these apply whether you create the worktree with `--worktree` or with `git worktree add`. In a worktree session that you start from the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), Claude Code reads project configuration such as settings, hooks, skills, agents, commands, and [`.mcp.json`](</docs/en/mcp#project-scope>) servers from the main checkout’s root rather than from the worktree. Hook commands run in that root, and `${CLAUDE_PROJECT_DIR}` points at it. To reach the files Claude is working on, read the worktree’s path from the hook’s [`cwd` input field](</docs/en/hooks#common-input-fields>). `CLAUDE.md` files and `.claude/rules/` still load from the worktree. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -82,7 +82,7 @@ * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. * **Command shape** : Claude Code blocks a Bash or Monitor command when it can’t verify from the command text that any git the command runs stays inside the worktree. That happens, for example, when the command name is computed at runtime, when the syntax can’t be parsed, or when an expansion such as `${!name}` or `${ command; }` could run a command the text doesn’t spell out. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. -These checks read the path an edit targets, the directory a command runs in, and the text of the command. None of them tracks which files a shell command writes, so a command that writes into the main checkout without running git there, such as `cp` or a shell redirect, isn’t refused by them. Claude Code treats that command like any other shell command, so whether it runs or prompts you depends on your [permission mode](</docs/en/permission-modes>) and rules. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). +These checks read the path an edit targets, the directory a command runs in, and the text of the command. None of them tracks which files a shell command writes, so a command that writes into the main checkout without running git there, such as `cp` or a shell redirect, isn’t refused by them. Claude Code treats that command like any other shell command under your [permissions](</docs/en/permissions>) and [sandboxing](</docs/en/sandboxing>) settings. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -1,4 +1,4 @@ -A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so one session can build a feature while a second fixes a bug. +A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree gives it a separate copy of the files to edit, so one session can build a feature while a second fixes a bug. Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), select the **worktree** option when you start a session to give it its own worktree. @@ -82,7 +82,7 @@ * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. * **Command shape** : Claude Code blocks a Bash or Monitor command when it can’t verify from the command text that any git the command runs stays inside the worktree. That happens, for example, when the command name is computed at runtime, when the syntax can’t be parsed, or when an expansion such as `${!name}` or `${ command; }` could run a command the text doesn’t spell out. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. -The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). +These checks read the path an edit targets, the directory a command runs in, and the text of the command. None of them tracks which files a shell command writes, so a command that writes into the main checkout without running git there, such as `cp` or a shell redirect, isn’t refused by them. Claude Code treats that command like any other shell command, so whether it runs or prompts you depends on your [permission mode](</docs/en/permission-modes>) and rules. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -101,7 +101,7 @@ Apply the requested refactor across every affected file, then run the tests and report the results. -Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. +Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. A subagent in its own worktree takes the instruction files it [starts with](</docs/en/sub-agents#what-loads-at-startup>) from your main conversation, not from its worktree. When that worktree is in the default location under `.claude/worktrees/`, the subagent also doesn’t load the `CLAUDE.md` file or `.claude/rules/` directory at the worktree’s root as it reads files there, even if those differ on the worktree’s branch. ### @@ -138,7 +138,7 @@ * `"fresh"` (default): branch from the repository’s default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote. * `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. -You can’t set `worktree.baseRef` to a branch name. To start a worktree from a specific existing branch, create it with git directly. For a `"fresh"` base, Claude Code keeps `origin/HEAD` current: when the repository hasn’t been fetched in the last 24 hours, it fetches the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. Before v2.1.208, a fresh worktree used whatever `origin/HEAD` was already cached locally. This example makes every new worktree branch from your current work: +You can’t set `worktree.baseRef` to a branch name. To start a worktree from a specific existing branch, create it with git directly. For a `"fresh"` base, Claude Code keeps `origin/HEAD` current: when the repository hasn’t been fetched in the last 24 hours, it fetches the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. The fetch never waits for input in your terminal, so it also counts as failed when git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. Before v2.1.208, a fresh worktree used whatever `origin/HEAD` was already cached locally. This example makes every new worktree branch from your current work: { "worktree": { @@ -162,7 +162,7 @@ * **gitlab.com** : fetches `merge-requests/<number>/head` * **GitHub Enterprise, self-managed GitLab, or any other host** : tries `pull/<number>/head` first, then `merge-requests/<number>/head` -Before v2.1.233, Claude Code accepted only `#<number>` and GitHub-style pull request URLs for `--worktree`, and always fetched `pull/<number>/head`. +This fetch never waits for input in your terminal. If git or ssh would ask for a password, a key passphrase, or confirmation of a new SSH host, the fetch fails instead and Claude Code exits with an `Error creating worktree: Failed to fetch PR/MR #<number>` message. A key that `ssh-agent` holds still works, so load your key there and run `git fetch` once by hand to record a new host before you start. Before v2.1.233, Claude Code accepted only `#<number>` and GitHub-style pull request URLs for `--worktree`, and always fetched `pull/<number>/head`. ###
modified
--- a/worktrees.md +++ b/worktrees.md @@ -117,7 +117,7 @@ * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. -Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. Before v2.1.246, the sweep didn’t check for the marker, and could remove a worktree you created yourself when an old background-session record pointed at it. While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. +Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -45,7 +45,7 @@ Clean up worktrees -When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. +When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. These rules apply to worktrees Claude created with git. For a worktree your [WorktreeCreate hook](</docs/en/hooks#worktreecreate>) created, see [WorktreeRemove](</docs/en/hooks#worktreeremove>) instead. * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch. To return later, run the `claude --worktree <name> --resume` command that Claude Code prints on exit. Removing deletes the worktree directory and its branch, along with all the work in them
modified
--- a/worktrees.md +++ b/worktrees.md @@ -48,7 +48,7 @@ When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later - * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them + * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch. To return later, run the `claude --worktree <name> --resume` command that Claude Code prints on exit. Removing deletes the worktree directory and its branch, along with all the work in them * **The worktree’s state can’t be verified** : when Claude Code can’t count the worktree’s changes or can’t inspect its submodule checkouts, it prompts you rather than removing the worktree automatically. The prompt names what it couldn’t check Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. @@ -59,9 +59,9 @@ Resume a worktree session -When you resume a session that was inside a worktree, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](</docs/en/tools-reference>) tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: - - * **Launch directory** : resume from the main checkout or another directory of the repository. Claude Code re-enters a worktree it created with git under `.claude/worktrees/` even when you launch from inside it. When you launch from inside any other worktree, Claude Code re-enters it only if it can vouch for it from there: a worktree that is its own repository, one without git metadata, or a launch from a subdirectory of a worktree you created with `git worktree add` declines, so launch those from the main checkout. +When you resume a session that ended inside a worktree without exiting it, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. `--continue` picks the most recent session recorded under the directory you launch from. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](</docs/en/tools-reference>) tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: + + * **Launch directory** : resume with `--resume` from the main checkout or another directory of the repository. Claude Code re-enters a worktree it created with git under `.claude/worktrees/` even when you launch from inside it. When you launch from inside any other worktree, Claude Code re-enters it only if it can vouch for it from there: a worktree that is its own repository, one without git metadata, or a launch from a subdirectory of a worktree you created with `git worktree add` declines, so launch those from the main checkout. * **`--fork-session`** : the forked session starts in the directory you launched Claude from, and Claude Code leaves the original session’s worktree untouched. * **Deleted worktree** : if the worktree directory no longer exists, Claude Code resumes the session in the directory you launched Claude from. It tells you the worktree is gone and clears the session’s worktree binding.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -218,7 +218,7 @@ A worktree gets its own files and branch, but it shares the following with the main checkout: * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. - * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. + * **Plugins** : plugins installed at [project scope](</docs/en/plugins/loading#find-where-a-plugin-is-enabled>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later. @@ -276,7 +276,7 @@ } } -Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](</docs/en/hooks#worktreecreate>) for the input schema and a removal example. +Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](</docs/en/hooks#worktreecreate>) for the input schema and a removal example. A `WorktreeCreate` hook also lets you run [`/batch`](</docs/en/commands#all-commands>) outside a git repository. Each `/batch` subagent then publishes its change with your project’s version-control commands and, when it can’t open a pull request, reports what it published instead. Running `/batch` outside a git repository requires Claude Code v2.1.281 or later. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -45,10 +45,11 @@ Clean up worktrees -When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, and new commits. +When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, uncommitted work inside checked-out submodules, and new commits. * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them + * **The worktree’s state can’t be verified** : when Claude Code can’t count the worktree’s changes or can’t inspect its submodule checkouts, it prompts you rather than removing the worktree automatically. The prompt names what it couldn’t check Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. @@ -79,9 +80,9 @@ * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. - * **Command shape** : Claude Code blocks a Bash or Monitor command when it can’t verify from the command text that any git the command runs stays inside the worktree, for example when the command name is computed at runtime or the syntax can’t be parsed. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. - -The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. + * **Command shape** : Claude Code blocks a Bash or Monitor command when it can’t verify from the command text that any git the command runs stays inside the worktree. That happens, for example, when the command name is computed at runtime, when the syntax can’t be parsed, or when an expansion such as `${!name}` or `${ command; }` could run a command the text doesn’t spell out. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. + +The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. For a refused command, see [what the refusal message means and how to clear it](</docs/en/errors#command-blocked-by-the-worktree-isolation-checks>). ## @@ -111,6 +112,7 @@ Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in these cases: * The worktree still holds work: changed or untracked files, or unpushed commits. + * A checked-out submodule in the worktree holds changed or untracked files, or Claude Code can’t inspect the worktree’s submodules. This check requires Claude Code v2.1.274 or later. * One of the four cases that also block worktree creation applies: Claude Code can’t determine which filter drivers the repository config defines, or finds a setting there it can’t switch off. * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. @@ -213,13 +215,14 @@ What worktrees share with the main checkout -A worktree gets its own files and branch, but it shares the repository’s `.git` directory, project-scope plugins, and saved permission approvals with the main checkout: +A worktree gets its own files and branch, but it shares the following with the main checkout: * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). - -All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). + * **Untracked skills, agents, and commands** : when the worktree checkout has no `.claude/skills` directory at its root, for example because your `.claude/skills` is gitignored, Claude Code loads the main checkout’s [project skills](</docs/en/skills#where-skills-live>) in the worktree session. In a worktree with its own `.claude/skills` directory, only that copy loads. The same read-through covers `.claude/agents` and `.claude/commands`. For skills, the read-through requires Claude Code v2.1.277 or later. + +All of these apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -349,7 +349,7 @@ * `Error: ...The worktree binding is kept.` for `Could not re-enter` * `Notice: the worktree <path> for this session no longer exists...` for a gone worktree; Claude Code prints it and continues the session, as an interactive resume does -The refusal ending embedded in each error is shared with the interactive notices, so it still matches its entry under Claude Code refuses to use a worktree. +The refusal ending embedded in each error is shared with the interactive notices, so it still matches its entry under Claude Code refuses to use a worktree. In the stream-json result, [`startup_failure_reason`](</docs/en/agent-sdk/typescript#startup_failure_reason>) is `worktree_unverified` for the `could not verify worktree` error and `worktree_resume_refused` for the `cannot resume into worktree` and `The worktree binding is kept` errors. An application can branch on it instead of matching the error text. Before v2.1.274, the result carried no `startup_failure_reason` field. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -111,7 +111,7 @@ Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in these cases: * The worktree still holds work: changed or untracked files, or unpushed commits. - * Claude Code can’t determine which filter drivers the repository config defines, in any of the three cases that also block worktree creation. + * One of the four cases that also block worktree creation applies: Claude Code can’t determine which filter drivers the repository config defines, or finds a setting there it can’t switch off. * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. @@ -305,11 +305,12 @@ Git LFS files are pointer files in a worktree Claude Code created -If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In three rare cases, Claude Code can’t tell which filter drivers the repository’s config defines, and creates no worktree at all. Match the error to its fix: +If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In four rare cases, Claude Code creates no worktree at all: it can’t tell which filter drivers the repository’s config defines, or it finds a setting there it can’t switch off. Match the error to its fix: * **`Could not read the repository git config to neutralize filter drivers`** : Claude Code couldn’t read the repository’s `.git/config`, for example because of its permissions. Fix that and retry. * **`The repository git config defines a filter driver whose name cannot be neutralized (contains "=" or a newline)`** : rename or remove that filter driver in `.git/config` and retry. * **`The repository git config has a conditional include (includeIf)`** : move the settings the `includeIf` in `.git/config` pulls in directly into that file, remove the `includeIf`, and retry. An `includeIf` in your global git config doesn’t trigger this. + * **`Git was not run: the repository's own git config sets<key>`**: the message names a key that points Git LFS at a program to run, such as `lfs.customtransfer.<name>.path` or `lfs.standalonetransferagent`. If that setting is yours, move it to your global git config. If you don’t recognize it, remove it from the repository’s git config, since a tool or checkout you don’t trust may have written it. Retry once the key is gone from the repository’s config. ###
modified
--- a/worktrees.md +++ b/worktrees.md @@ -1,6 +1,6 @@ A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so one session can build a feature while a second fixes a bug. -Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), every new session gets its own worktree automatically. +Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), select the **worktree** option when you start a session to give it its own worktree. Worktrees are one of several ways to run Claude in parallel. They isolate file edits. [Subagents](</docs/en/sub-agents>) split work up inside one session, and [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions in your worktrees. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -317,7 +317,7 @@ Claude Code refuses to use a worktree -An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages: +An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. A directory with no git metadata at all, such as one your `WorktreeCreate` hook creates, passes the check only when no git repository contains it. If the hook creates the directory inside a repository, git resolves it to that repository’s checkout and Claude Code refuses it with the `git resolves its working tree to` message, so have the hook create its directories outside any repository. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages: * **Says`launch from the parent checkout` or `Run the resume from the project checkout`**: you launched Claude Code from inside the worktree. Launch from the main checkout instead; the worktree needs no recreation. * **Says`it cannot be resumed or re-entered`**: nothing in this session vouches for the worktree from where you launched. Recreate it; the directory and its work remain on disk for manual recovery, and when the worktree has a parent checkout, resuming from there also works. @@ -332,7 +332,7 @@ The session resumes outside its worktree -When an interactive resume can’t return the session to its worktree, Claude Code says so with one of the messages below. +When you resume a session interactively and Claude Code can’t return it to its worktree, Claude Code says so with one of the messages below. When Claude Code clears the worktree binding, it records the clear in the session transcript. If you [suppress transcript writes](</docs/en/sessions#where-transcripts-are-stored>), the message says instead that the binding could not be cleared and that Claude Code will re-check the worktree on a later resume. Message starts with| What happened and what to do ---|--- @@ -341,9 +341,9 @@ `Did not re-enter your worktree <path>`| Claude Code refused the worktree binding as unsafe; it clears the binding and the session continues without isolation. The message includes the specific refusal: match it under Claude Code refuses to use a worktree, since the fix is recreation for some refusals and a path change for others. `Could not re-enter your worktree <path>`| Claude Code couldn’t vouch for the worktree from where you launched, most commonly because you launched from inside it; the binding is kept. The rest of the message names the fix; match it under Claude Code refuses to use a worktree. -In [non-interactive mode](</docs/en/headless>) with `-p`, and on resumes the [Agent SDK](</docs/en/agent-sdk/sessions>) runs, Claude Code stops the resume with a stderr error for every refusal except a gone worktree, instead of continuing without isolation, and the messages take different shapes from the ones in the table above: - - * `Error: cannot resume into worktree <path>: ...This session was not started.` for a refusal the table shows as `Did not re-enter` +In [non-interactive mode](</docs/en/headless>) with `-p`, and on resumes that the [Agent SDK](</docs/en/agent-sdk/sessions>) runs, Claude Code stops the resume with a stderr error for every refusal except a gone worktree, instead of continuing without isolation. With `--output-format stream-json`, the refusal also arrives on stdout as a `result` message with subtype `error_during_execution` whose `errors` array carries the same text, so an Agent SDK application receives the reason rather than only a non-zero exit. Before v2.1.260, a worktree-resume refusal produced no `result` message. The messages take different shapes from the interactive messages in the table: + + * `Error: cannot resume into worktree <path>: ...This session was not started.` for a refusal the table shows as `Did not re-enter`. Claude Code clears the worktree binding before exiting, and the error says so; the next time you resume the conversation, the session continues in the current directory without worktree isolation. Before v2.1.260, Claude Code didn’t write the cleared binding, so every retry of the same resume failed with the same error. If you [suppress transcript writes](</docs/en/sessions#where-transcripts-are-stored>), the clear can’t be saved. The error then says the same command will be refused again, and names `--fork-session` and starting a new conversation as ways to continue without the worktree. * `Error: could not verify worktree <path> for this resume, so the resume was aborted...` for `Could not verify` * `Error: ...The worktree binding is kept.` for `Could not re-enter` * `Notice: the worktree <path> for this session no longer exists...` for a gone worktree; Claude Code prints it and continues the session, as an interactive resume does
modified
--- a/worktrees.md +++ b/worktrees.md @@ -79,7 +79,7 @@ * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. - * **Command shape** : Claude Code blocks a Bash or Monitor command it can’t verify stays inside the worktree, even when the command runs no git at all. Claude Code refuses shell constructs it can’t trace without running them, such as brace expansion and heredocs with unquoted delimiters. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. + * **Command shape** : Claude Code blocks a Bash or Monitor command when it can’t verify from the command text that any git the command runs stays inside the worktree, for example when the command name is computed at runtime or the syntax can’t be parsed. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -50,7 +50,7 @@ * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them -Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is really a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. +Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -2,7 +2,7 @@ Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), every new session gets its own worktree automatically. -Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](</docs/en/sub-agents>) and [agent teams](</docs/en/agent-teams>) coordinate the work itself. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. +Worktrees are one of several ways to run Claude in parallel. They isolate file edits. [Subagents](</docs/en/sub-agents>) split work up inside one session, and [cross-session messaging](</docs/en/cross-session-messaging>) lets Claude pass findings between the sessions in your worktrees. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. ## @@ -115,7 +115,7 @@ * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. -Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. Before v2.1.246, the sweep didn’t check for the marker, and could remove a worktree you created yourself when an old background-session record pointed at it. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. +Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. Before v2.1.246, the sweep didn’t check for the marker, and could remove a worktree you created yourself when an old background-session record pointed at it. While an agent is running, Claude Code holds a `git worktree lock` on its worktree so that concurrent cleanup can’t remove it, and releases the lock when the agent finishes. Claude Code holds the same lock on the worktree it created for a backgrounded session while the session runs, so the sweep leaves the worktree in place and `git worktree remove` refuses to remove it. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. If git refuses because the worktree is locked, run `git worktree unlock` on it first. ## @@ -217,7 +217,7 @@ * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. - * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and the other cases where Claude Code [keeps the local file in the starting directory](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). + * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and in the other cases where Claude Code [doesn’t use the repository root](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). @@ -356,9 +356,10 @@ See also -Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts and switching between the sessions you create: +Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts, passing findings between them, and switching between the sessions you create: * [Subagents](</docs/en/sub-agents>): delegate work to isolated agents within a session + * [Cross-session messaging](</docs/en/cross-session-messaging>): let the sessions in your worktrees pass findings to each other * [Agent teams](</docs/en/agent-teams>): coordinate multiple Claude sessions automatically * [Manage sessions](</docs/en/sessions>): name, resume, and switch between conversations * [Desktop parallel sessions](</docs/en/desktop#work-in-parallel-with-sessions>): worktree-backed sessions in the desktop app
modified
--- a/worktrees.md +++ b/worktrees.md @@ -108,7 +108,14 @@ Clean up subagent and background-session worktrees -A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. +Claude Code runs a periodic sweep that removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). When you [background](</docs/en/agent-view#send-the-session-to-the-background>) a `--worktree` session, its worktree becomes a background-session worktree that the sweep can remove. The sweep leaves a worktree in place in these cases: + + * The worktree still holds work: changed or untracked files, or unpushed commits. + * Claude Code can’t determine which filter drivers the repository config defines, in any of the three cases that also block worktree creation. + * The worktree belongs to a `--worktree` session you haven’t backgrounded, whatever its age. + * You created the worktree yourself with `git worktree add`, even if you then ran a `--worktree <name>` session in it and backgrounded that session. + +Claude Code writes a marker into the git metadata of every worktree it creates with git, and the sweep keeps any worktree without one, including a worktree a `WorktreeCreate` hook created. Before v2.1.246, the sweep didn’t check for the marker, and could remove a worktree you created yourself when an old background-session record pointed at it. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. ## @@ -296,6 +303,18 @@ ​ +Git LFS files are pointer files in a worktree Claude Code created + +If you set up [Git LFS](<https://git-lfs.com>) with `git lfs install --local`, a worktree that Claude Code creates contains LFS pointer files instead of the real files. The `--local` flag writes the LFS filter into the repository’s own `.git/config` rather than your global git config. A plain `git lfs install` writes to your global config and isn’t affected. The same applies to any other [filter driver](<https://git-scm.com/docs/gitattributes>) defined in the repository’s own config. Claude Code skips the repository’s own filter drivers when it creates a worktree because a filter driver is a shell command, and anything that can write to the repository, including Claude, could have put one there. Before v2.1.247, Claude Code ran those drivers during worktree creation. To get the real files, run `git lfs pull` inside the worktree. In three rare cases, Claude Code can’t tell which filter drivers the repository’s config defines, and creates no worktree at all. Match the error to its fix: + + * **`Could not read the repository git config to neutralize filter drivers`** : Claude Code couldn’t read the repository’s `.git/config`, for example because of its permissions. Fix that and retry. + * **`The repository git config defines a filter driver whose name cannot be neutralized (contains "=" or a newline)`** : rename or remove that filter driver in `.git/config` and retry. + * **`The repository git config has a conditional include (includeIf)`** : move the settings the `includeIf` in `.git/config` pulls in directly into that file, remove the `includeIf`, and retry. An `includeIf` in your global git config doesn’t trigger this. + +### + +​ + Claude Code refuses to use a worktree An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages:
modified
--- a/worktrees.md +++ b/worktrees.md @@ -161,7 +161,7 @@ Copy gitignored files into worktrees -A worktree is a fresh checkout, so untracked files like `.env` or `.env.local` from your main repository are not present. To copy them automatically when Claude creates a worktree, add a `.worktreeinclude` file to your project root. The file uses `.gitignore` syntax. Only files that match a pattern and are also gitignored are copied, so tracked files are never duplicated. This `.worktreeinclude` copies two env files and a secrets config into each new worktree: +A worktree is a fresh checkout, so untracked files like `.env` or `.env.local` from your main repository are not present. To copy them automatically when Claude creates a worktree, add a `.worktreeinclude` file to your project root. The file uses `.gitignore` syntax. Only files that match a pattern and are also gitignored are copied, so tracked files are never duplicated. If you write a pattern that starts with `**/` and the files you want are inside a directory that is gitignored as a whole, Claude Code copies them only when that directory itself matches the pattern, or when the first name after the `**/` is one of the names in the directory’s path. For example, if you write `**/.claude/skills/*.md`, that first name is `.claude`, so Claude Code copies the matching files out of an ignored `.claude/` directory. To copy files out of an ignored directory that a `**/` pattern doesn’t reach, name the directory in the pattern instead: write `vendor/**/config.json` rather than `**/config.json`. Before v2.1.239, Claude Code copied files out of a wholly ignored directory for a `**/` pattern only when the directory itself matched the pattern. This `.worktreeinclude` copies two env files and a secrets config into each new worktree: .worktreeinclude
modified
--- a/worktrees.md +++ b/worktrees.md @@ -108,7 +108,7 @@ Clean up subagent and background-session worktrees -A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. +A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings-reference#cleanupperioddays>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. ## @@ -124,7 +124,7 @@ Choose the base branch -New worktrees branch from the repository’s default branch, so most sessions don’t need this setting. Set `worktree.baseRef` in [settings](</docs/en/settings#worktree-settings>) to branch from your current work instead. The setting accepts two values: +New worktrees branch from the repository’s default branch, so most sessions don’t need this setting. Set `worktree.baseRef` in [settings](</docs/en/settings-reference#worktree>) to branch from your current work instead. The setting accepts two values: * `"fresh"` (default): branch from the repository’s default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote. * `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. @@ -210,7 +210,7 @@ * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. - * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). + * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. On Windows and the other cases where Claude Code [keeps the local file in the starting directory](</docs/en/settings#where-claude-code-looks-for-each-file>), the rule stays with that worktree. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). @@ -249,7 +249,7 @@ Non-git version control -Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#settings-files>): +Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#where-settings-live>): { "hooks": {
modified
--- a/worktrees.md +++ b/worktrees.md @@ -33,6 +33,11 @@ Ask Claude to create a worktree You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first, because the move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. + +**Hook paths don’t follow the worktree.** After Claude enters a worktree, Claude Code keeps `${CLAUDE_PROJECT_DIR}` in your [hooks](</docs/en/hooks#reference-scripts-by-path>) where it was and passes the worktree path to them a different way: + + * **`${CLAUDE_PROJECT_DIR}` stays put**: it still points at the project root where the session started, so a hook command such as `${CLAUDE_PROJECT_DIR}/.claude/hooks/check-style.sh` still runs the script in the main checkout. + * **`cwd` follows Claude**: the `cwd` field in the hook’s [input JSON](</docs/en/hooks#common-input-fields>) is the worktree root, and it moves again when Claude runs `cd`. Read it when a hook needs the worktree path. ## @@ -74,7 +79,7 @@ * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. - * **Command shape** : Claude Code blocks a Bash or Monitor command it can’t verify stays inside the worktree. The block applies even when the command runs no git at all. Claude Code refuses shell constructs it can’t statically trace, such as brace expansion and heredocs with unquoted delimiters. It tells Claude to break the command into plain, separate commands. You can’t turn this check off. + * **Command shape** : Claude Code blocks a Bash or Monitor command it can’t verify stays inside the worktree, even when the command runs no git at all. Claude Code refuses shell constructs it can’t trace without running them, such as brace expansion and heredocs with unquoted delimiters. Claude Code tells Claude how to rewrite the refused command, such as splitting it into plain, separate commands. You can’t turn this check off. The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -205,7 +205,7 @@ * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. - * **Permission approvals** : choosing “Yes, don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). + * **Permission approvals** : choosing “Yes, and don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>).
modified
--- a/worktrees.md +++ b/worktrees.md @@ -45,7 +45,7 @@ * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them -Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees. Remove them with `git worktree remove`. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is really a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. +Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees, and Claude Code leaves the lock it took on each one at creation in place until a later session’s stale-lock sweep releases it. To remove one, run `git worktree remove`; if git refuses because the worktree is locked, run `git worktree unlock` on it first. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is really a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. ## @@ -138,9 +138,17 @@ Branch from a pull request -To branch from a specific pull request, pass `--worktree` the PR number prefixed with `#`, or a full GitHub pull request URL. Claude Code fetches `pull/<number>/head` from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`. Quote the argument so your shell doesn’t treat `#` as the start of a comment: +To branch from a specific pull request or merge request, pass `--worktree` the number prefixed with `#`, a GitHub pull request URL, or a GitLab merge request URL such as `https://gitlab.com/group/repo/-/merge_requests/123`. Claude Code fetches that change’s head commit from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`. Quote the argument so your shell doesn’t treat `#` as the start of a comment: claude --worktree "#1234" + +Claude Code reads only the number from the URL. It always fetches from your repository’s `origin` remote, and picks the fetch path by `origin`’s host: + + * **github.com** : fetches `pull/<number>/head` + * **gitlab.com** : fetches `merge-requests/<number>/head` + * **GitHub Enterprise, self-managed GitLab, or any other host** : tries `pull/<number>/head` first, then `merge-requests/<number>/head` + +Before v2.1.233, Claude Code accepted only `#<number>` and GitHub-style pull request URLs for `--worktree`, and always fetched `pull/<number>/head`. ### @@ -168,9 +176,16 @@ * It has no uncommitted changes or untracked files. * It is still on the branch Claude Code created for it. - * It has no commits of its own, or its pull request was merged and its remote branch deleted. - -Claude Code detects the merged case from git state alone: the remote branch the worktree pushed to no longer exists, and every commit in the worktree is already on the default branch. Anything else reopens at the old tip: a worktree that fails any of the conditions, one whose state can’t be verified, and any reuse when `worktree.baseRef` is `"head"` or the name is a pull request number. Before v2.1.208, a reused name always reopened the old worktree at its old tip. + * It has no commits of its own, or its pull request or merge request was merged and its remote branch deleted. + +Claude Code detects the merged case from git state alone: the remote branch the worktree pushed to no longer exists, and every commit in the worktree is already on the default branch. In every other case, Claude Code reopens the worktree at its old tip: + + * The worktree fails any of the conditions. + * Claude Code can’t verify the worktree’s state. + * `worktree.baseRef` is `"head"`. + * The name is a pull request or merge request reference. + +Before v2.1.208, when you reused a name, Claude Code always reopened the old worktree at its old tip. ###
modified
--- a/worktrees.md +++ b/worktrees.md @@ -262,7 +262,7 @@ Claude Code can’t enter the worktree at startup -When Claude Code can’t enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) prints something other than the directory it created, or when the directory was deleted after it was set up. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. +When Claude Code can’t enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) prints something other than the directory it created, or when the directory was deleted after it was set up. ###
modified
--- a/worktrees.md +++ b/worktrees.md @@ -69,13 +69,14 @@ How Claude Code enforces isolation -While a session is isolated in a worktree, whether you started it with `--worktree`, Claude entered one with `EnterWorktree`, or you resumed a worktree session, Claude Code blocks the tool calls listed below when they would reach the main checkout. The same enforcement covers every subagent Claude spawns from the isolated session, and it applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks; their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies three checks: +While a session is isolated in a worktree, Claude Code blocks the tool calls the checks below define. The same rules apply whether you started the session with `--worktree`, Claude entered a worktree with `EnterWorktree`, or you resumed a worktree session. The same enforcement covers every subagent Claude spawns from the isolated session. It applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks. Their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies four checks: * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. - * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout, whether through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. Claude Code also blocks a command it can’t verify stays inside the worktree. For PowerShell commands, Claude Code applies only the working-directory check. - -The checks apply to the repository you launched Claude Code from, including the main checkout a linked worktree is linked from. Claude sees each refusal as a tool error that names the worktree and says how to proceed. + * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout. The redirect can come through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. + * **Command shape** : Claude Code blocks a Bash or Monitor command it can’t verify stays inside the worktree. The block applies even when the command runs no git at all. Claude Code refuses shell constructs it can’t statically trace, such as brace expansion and heredocs with unquoted delimiters. It tells Claude to break the command into plain, separate commands. You can’t turn this check off. + +The checks apply to the repository you launched Claude Code from. They also cover the main checkout a linked worktree is linked from. For PowerShell commands, Claude Code applies only the working-directory check. Claude sees each refusal as a tool error that names the worktree and says how to proceed. ## @@ -102,7 +103,7 @@ Clean up subagent and background-session worktrees -A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting. The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. +A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, following the [retention sweep rules](</docs/en/claude-directory#cleaned-up-automatically>). The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -53,11 +53,29 @@ Resume a worktree session -When you resume a session that was inside a worktree, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](</docs/en/tools-reference>) tool. A resume that forks the session with `--fork-session` starts in the directory you launched Claude from and leaves the original session’s worktree untouched. If the worktree directory no longer exists, the session resumes in the directory you launched Claude from. +When you resume a session that was inside a worktree, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](</docs/en/tools-reference>) tool. Before returning the session to its worktree, Claude Code verifies that the worktree is still a checkout separate from the main one, and declines to re-enter a worktree that fails the check. For a git worktree, the check reads its git metadata. A worktree without git metadata, such as one a `WorktreeCreate` hook created, can pass the check; the cases Claude Code still refuses are listed with their recoveries under Claude Code refuses to use a worktree. For the messages and how to recover from each, see The session resumes outside its worktree. Where you launch from, and how you resume, change what Claude Code re-enters: + + * **Launch directory** : resume from the main checkout or another directory of the repository. Claude Code re-enters a worktree it created with git under `.claude/worktrees/` even when you launch from inside it. When you launch from inside any other worktree, Claude Code re-enters it only if it can vouch for it from there: a worktree that is its own repository, one without git metadata, or a launch from a subdirectory of a worktree you created with `git worktree add` declines, so launch those from the main checkout. + * **`--fork-session`** : the forked session starts in the directory you launched Claude from, and Claude Code leaves the original session’s worktree untouched. + * **Deleted worktree** : if the worktree directory no longer exists, Claude Code resumes the session in the directory you launched Claude from. It tells you the worktree is gone and clears the session’s worktree binding. Before v2.1.212, a non-interactive resume stayed in the starting directory and `ExitWorktree` reported that there was no active worktree session to exit. When Claude enters or exits a worktree that Claude Code created with git, the transcript follows: Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. Requires Claude Code v2.1.198 or later. + +## + +​ + +How Claude Code enforces isolation + +While a session is isolated in a worktree, whether you started it with `--worktree`, Claude entered one with `EnterWorktree`, or you resumed a worktree session, Claude Code blocks the tool calls listed below when they would reach the main checkout. The same enforcement covers every subagent Claude spawns from the isolated session, and it applies whether the session is interactive or runs in the [background](</docs/en/agent-view#how-file-edits-are-isolated>). Subagents that run in their own worktree carry the same checks; their version history is under [Write subagent files](</docs/en/sub-agents#write-subagent-files>). Claude Code applies three checks: + + * **File edits** : Claude Code blocks an `Edit`, `Write`, or `NotebookEdit` that targets a path in the main checkout. + * **Command working directory** : Claude Code blocks a Bash, PowerShell, or Monitor command whose working directory resolves to the main checkout, or whose working directory it can’t verify stays outside it. + * **Git redirects** : Claude Code blocks a Bash or Monitor command that redirects git into the main checkout, whether through `git -C`, `--git-dir`, a `GIT_DIR` or `GIT_WORK_TREE` variable, or a `cd` into the main checkout before running git. Claude Code also blocks a command it can’t verify stays inside the worktree. For PowerShell commands, Claude Code applies only the working-directory check. + +The checks apply to the repository you launched Claude Code from, including the main checkout a linked worktree is linked from. Claude sees each refusal as a tool error that names the worktree and says how to proceed. ## @@ -235,7 +253,7 @@ Troubleshooting -The errors below occur when Claude Code creates a worktree or enters one at startup. +Claude Code reports the errors below when it creates a worktree, enters one at startup, or returns a resumed session to one. ### @@ -252,6 +270,45 @@ Worktree creation fails on a symlinked path Claude Code refuses to create a worktree when `.claude`, `.claude/worktrees`, or the worktree directory itself is a symlink, and the error names the symlinked path. Remove the symlink and retry. Before v2.1.212, if the repository already contained a committed symlink at one of those paths, worktree creation followed it and could create files outside the repository. + +### + +​ + +Claude Code refuses to use a worktree + +An error starting `Refusing to use <path> as an isolation worktree` means Claude Code checked the directory’s git identity before adopting it as a session’s or subagent’s isolated checkout, and declined it. The check runs whether Claude Code is creating the worktree, entering an existing one, or reusing one from an earlier run. In most cases the rest of the message says the directory’s git metadata resolves into the main checkout: for example, its `.git` file points at the main repository’s own `.git` directory, or git resolves its working tree to the main checkout through a `core.worktree` redirect. From such a directory, an ordinary git command such as `git reset --hard` would act on the main checkout instead of the worktree. Claude Code also refuses when the directory has a `.git` entry it can’t read, rather than assuming the worktree is safe. Claude Code leaves the refused directory in place, since it may hold work. Match the message to its recovery, whether it follows `Refusing to use <path>` or appears in a resume message; some endings occur only in resume messages: + + * **Says`launch from the parent checkout` or `Run the resume from the project checkout`**: you launched Claude Code from inside the worktree. Launch from the main checkout instead; the worktree needs no recreation. + * **Says`it cannot be resumed or re-entered`**: nothing in this session vouches for the worktree from where you launched. Recreate it; the directory and its work remain on disk for manual recovery, and when the worktree has a parent checkout, resuming from there also works. + * **Says`it contains the protected checkout`**: the refused directory is a parent of your main checkout, such as your home directory. Don’t delete it. Change the worktree path, such as the path your `WorktreeCreate` hook returns or the `EnterWorktree` target, so the worktree doesn’t contain the checkout. + * **Says`the protected checkout <path> has a .git entry that could not be examined` or `has git metadata that could not be resolved`**: the problem is the main checkout’s git metadata, not the worktree’s. Don’t delete the worktree, and ignore the message’s trailing advice to recreate it, which doesn’t apply to these two endings. Repair the main checkout, for example a permissions problem or a git `dubious ownership` refusal on its `.git`, and retry. + * **Says`its recorded path has a network spelling`**: Claude Code never resumes into a worktree at a network path. Recreate the worktree at a local path. + * **Any other ending** : the message names the problem and its fix, such as removing a `core.worktree` redirect or recreating the worktree; follow it. Before deleting a directory whose message says its git identity could not be verified, address the named cause first, for example a symbolic link in the worktree’s path or git itself failing to run, since the directory may be healthy. When you do recreate, salvage any changes you need from the old directory first; it stays on disk. + +### + +​ + +The session resumes outside its worktree + +When an interactive resume can’t return the session to its worktree, Claude Code says so with one of the messages below. + +Message starts with| What happened and what to do +---|--- +`Your worktree <path> no longer exists`| The worktree directory was removed. The session continues in the current directory without isolation, and Claude Code clears the worktree binding. No action needed. +`Could not verify your worktree <path> this time`| Claude Code couldn’t verify the worktree, usually for a transient reason; the binding is kept, and the session continues in the current directory without isolation. Resume again to retry; if it keeps happening, enter the worktree in a new session and match the refusal message under Claude Code refuses to use a worktree, which can name the main checkout’s metadata rather than the worktree’s. +`Did not re-enter your worktree <path>`| Claude Code refused the worktree binding as unsafe; it clears the binding and the session continues without isolation. The message includes the specific refusal: match it under Claude Code refuses to use a worktree, since the fix is recreation for some refusals and a path change for others. +`Could not re-enter your worktree <path>`| Claude Code couldn’t vouch for the worktree from where you launched, most commonly because you launched from inside it; the binding is kept. The rest of the message names the fix; match it under Claude Code refuses to use a worktree. + +In [non-interactive mode](</docs/en/headless>) with `-p`, and on resumes the [Agent SDK](</docs/en/agent-sdk/sessions>) runs, Claude Code stops the resume with a stderr error for every refusal except a gone worktree, instead of continuing without isolation, and the messages take different shapes from the ones in the table above: + + * `Error: cannot resume into worktree <path>: ...This session was not started.` for a refusal the table shows as `Did not re-enter` + * `Error: could not verify worktree <path> for this resume, so the resume was aborted...` for `Could not verify` + * `Error: ...The worktree binding is kept.` for `Could not re-enter` + * `Notice: the worktree <path> for this session no longer exists...` for a gone worktree; Claude Code prints it and continues the session, as an interactive resume does + +The refusal ending embedded in each error is shared with the interactive notices, so it still matches its entry under Claude Code refuses to use a worktree. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -185,9 +185,9 @@ git worktree add ../project-feature-a -b feature-a -Create a worktree from an existing branch: - - git worktree add ../project-bugfix bugfix-123 +Create a worktree from an existing branch, replacing `fix-issue-456` with a branch that already exists in your repository: + + git worktree add ../project-bugfix fix-issue-456 Start Claude in the worktree:
modified
Show diff (311 lines)
--- a/worktrees.md +++ b/worktrees.md @@ -1,4 +1,8 @@ -A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so you can have Claude building a feature in one terminal while fixing a bug in a second. This page covers worktree isolation in the CLI. Everything below assumes a git repository. For other version control systems, see Non-git version control. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) creates a worktree for every new session automatically. Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](</docs/en/sub-agents>) and [agent teams](</docs/en/agent-teams>) coordinate the work itself. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. +A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so one session can build a feature while a second fixes a bug. + +Worktrees require a git repository; for other version control systems, configure hooks to replace the git logic. In the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>), every new session gets its own worktree automatically. + +Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](</docs/en/sub-agents>) and [agent teams](</docs/en/agent-teams>) coordinate the work itself. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. Most sessions need only the first two sections: start Claude in a worktree, then clean up when you exit. Return to the rest of the page when you need to resume a session, change how worktrees are created, or debug a failure. ## @@ -6,19 +10,11 @@ Start Claude in a worktree -Pass `--worktree` or `-w` to create an isolated worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<value>/` at your repository root, on a new branch named `worktree-<value>`: +Pass `--worktree` or `-w` with a name to create an isolated worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<name>/` at your repository root, on a new branch named `worktree-<name>`: claude --worktree feature-auth -To put worktrees somewhere else, configure a `WorktreeCreate` hook. Run the command again with a different name in another terminal to start a second isolated session: - - claude --worktree bugfix-123 - -If you omit the name, Claude generates one such as `bright-running-fox`: - - claude --worktree - -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Entering a path outside the repository’s `.claude/worktrees/` directory asks for your approval first, because it moves the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Worktrees work with [sandboxing](</docs/en/sandboxing#filesystem-isolation>) enabled: the sandbox allows writes to the main repository’s shared `.git` directory so commands such as `git commit` can update refs and the index from inside a linked worktree. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. Permission approvals are shared across worktrees the same way: choosing “Yes, don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. This covers worktrees created with `--worktree`, with `git worktree add`, and by the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). +Run the command again with a different name in another terminal to start a second isolated session. If you omit the name, Claude generates one such as `bright-running-fox`. Interactive runs require [workspace trust](</docs/en/security>): if you haven’t run Claude in the directory before, run `claude` once there to accept the trust dialog, or `--worktree` exits with an error prompting you to. Non-interactive runs with `-p` skip the trust check, so `claude -p --worktree` proceeds without it. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. @@ -26,9 +22,90 @@ ​ +Set up the worktree environment + +A worktree is a fresh checkout, so initialize your development environment there: ask Claude to install dependencies, or run your project’s setup yourself in the worktree directory under `.claude/worktrees/`. To carry gitignored files such as `.env` into every new worktree automatically, add a `.worktreeinclude` file. + +### + +​ + +Ask Claude to create a worktree + +You can also ask Claude to “work in a worktree” during a session, and it creates one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path; the previous worktree stays on disk untouched. When Claude enters a path outside the repository’s `.claude/worktrees/` directory, Claude Code asks for your approval first, because the move takes the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. + +## + +​ + +Clean up worktrees + +When you exit an interactive worktree session, Claude checks the worktree for work that removal would delete: changed or untracked files, and new commits. + + * **The worktree is clean** : for an unnamed session, Claude removes the worktree and its branch automatically. A [named](</docs/en/sessions#name-your-sessions>) session prompts you first so you can keep the worktree for later + * **The worktree has work in it** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, along with all the work in them + +Non-interactive runs with `-p` have no exit prompt, so Claude doesn’t clean up their worktrees. Remove them with `git worktree remove`. On Windows, removing a worktree doesn’t delete files outside it. If a folder inside the worktree is really a link to somewhere else, such as an NTFS junction or a directory symlink, Claude Code deletes only the link and keeps the folder it points to. Before v2.1.205, removing a worktree with a link nested in a subdirectory could delete the folder it pointed to. + +## + +​ + +Resume a worktree session + +When you resume a session that was inside a worktree, Claude Code returns the session to that worktree. This holds for interactive resumes, for `--continue` and `--resume` in [non-interactive mode](</docs/en/headless>) with `-p`, and for the Agent SDK. Back inside the worktree, Claude can still exit it with the [`ExitWorktree`](</docs/en/tools-reference>) tool. A resume that forks the session with `--fork-session` starts in the directory you launched Claude from and leaves the original session’s worktree untouched. If the worktree directory no longer exists, the session resumes in the directory you launched Claude from. + +Before v2.1.212, a non-interactive resume stayed in the starting directory and `ExitWorktree` reported that there was no active worktree session to exit. + +When Claude enters or exits a worktree that Claude Code created with git, the transcript follows: Claude Code records the session under the session’s new working directory, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find it there. Exiting moves it back the same way. A worktree created by a `WorktreeCreate` hook keeps its transcript at the launch directory. Requires Claude Code v2.1.198 or later. + +## + +​ + +Isolate subagents with worktrees + +Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or make the isolation permanent for a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to its frontmatter. This subagent in `.claude/agents/` always runs in its own worktree: + + --- + name: refactorer + description: Applies mechanical refactors across many files + isolation: worktree + --- + + Apply the requested refactor across every affected file, then run the tests + and report the results. + +Each subagent gets a temporary worktree that Claude Code removes automatically when the subagent finishes without changes; a worktree with changes stays on disk until the periodic sweep below can remove it without losing work. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. + +### + +​ + +Clean up subagent and background-session worktrees + +A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting. The sweep skips a worktree that still holds work: changed or untracked files, or unpushed commits. It never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. The sweep never releases a lock you set yourself with `git worktree lock`. Before v2.1.210, a lock left by a killed session stayed in place until you ran `git worktree unlock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. + +## + +​ + +Customize worktree creation + +Claude Code’s defaults for creating worktrees cover most sessions: it creates them under `.claude/worktrees/`, branches them from your repository’s default branch, and checks out only tracked files. The options in this section change those defaults. + +### + +​ + Choose the base branch -Worktrees branch from your repository’s default branch, `origin/HEAD`, so they start from a clean tree matching the remote. When nothing has fetched the repository in the last 24 hours, Claude Code refreshes `origin/HEAD` with a fetch of the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. The refresh requires Claude Code v2.1.208 or later; before that, a fresh worktree used whatever `origin/HEAD` was already cached locally. To always branch from local `HEAD` instead, set `worktree.baseRef` to `"head"` in [settings](</docs/en/settings#worktree-settings>). Setting `baseRef` to `"head"` makes new worktrees carry your unpushed commits and feature-branch state, which is useful when isolating subagents that need to operate on in-progress work. When the session runs inside a linked worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. The setting accepts only `"fresh"` or `"head"`, not arbitrary git refs: +New worktrees branch from the repository’s default branch, so most sessions don’t need this setting. Set `worktree.baseRef` in [settings](</docs/en/settings#worktree-settings>) to branch from your current work instead. The setting accepts two values: + + * `"fresh"` (default): branch from the repository’s default branch on the remote, usually `main`, so the worktree starts from a clean tree matching the remote. + * `"head"`: branch from your current local `HEAD`, so the worktree carries your unpushed commits and feature-branch state. Use this when isolating subagents that need to operate on in-progress work. Inside a worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. + +You can’t set `worktree.baseRef` to a branch name. To start a worktree from a specific existing branch, create it with git directly. For a `"fresh"` base, Claude Code keeps `origin/HEAD` current: when the repository hasn’t been fetched in the last 24 hours, it fetches the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. Before v2.1.208, a fresh worktree used whatever `origin/HEAD` was already cached locally. This example makes every new worktree branch from your current work: { "worktree": { @@ -36,27 +113,17 @@ } } -To branch from a specific pull request, pass the PR number prefixed with `#`, or a full GitHub pull request URL. Claude Code fetches `pull/<number>/head` from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`: +### + +​ + +Branch from a pull request + +To branch from a specific pull request, pass `--worktree` the PR number prefixed with `#`, or a full GitHub pull request URL. Claude Code fetches `pull/<number>/head` from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`. Quote the argument so your shell doesn’t treat `#` as the start of a comment: claude --worktree "#1234" -For full control over how worktrees are created, configure a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>), which replaces the default `git worktree` logic entirely. - -### - -​ - -Reuse a worktree name - -Reusing a worktree name whose directory already exists resumes that worktree. A resumed worktree resets to the current base instead of resuming at its old tip when all of the following hold: - - * It has no uncommitted changes or untracked files. - * It is still on the branch Claude Code created for it. - * It never committed, or its pull request was merged and its remote branch deleted. - -Before v2.1.208, a reused name always resumed the old worktree at its old tip. - -## +### ​ @@ -70,43 +137,43 @@ .env.local config/secrets.json -This applies to worktrees created with `--worktree`, subagent worktrees, and parallel sessions in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). - -## - -​ - -Isolate subagents with worktrees - -Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or set it permanently on a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to the frontmatter. Each subagent gets a temporary worktree that is removed automatically when the subagent finishes without changes. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. - -## - -​ - -Clean up worktrees - -When you exit a worktree session, cleanup depends on whether you made changes: - - * **No uncommitted changes, no untracked files, and no new commits** : the worktree and its branch are removed automatically. If the session has a [name](</docs/en/sessions#name-your-sessions>), Claude prompts instead so you can keep the worktree for later - * **Uncommitted changes, untracked files, or new commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding any uncommitted changes, untracked files, and commits - * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` - -### - -​ - -Clean up subagent and background-session worktrees - -A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. The sweep never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. Before v2.1.210, that stale lock stayed in place until you ran `git worktree unlock`. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. - -### - -​ - -Worktree removal on Windows - -On Windows, before removing a worktree, Claude Code removes any NTFS junction or directory symlink at any depth inside it as a link entry, so removing the worktree doesn’t delete the files a link points to. Before v2.1.205, Claude Code removed only top-level links as link entries, and removing a worktree with a junction nested in a subdirectory could delete the contents of the directory the link pointed to outside the worktree. +This applies to every worktree Claude Code creates with git: `--worktree` worktrees, subagent worktrees, and parallel sessions in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). With a `WorktreeCreate` hook, copy the files inside the hook script. + +### + +​ + +Reuse a worktree name + +Passing `--worktree` a name whose directory already exists opens that existing worktree instead of creating a new one. With the default `"fresh"` base, a reopened worktree resets to the repository’s default branch instead of continuing at its old tip when all of the following hold: + + * It has no uncommitted changes or untracked files. + * It is still on the branch Claude Code created for it. + * It has no commits of its own, or its pull request was merged and its remote branch deleted. + +Claude Code detects the merged case from git state alone: the remote branch the worktree pushed to no longer exists, and every commit in the worktree is already on the default branch. Anything else reopens at the old tip: a worktree that fails any of the conditions, one whose state can’t be verified, and any reuse when `worktree.baseRef` is `"head"` or the name is a pull request number. Before v2.1.208, a reused name always reopened the old worktree at its old tip. + +### + +​ + +Replace worktree creation with a hook + +Configure a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) to replace the default `git worktree` logic entirely, including placing worktrees somewhere other than `.claude/worktrees/`. For a complete example, see Non-git version control. + +## + +​ + +What worktrees share with the main checkout + +A worktree gets its own files and branch, but it shares the repository’s `.git` directory, project-scope plugins, and saved permission approvals with the main checkout: + + * **The repository’s`.git` directory**: git commands in a worktree write to the main repository’s shared `.git` directory, and [sandboxing](</docs/en/sandboxing#filesystem-isolation>) allows those writes, so commands such as `git commit` work from inside a worktree with the sandbox enabled. + * **Plugins** : plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. Requires Claude Code v2.1.200 or later. + * **Permission approvals** : choosing “Yes, don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). + +All three apply whether you create the worktree with `--worktree`, with `git worktree add`, or through the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). ## @@ -114,7 +181,7 @@ Manage worktrees manually -For full control over worktree location and branch configuration, create worktrees with Git directly. This is useful when you need to check out a specific existing branch or place the worktree outside the repository. Create a worktree on a new branch: +Create worktrees with Git directly when you need to check out a specific existing branch or place the worktree outside the repository. Create a worktree on a new branch: git worktree add ../project-feature-a -b feature-a @@ -124,7 +191,8 @@ Start Claude in the worktree: - cd ../project-feature-a && claude + cd ../project-feature-a + claude List your worktrees: @@ -134,7 +202,7 @@ git worktree remove ../project-feature-a -See the [Git worktree documentation](<https://git-scm.com/docs/git-worktree>) for the full command reference. Remember to initialize your development environment in each new worktree: install dependencies, set up virtual environments, or run whatever your project’s setup requires. +See the [Git worktree documentation](<https://git-scm.com/docs/git-worktree>) for the full command reference. ## @@ -142,7 +210,7 @@ Non-git version control -Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from stdin, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#settings-files>): +Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from the JSON on stdin with `jq`, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#settings-files>): { "hooks": { @@ -165,6 +233,30 @@ ​ +Troubleshooting + +The errors below occur when Claude Code creates a worktree or enters one at startup. + +### + +​ + +Claude Code can’t enter the worktree at startup + +When Claude Code can’t enter the worktree directory at startup, it prints an error naming the path and exits with code 1. This can happen when a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) prints something other than the directory it created, or when the directory was deleted after it was set up. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. + +### + +​ + +Worktree creation fails on a symlinked path + +Claude Code refuses to create a worktree when `.claude`, `.claude/worktrees`, or the worktree directory itself is a symlink, and the error names the symlinked path. Remove the symlink and retry. Before v2.1.212, if the repository already contained a committed symlink at one of those paths, worktree creation followed it and could create files outside the repository. + +## + +​ + See also Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts and switching between the sessions you create:
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Entering a path outside the repository’s `.claude/worktrees/` directory asks for your approval first, because it moves the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Worktrees work with [sandboxing](</docs/en/sandboxing#filesystem-isolation>) enabled: the sandbox allows writes to the main repository’s shared `.git` directory so commands such as `git commit` can update refs and the index from inside a linked worktree. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Entering a path outside the repository’s `.claude/worktrees/` directory asks for your approval first, because it moves the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Worktrees work with [sandboxing](</docs/en/sandboxing#filesystem-isolation>) enabled: the sandbox allows writes to the main repository’s shared `.git` directory so commands such as `git commit` can update refs and the index from inside a linked worktree. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. Permission approvals are shared across worktrees the same way: choosing “Yes, don’t ask again” for a Bash command in a worktree session saves the rule to the main checkout’s `.claude/settings.local.json`, so it applies in the main checkout and in every other worktree of the repository, and it survives the worktree’s removal. This covers worktrees created with `--worktree`, with `git worktree add`, and by the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). Before v2.1.211, an approval granted in a worktree was saved inside that worktree, didn’t apply elsewhere, and was lost when the worktree was removed. See [where approvals are saved](</docs/en/permissions#permission-system>). Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. @@ -92,7 +92,21 @@ * **Uncommitted changes, untracked files, or new commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding any uncommitted changes, untracked files, and commits * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` -Worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) are removed automatically once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. On Windows, before removing a worktree, Claude Code removes any NTFS junction or directory symlink at any depth inside it as a link entry, so removing the worktree doesn’t delete the files a link points to. Before v2.1.205, Claude Code removed only top-level links as link entries, and removing a worktree with a junction nested in a subdirectory could delete the contents of the directory the link pointed to outside the worktree. +### + +​ + +Clean up subagent and background-session worktrees + +A periodic sweep removes worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. The sweep never removes worktrees you create with `--worktree`. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. The sweep also releases a lock Claude Code set for a session whose process has exited, so a killed background session doesn’t leave its worktree permanently locked. Before v2.1.210, that stale lock stayed in place until you ran `git worktree unlock`. The sweep never releases a lock you set yourself with `git worktree lock`. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. + +### + +​ + +Worktree removal on Windows + +On Windows, before removing a worktree, Claude Code removes any NTFS junction or directory symlink at any depth inside it as a link entry, so removing the worktree doesn’t delete the files a link points to. Before v2.1.205, Claude Code removed only top-level links as link entries, and removing a worktree with a junction nested in a subdirectory could delete the contents of the directory the link pointed to outside the worktree. ## @@ -128,7 +142,7 @@ Non-git version control -Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from stdin, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory: +Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from stdin, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory. Add the configuration to your [`settings.json`](</docs/en/settings#settings-files>): { "hooks": {
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Entering a path outside the repository’s `.claude/worktrees/` directory asks for your approval first, because it moves the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Entering a path outside the repository’s `.claude/worktrees/` directory asks for your approval first, because it moves the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Worktrees work with [sandboxing](</docs/en/sandboxing#filesystem-isolation>) enabled: the sandbox allows writes to the main repository’s shared `.git` directory so commands such as `git commit` can update refs and the index from inside a linked worktree. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. @@ -28,7 +28,7 @@ Choose the base branch -Worktrees branch from your repository’s default branch, `origin/HEAD`, so they start from a clean tree matching the remote. When nothing has fetched the repository in the last 24 hours, Claude Code refreshes `origin/HEAD` with a fetch of the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. The refresh requires Claude Code v2.1.208 or later; before that, a fresh worktree used whatever `origin/HEAD` was already cached locally. To always branch from local `HEAD` instead, set `worktree.baseRef` to `"head"` in [settings](</docs/en/settings#worktree-settings>). Setting `baseRef` to `"head"` makes new worktrees carry your unpushed commits and feature-branch state, which is useful when isolating subagents that need to operate on in-progress work. The setting accepts only `"fresh"` or `"head"`, not arbitrary git refs: +Worktrees branch from your repository’s default branch, `origin/HEAD`, so they start from a clean tree matching the remote. When nothing has fetched the repository in the last 24 hours, Claude Code refreshes `origin/HEAD` with a fetch of the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. The refresh requires Claude Code v2.1.208 or later; before that, a fresh worktree used whatever `origin/HEAD` was already cached locally. To always branch from local `HEAD` instead, set `worktree.baseRef` to `"head"` in [settings](</docs/en/settings#worktree-settings>). Setting `baseRef` to `"head"` makes new worktrees carry your unpushed commits and feature-branch state, which is useful when isolating subagents that need to operate on in-progress work. When the session runs inside a linked worktree, `"head"` resolves to that worktree’s `HEAD`, not the main checkout’s. The setting accepts only `"fresh"` or `"head"`, not arbitrary git refs: { "worktree": {
modified
--- a/worktrees.md +++ b/worktrees.md @@ -28,7 +28,7 @@ Choose the base branch -Worktrees branch from your repository’s default branch, `origin/HEAD`, so they start from a clean tree matching the remote. If no remote is configured or the fetch fails, the worktree falls back to your current local `HEAD`. To always branch from local `HEAD` instead, set `worktree.baseRef` to `"head"` in [settings](</docs/en/settings#worktree-settings>). Setting `baseRef` to `"head"` makes new worktrees carry your unpushed commits and feature-branch state, which is useful when isolating subagents that need to operate on in-progress work. The setting accepts only `"fresh"` or `"head"`, not arbitrary git refs: +Worktrees branch from your repository’s default branch, `origin/HEAD`, so they start from a clean tree matching the remote. When nothing has fetched the repository in the last 24 hours, Claude Code refreshes `origin/HEAD` with a fetch of the default branch, capped at five seconds, and uses the locally cached ref if the fetch fails. If no remote is configured, or `origin/HEAD` isn’t cached locally and can’t be fetched, the worktree falls back to your current local `HEAD`. The refresh requires Claude Code v2.1.208 or later; before that, a fresh worktree used whatever `origin/HEAD` was already cached locally. To always branch from local `HEAD` instead, set `worktree.baseRef` to `"head"` in [settings](</docs/en/settings#worktree-settings>). Setting `baseRef` to `"head"` makes new worktrees carry your unpushed commits and feature-branch state, which is useful when isolating subagents that need to operate on in-progress work. The setting accepts only `"fresh"` or `"head"`, not arbitrary git refs: { "worktree": { @@ -41,6 +41,20 @@ claude --worktree "#1234" For full control over how worktrees are created, configure a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>), which replaces the default `git worktree` logic entirely. + +### + +​ + +Reuse a worktree name + +Reusing a worktree name whose directory already exists resumes that worktree. A resumed worktree resets to the current base instead of resuming at its old tip when all of the following hold: + + * It has no uncommitted changes or untracked files. + * It is still on the branch Claude Code created for it. + * It never committed, or its pull request was merged and its remote branch deleted. + +Before v2.1.208, a reused name always resumed the old worktree at its old tip. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Entering a path outside the repository’s `.claude/worktrees/` directory asks for your approval first, because it moves the session’s working directory, write access, and project configuration such as `CLAUDE.md` and settings to that location. An `EnterWorktree` [permission rule](</docs/en/permissions>) or choosing “don’t ask again” doesn’t suppress this prompt; only `bypassPermissions` mode skips it. Before v2.1.206, Claude could enter any existing worktree path without asking. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. If Claude Code can’t enter the worktree directory at startup, for example because a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>) printed something other than the directory it created, or because the directory was deleted after it was set up, Claude Code prints an error naming the path and exits with code 1. Before v2.1.205, this crashed the session, and with `-p` it stalled for about 30 seconds before exiting with code 0. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. @@ -78,7 +78,7 @@ * **Uncommitted changes, untracked files, or new commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding any uncommitted changes, untracked files, and commits * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` -Worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) are removed automatically once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. +Worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) are removed automatically once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. On Windows, before removing a worktree, Claude Code removes any NTFS junction or directory symlink at any depth inside it as a link entry, so removing the worktree doesn’t delete the files a link points to. Before v2.1.205, Claude Code removed only top-level links as link entries, and removing a worktree with a junction nested in a subdirectory could delete the contents of the directory the link pointed to outside the worktree. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. Plugins installed at [project scope](</docs/en/plugins-reference#plugin-installation-scopes>) from the main checkout also load in worktrees of the same repository, so you don’t need to reinstall them per worktree. This applies whether you create the worktree with `--worktree` or with `git worktree add`. Requires Claude Code v2.1.200 or later. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. As of v2.1.198, entering or exiting a worktree also relocates the session transcript to that directory’s project storage, the same way [`/cd`](</docs/en/commands>) does, so `/desktop` and `--resume` find the session there afterward. Worktrees created by a `WorktreeCreate` hook are excluded and keep the transcript at the launch directory. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout.
modified
--- a/worktrees.md +++ b/worktrees.md @@ -18,7 +18,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Before using `--worktree` in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first, including when combined with `-p`. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Before using `--worktree` interactively in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first. Non-interactive runs with `-p` skip the [trust check](</docs/en/security>), so `claude -p --worktree` proceeds without it. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. @@ -78,7 +78,7 @@ * **Uncommitted changes, untracked files, or new commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding any uncommitted changes, untracked files, and commits * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` -Worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) are removed automatically once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. +Worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) are removed automatically once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. While an agent is running, Claude runs `git worktree lock` on its worktree so that concurrent cleanup cannot remove it. The lock is released when the agent finishes. To clean up a worktree that the sweep keeps, run `git worktree remove`, adding `--force` if the worktree has uncommitted changes or untracked files. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -1,9 +1,3 @@ -> ## Documentation Index -> -> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt> -> -> Use this file to discover all available pages before exploring further. - A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so you can have Claude building a feature in one terminal while fixing a bug in a second. This page covers worktree isolation in the CLI. Everything below assumes a git repository. For other version control systems, see Non-git version control. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) creates a worktree for every new session automatically. Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](</docs/en/sub-agents>) and [agent teams](</docs/en/agent-teams>) coordinate the work itself. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -24,7 +24,7 @@ claude --worktree -You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Before using `--worktree` in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first, including when combined with `-p`. +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Once in a worktree, Claude can switch directly to another one under `.claude/worktrees/` by calling `EnterWorktree` with the target path. The previous worktree stays on disk untouched. Before using `--worktree` in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first, including when combined with `-p`. Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. @@ -84,7 +84,7 @@ * **Uncommitted changes, untracked files, or new commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding any uncommitted changes, untracked files, and commits * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` -Subagent worktrees orphaned by a crash or interrupted run are removed at startup once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. +Worktrees that Claude created for subagents and [background sessions](</docs/en/agent-view#how-file-edits-are-isolated>) are removed automatically once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -70,7 +70,7 @@ Isolate subagents with worktrees -Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or set it permanently on a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to the frontmatter. Each subagent gets a temporary worktree that is removed automatically when the subagent finishes without changes. +Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or set it permanently on a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to the frontmatter. Each subagent gets a temporary worktree that is removed automatically when the subagent finishes without changes. Subagent worktrees use the same base branch as `--worktree`, so they branch from your repository’s default branch unless `worktree.baseRef` is set to `"head"`. ##
modified
--- a/worktrees.md +++ b/worktrees.md @@ -80,8 +80,8 @@ When you exit a worktree session, cleanup depends on whether you made changes: - * **No changes** : the worktree and its branch are removed automatically - * **Changes or commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding all uncommitted changes and commits + * **No uncommitted changes, no untracked files, and no new commits** : the worktree and its branch are removed automatically. If the session has a [name](</docs/en/sessions#name-your-sessions>), Claude prompts instead so you can keep the worktree for later + * **Uncommitted changes, untracked files, or new commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding any uncommitted changes, untracked files, and commits * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` Subagent worktrees orphaned by a crash or interrupted run are removed at startup once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep.
added
Show diff (156 lines)
--- a/worktrees.md +++ b/worktrees.md @@ -0,0 +1,153 @@ +> ## Documentation Index +> +> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt> +> +> Use this file to discover all available pages before exploring further. + +A [git worktree](<https://git-scm.com/docs/git-worktree>) is a separate working directory with its own files and branch, sharing the same repository history and remote as your main checkout. Running each Claude Code session in its own worktree means edits in one session never touch files in another, so you can have Claude building a feature in one terminal while fixing a bug in a second. This page covers worktree isolation in the CLI. Everything below assumes a git repository. For other version control systems, see Non-git version control. The [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>) creates a worktree for every new session automatically. Worktrees are one of several ways to run Claude in parallel. They isolate file edits, while [subagents](</docs/en/sub-agents>) and [agent teams](</docs/en/agent-teams>) coordinate the work itself. See [Run agents in parallel](</docs/en/agents>) to compare the approaches, or skip ahead to Isolate subagents with worktrees to use worktrees and subagents together. + +## + +​ + +Start Claude in a worktree + +Pass `--worktree` or `-w` to create an isolated worktree and start Claude in it. By default, the worktree is created under `.claude/worktrees/<value>/` at your repository root, on a new branch named `worktree-<value>`: + + claude --worktree feature-auth + +To put worktrees somewhere else, configure a `WorktreeCreate` hook. Run the command again with a different name in another terminal to start a second isolated session: + + claude --worktree bugfix-123 + +If you omit the name, Claude generates one such as `bright-running-fox`: + + claude --worktree + +You can also ask Claude to “work in a worktree” during a session, and it will create one with the [`EnterWorktree`](</docs/en/tools-reference>) tool. Before using `--worktree` in a directory for the first time, accept the workspace trust dialog by running `claude` once in that directory. If trust has not yet been accepted, `--worktree` exits with an error and prompts you to run `claude` in the directory first, including when combined with `-p`. + +Add `.claude/worktrees/` to your `.gitignore` so worktree contents don’t appear as untracked files in your main checkout. + +### + +​ + +Choose the base branch + +Worktrees branch from your repository’s default branch, `origin/HEAD`, so they start from a clean tree matching the remote. If no remote is configured or the fetch fails, the worktree falls back to your current local `HEAD`. To always branch from local `HEAD` instead, set `worktree.baseRef` to `"head"` in [settings](</docs/en/settings#worktree-settings>). Setting `baseRef` to `"head"` makes new worktrees carry your unpushed commits and feature-branch state, which is useful when isolating subagents that need to operate on in-progress work. The setting accepts only `"fresh"` or `"head"`, not arbitrary git refs: + + { + "worktree": { + "baseRef": "head" + } + } + +To branch from a specific pull request, pass the PR number prefixed with `#`, or a full GitHub pull request URL. Claude Code fetches `pull/<number>/head` from `origin` and creates the worktree at `.claude/worktrees/pr-<number>`: + + claude --worktree "#1234" + +For full control over how worktrees are created, configure a [`WorktreeCreate` hook](</docs/en/hooks#worktreecreate>), which replaces the default `git worktree` logic entirely. + +## + +​ + +Copy gitignored files into worktrees + +A worktree is a fresh checkout, so untracked files like `.env` or `.env.local` from your main repository are not present. To copy them automatically when Claude creates a worktree, add a `.worktreeinclude` file to your project root. The file uses `.gitignore` syntax. Only files that match a pattern and are also gitignored are copied, so tracked files are never duplicated. This `.worktreeinclude` copies two env files and a secrets config into each new worktree: + +.worktreeinclude + + .env + .env.local + config/secrets.json + +This applies to worktrees created with `--worktree`, subagent worktrees, and parallel sessions in the [desktop app](</docs/en/desktop#work-in-parallel-with-sessions>). + +## + +​ + +Isolate subagents with worktrees + +Subagents can run in their own worktrees so parallel edits don’t conflict. Ask Claude to “use worktrees for your agents”, or set it permanently on a [custom subagent](</docs/en/sub-agents#supported-frontmatter-fields>) by adding `isolation: worktree` to the frontmatter. Each subagent gets a temporary worktree that is removed automatically when the subagent finishes without changes. + +## + +​ + +Clean up worktrees + +When you exit a worktree session, cleanup depends on whether you made changes: + + * **No changes** : the worktree and its branch are removed automatically + * **Changes or commits exist** : Claude prompts you to keep or remove the worktree. Keeping preserves the directory and branch so you can return later. Removing deletes the worktree directory and its branch, discarding all uncommitted changes and commits + * **Non-interactive runs** : worktrees created with `--worktree` alongside `-p` are not cleaned up automatically since there is no exit prompt. Remove them with `git worktree remove` + +Subagent worktrees orphaned by a crash or interrupted run are removed at startup once they are older than your [`cleanupPeriodDays`](</docs/en/settings#available-settings>) setting, provided they have no uncommitted changes, no untracked files, and no unpushed commits. Worktrees you create with `--worktree` are never removed by this sweep. + +## + +​ + +Manage worktrees manually + +For full control over worktree location and branch configuration, create worktrees with Git directly. This is useful when you need to check out a specific existing branch or place the worktree outside the repository. Create a worktree on a new branch: + + git worktree add ../project-feature-a -b feature-a + +Create a worktree from an existing branch: + + git worktree add ../project-bugfix bugfix-123 + +Start Claude in the worktree: + + cd ../project-feature-a && claude + +List your worktrees: + + git worktree list + +Remove one when you’re done with it: + + git worktree remove ../project-feature-a + +See the [Git worktree documentation](<https://git-scm.com/docs/git-worktree>) for the full command reference. Remember to initialize your development environment in each new worktree: install dependencies, set up virtual environments, or run whatever your project’s setup requires. + +## + +​ + +Non-git version control + +Worktree isolation uses git by default. For SVN, Perforce, Mercurial, or other systems, configure [`WorktreeCreate` and `WorktreeRemove` hooks](</docs/en/hooks#worktreecreate>) to provide custom creation and cleanup logic. Because the hook replaces the default git behavior, `.worktreeinclude` is not processed when you use `--worktree`. Copy any local configuration files inside your hook script instead. This `WorktreeCreate` hook reads the worktree name from stdin, checks out a fresh SVN working copy, and prints the directory path so Claude Code can use it as the session’s working directory: + + { + "hooks": { + "WorktreeCreate": [ + { + "hooks": [ + { + "type": "command", + "command": "bash -c 'NAME=$(jq -r .name); DIR=\"$HOME/.claude/worktrees/$NAME\"; svn checkout https://svn.example.com/repo/trunk \"$DIR\" >&2 && echo \"$DIR\"'" + } + ] + } + ] + } + } + +Pair it with a `WorktreeRemove` hook to clean up when the session ends. See the [hooks reference](</docs/en/hooks#worktreecreate>) for the input schema and a removal example. + +## + +​ + +See also + +Worktrees handle file isolation. The related pages below cover delegating work into those isolated checkouts and switching between the sessions you create: + + * [Subagents](</docs/en/sub-agents>): delegate work to isolated agents within a session + * [Agent teams](</docs/en/agent-teams>): coordinate multiple Claude sessions automatically + * [Manage sessions](</docs/en/sessions>): name, resume, and switch between conversations + * [Desktop parallel sessions](</docs/en/desktop#work-in-parallel-with-sessions>): worktree-backed sessions in the desktop app