用于并行智能体的 Claude Code worktree:worktree skill
Dmitriy Solodukha,Caprock 开发者 · 发布于
测试于 (Claude Code 和 Codex)
Claude Code worktree 让并行智能体能在同一仓库中工作。worktree skill 负责设置、检查状态、合并回原分支和清理,从不使用 --force。
Claude Code worktree 让每个智能体在同一仓库中拥有独立的文件夹和分支;worktree skill 在 Claude Code、Codex、OpenCode 和 Cursor 中以相同方式完成设置和清理。一个任务、一个分支、一个文件夹:从最新的基线创建 worktree,复制项目所需的环境文件,为每个 worktree 分配独立的端口或数据库,运行冒烟检查,用一张表报告状态,合并回原分支,并且只删除无未提交改动且已合并的 worktree。
安装 worktree skill
每个智能体只需一条命令。skill 只有一个 SKILL.md;安装时不会运行任何内容。
将全部九个 skill 作为插件安装。在 Claude Code 中输入以下内容:
也可以只安装这个 skill,在终端中进入项目文件夹后运行:
添加 -g 即可为所有项目安装。
在终端中进入项目文件夹后运行:
添加 -g 即可为所有项目安装。
在终端中进入项目文件夹后运行:
添加 -g 即可为所有项目安装。 尚未在 OpenCode 上测试:这个 skill 是采用开放格式的纯文本指令,但还没有在 OpenCode 上实际运行验证。
在终端中进入项目文件夹后运行:
添加 -g 即可为所有项目安装。 尚未在 Cursor 上测试:这个 skill 是采用开放格式的纯文本指令,但还没有在 Cursor 上实际运行验证。
使用 worktree skill 的提示词
你的措辞与 skill 描述匹配时,智能体会选择它;直接指定 skill 名称更有把握。点击提示词即可复制。
worktree skill 如何运行 Claude Code worktree
- 创建前:
git worktree list和一个干净的 main 检出目录;使用 Caprock 时,recent_sessions会显示哪些分支正由运行中的会话占用。 - 创建:
git worktree add -b <task> ../<repo>.worktrees/<task> main,按任务命名,使用 kebab-case 格式。 - 确保可运行:复制被 gitignore 忽略的环境文件(不建符号链接),任务需要构建时运行项目自身的初始化流程,分开使用端口和数据库,并做一次快速检查。
- 随时查看状态:
git worktree list -v、git -C <path> status --short,以及领先于 main 的提交。 - 在主检出目录中 合并回去,或创建 pull request;遇到冲突就停止。
- 仅在
git merge-base --is-ancestor显示 merged 后才 移除,使用git worktree remove和git branch -d,它们会拒绝处理尚未合并的分支。
skill 中的每条 git 命令都已对照 git 自带的帮助核查(git 2.54.0,2026年11月29日)。
我们运行了什么,智能体做了什么
每个 skill 都于 2026年11月29日在专门创建的临时仓库中运行,并作为项目 skill 安装。这是一个小仓库,包含 calc.py,以及被 git 忽略的 .env。
Claude Code (claude -p --model sonnet)
Set up two git worktrees so two agents can work in parallel: one to add a subtract function to calc.py, one to make div raise a clear error on zero. Don't do the tasks themselves, just set up the worktrees and tell me their status.
调用了 Caprock 的 recent_sessions,从 main 分别创建了 ../app.worktrees/feat-subtract 和 ../app.worktrees/fix-div-zero,各自在独立分支上,在每个分支中运行了冒烟检查,并报告了 skill 要求的表格。它没有复制 .env,因为 calc.py 不读取这个文件,并说明了这一点。
| Worktree | Branch | State | Ahead of main | Next | | -------- | ------ | ----- | ------------- | ---- | | `../app.worktrees/feat-subtract` | `feat-subtract` | clean | 0 | work | | `../app.worktrees/fix-div-zero` | `fix-div-zero` | clean | 0 | work |
Codex (0.163.0,codex exec)
Clean up my git worktrees, I'm done with them.
先让一个 worktree 存在未提交的更改:它检查了状态和 --is-ancestor,移除干净的 worktree,并用 git branch -d 删除其分支;对于有未提交更改的 worktree,它引用 skill 的规则拒绝移除,没有使用 --force。
已测试的智能体
- Claude Code:测试于 2026年11月29日,使用
claude -p --model sonnet,skill 作为项目 skill 安装在.claude/skills/中。 - Codex:于 2026年11月29日使用 Codex 0.163.0(
codex exec)测试,skill 位于.agents/skills/。 - OpenCode 和 Cursor:未测试。此 skill 是以开放的 Agent Skills 格式编写的纯文本指令,但尚未在这两者上实际运行验证。
限制
- 只有任务需要构建或测试时才安装依赖:依赖来自网络,skill 会事先说明。
- 在 worktree 中编辑过的 Git 忽略文件,会在删除文件夹时一起删除;skill 会提醒你先将它们复制出来。
- 这里没有介绍 Codex 专有的 worktree 功能,因为没有核实过任何此类功能。
使用和不使用 Caprock 的情况
连接 Caprock MCP 服务器后,skill 会针对仓库调用 recent_sessions,查看哪些智能体会话正在运行、位于哪个分支,避免新任务占用正在使用的分支。未连接时,以 git worktree list 的分支列为准。Caprock 是免费开源应用,记录你电脑上的每个编程智能体会话。
完整的 SKILL.md
这是 dspv/skills 中修订版本 dfce799 的文件原样。手动安装时,将它保存在项目中:Claude Code 使用 .claude/skills/worktree/SKILL.md,Codex 使用 .agents/skills/worktree/SKILL.md。
--- name: worktree description: Set up and clean up git worktrees so several coding agents (or you and an agent) can work in parallel on one repository without stepping on each other. One task, one branch, one folder; copies env files, installs dependencies, checks status, merges back and removes the worktree safely. Use when the user asks for claude code worktrees, parallel agents or sessions on one repo, "work in a worktree", "spin up a worktree for this task", "clean up my worktrees", or "which worktrees have unfinished work". license: Apache-2.0 --- # Worktree A git worktree is a second checkout of the same repository: its own folder, its own branch, its own index, sharing one `.git` history. Two agents in two worktrees cannot overwrite each other's files. They can still collide on the same branch, the same port or the same database, so this skill fixes those too. Every command below is in git's own help pages (`git worktree --help` and the help of each other git command used; checked with git 2.54.0 on 2026-11-29). ## Safety rules (always) 1. **Never remove a worktree that has uncommitted or untracked work.** Check first (step 4). If it is dirty, stop and tell the user what is there. 2. **Never use `--force` or `-f`** on `git worktree add`, `remove` or `move`, and never `git branch -D`. Git refuses for a reason: a branch already checked out elsewhere, a dirty tree, a locked worktree. Report the refusal instead of overriding it. Only the user may decide to force, in their own words. 3. **Never delete a worktree folder with `rm -rf`.** Use `git worktree remove`; if a folder is already gone, `git worktree prune` cleans the record. 4. **One branch per worktree, one agent per worktree.** Git will not check out a branch that is already checked out in another worktree; do not work around it. 5. **Do not touch the main checkout** while agents work in worktrees, except to merge at the end. 6. **Do not remove a locked worktree.** A lock (`git worktree list` shows `locked`) means someone or some tool is still using it. Ask the user. ## 1. Before creating: look at what exists ```bash git worktree list # main checkout first, then each linked worktree git status --short # the main checkout should be clean before you branch from it ``` If a worktree for the same task already exists, reuse it instead of making a second one. **If the Caprock MCP tools are available** (server `caprock`), call `recent_sessions` with `repo` set to the repository to see which agent sessions are running here and on which branch. A session still active on a branch means that branch is taken: give the new task its own. Without those tools, the branch column of `git worktree list` is the record. (Caprock, <https://caprock.dev>, is a free, open-source app that runs locally and provides those tools.) ## 2. Create: one task, one branch, one folder Name everything after the task, short and in kebab-case: `fix-login-redirect`, `feat-csv-export`. The branch and the folder share the name. Where to put it, in order of preference: - **Beside the repository**: `../<repo>.worktrees/<task>`. Nothing nested inside the main checkout, so search tools, test runners and file watchers in the main checkout do not see a second copy of the code. - **Inside the repository**, when the agent may only write inside it: `.worktrees/<task>`, and hide the folder from git locally without editing a tracked file: `echo ".worktrees/" >> "$(git rev-parse --git-common-dir)/info/exclude"`. - **Claude Code's own location**, when Claude Code made it (see the last section): `.claude/worktrees/<task>`. Create it on a new branch from an up-to-date base (the user's default branch, usually `main`): ```bash git worktree add -b <task> ../<repo>.worktrees/<task> main ``` To continue an existing branch instead: `git worktree add ../<repo>.worktrees/<task> <branch>`. If git answers that the branch is already checked out in another worktree, stop (rule 4). ## 3. Make the worktree runnable A worktree is a fresh checkout of tracked files only. Before handing it to an agent: 1. **Env and local config files** (gitignored, so not in the new folder): copy the ones the project needs, such as `.env` or `.env.local`, from the main checkout. Copy, do not symlink, so one agent's change does not leak into the others. Never commit them. 2. **Dependencies**: run the project's own setup in the worktree, the one its README, Makefile or package manifest names (`npm ci`, `uv sync`, `bundle install` and the like). These fetch packages from the network: run them only when the task needs a working build or tests, and say so to the user. 3. **Shared resources**: give each worktree its own dev-server port and its own local database or data folder when the project allows it (usually an env variable). Two agents on one port or one database collide even in separate folders. 4. **Smoke check**: run the project's fastest check (a build, a lint, one test file) in the worktree, so a broken setup shows up now and not halfway through the task. Then start the agent with the worktree as its working directory, and give it the task, the branch name, and these rules: commit on this branch only, do not push unless told, do not touch other worktrees. ## 4. Check status (any time, and before every merge or removal) ```bash git worktree list -v # paths, branches, locked, prunable git -C <path> status --short # empty means no uncommitted work git -C <path> log --oneline main..HEAD # the task's commits not yet in main ``` A worktree is **done** when `status --short` is empty and its commits are what the task asked for. It is **dirty** when `status --short` prints anything (`??` lines are untracked files and count as work). `prunable` means the folder is gone; only `git worktree prune` is needed. ## 5. Merge back From the main checkout, with a clean status: ```bash git switch main git merge --no-ff <task> # or open a pull request from <task> ``` If the user's flow is pull requests, with their go-ahead push the branch and open one instead, and leave the worktree in place until it is merged. On a merge conflict, stop and show the conflicting files; do not resolve by taking one side wholesale. ## 6. Remove Only after step 4 shows the worktree clean and its commits are in the base branch: ```bash git merge-base --is-ancestor <task> main && echo merged # prints merged, or nothing git worktree remove ../<repo>.worktrees/<task> # refuses a dirty tree: good git branch -d <task> # refuses an unmerged branch: good git worktree prune -n -v # shows stale records; drop -n to clean ``` If `remove` refuses, the worktree has work: report it (rule 1). If `branch -d` refuses, the branch has commits that are not merged: report them with `git log --oneline main..<task>`. Copy out any gitignored file you still need (an `.env` you edited) before removing: git does not count those as work and they go with the folder. ## Output After each run, report one table, one row per worktree, then what is left for the user: | Worktree | Branch | State | Ahead of main | Next | | -------- | ------ | ----- | ------------- | ---- | `State` is `clean`, `dirty (N files)`, `locked` or `prunable`; `Ahead of main` is the count of `git log --oneline main..<branch>`; `Next` is `work`, `merge`, `remove` or `ask user`. Then list anything you refused to do (a dirty or locked worktree, an unmerged branch) and why. ## In Claude Code Claude Code has this built in (from its docs, code.claude.com/docs/en/worktrees, read on 2026-11-29): `claude --worktree <name>` (or `-w`) creates `.claude/worktrees/<name>/` on a new branch `worktree-<name>` and starts the session there; a `.worktreeinclude` file at the project root (gitignore syntax) lists gitignored files such as `.env` to copy into each new worktree; custom subagents can run in their own worktree with `isolation: worktree`. On exit, Claude Code asks before removing a worktree that has work. Non-interactive `claude -p` runs are not cleaned up: check and remove those with steps 4 and 6. Add `.claude/worktrees/` to the project's `.gitignore` (or `info/exclude`) so they do not show as untracked files.
关于 worktree skill 的问题
- Claude Code worktree 如何工作?
- `claude --worktree <name>`(或 `-w`)在新分支 `worktree-<name>` 上创建 `.claude/worktrees/<name>/`,并在那里启动会话。`.worktreeinclude` 文件列出需要复制进去的文件,如被 Git 忽略的 `.env`。
- worktree skill 为 Claude Code worktree 增加了什么?
- 它补全周边步骤:分配独立端口和数据库、执行冒烟检查、用一张状态表记录所有 worktree、安全合并,以及在清理时拒绝处理有未提交改动、已锁定或未合并的 worktree。它还会清理 `claude -p` 运行后留下的 worktree,这些不会由 Claude Code 删除。
- worktree skill 会删除我的工作成果吗?
- 它的指令明确禁止这些做法:不用 `--force`、`git branch -D` 或 `rm -rf`;遇到包含未提交或未跟踪文件的 worktree,只报告,不删除。
- 它能用于 Codex 吗?
- 可以,用普通的 Git 即可。在 2026年11月29日的测试中,Codex 0.163.0 用它清理了 worktree,并拒绝清理有未提交改动的那个。