Run Parallel AI Agents with Git Worktrees
说明与用途
使用 git worktree 在不产生编辑冲突的情况下并行运行 Claude Code 智能体:每个智能体获得独立的目录和分支。限制条件:每个工作树只能检出一个分支;删除时需要清理;订阅使用量共享,会话越多越容易达到限制;每个工作树需要独立的端口。
问题
Two Claude Code agents in one working tree step on each other's edits, causing conflicts.
结果
Parallel Claude Code agents can run without stepping on each other's edits by giving each session its own directory and branch via git worktree.
工作流
- cd todo-app
- git worktree add ../todo-app-login -b feature/login
- claude --worktree feature-auth
- Add .claude/worktrees/ to .gitignore
- Install dependencies in each new worktree
- Give each worktree its own dev-server port
- Clean up: interactive session removes unnamed worktree automatically; with changes use claude --worktree
<name>--resume or -p then git worktree remove
证据
A branch can be checked out in only one worktree at a time. A second one fails with fatal: 'feature/login' is already used by worktree at ...
git worktree remove refuses while modified or untracked files remain
If you delete a worktree with rm, clean up with git worktree prune -v
This creates .claude/worktrees/feature-auth/ on a new branch worktree-feature-auth. Run it in another terminal with a different name for a second session. Add .claude/worktrees/ to .gitignore. New worktrees branch from the default branch; set worktree.baseRef to "head" to branch from current work.
A worktree is a fresh checkout: no node_modules, no gitignored .env. Install dependencies in each one. Dev-server ports and local databases are shared, so give each worktree its own port.
On a subscription, usage is shared across sessions (five-hour and weekly limits), so more sessions hit limits sooner. The costs docs say agent teams use roughly 7x more tokens than standard sessions when teammates run in plan mode.
Interactive session with no changes: an unnamed worktree and its branch are removed automatically. With changes: you're asked to keep or remove; resume with claude --worktree <name> --resume. -p runs leave worktrees behind; remove them with git worktree remove (git worktree unlock first if locked)
- 记录日期: 2026-10-23T11:11:35.237Z